<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Cities;
use App\Models\Country;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\JsonResponse;
use Yajra\DataTables\Facades\DataTables;

class CitiesController extends Controller
{
    public function index()
    {
        $cities = Cities::orderBy('created_at', 'desc')->get();

        return view('admin.cities.index', compact('cities'));

    }

    public function getCityList(Request $request){
        $sqlBuilder = Cities::select([
            'cities.id',
            'cities.name as city_name',
            'cities.name_ar as city_name_ar',
            'cities.status as city_status',
            'countries.name as country_name',
        ])->join('countries', 'cities.country_id', '=', 'countries.id');

        return DataTables::of($sqlBuilder)
        ->filter(function ($query) use ($request) {
            if ($request->has('search') && !empty($request->search['value'])) {
                $query->where('cities.name', 'ilike', "%" . $request->search['value'] . "%");
            }
        })
            ->editColumn('status', function ($data) {
            return '<div class="status">
                        <div class="form-check form-switch ">
                            <input class="form-check-input status-checkbox" type="checkbox" role="switch" id="SwitchCheck4" data-url="'. route('admin.cities.status', ['id' => $data->id]) .'" data-id="'.$data->id.'" '.(!empty($data->status) && $data->status == 1 ? 'checked' : '').' />
                        </div>
                    </div>';
            })
            ->addColumn('action', function ($data) {
                $html = '<div class="dropdown">
                                        <a href="#" class="btn btn-soft-secondary btn-sm" role="button" id="dropdownMenuLink5" data-bs-toggle="dropdown" aria-expanded="false">
                                            <i class="ri-more-2-fill"></i>
                                        </a>
                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink5">
                                            <li><a class="dropdown-item" href="' . route('admin.cities.edit', ['id' => $data->id]) . '">Edit</a></li>
                                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.cities.destroy', ['id' => $data->id]) . '">Delete</a></li>
                                        </ul>
                                    </div>';
            return $html;
            })
            ->rawColumns(['country_name','status','action'])
            ->make(true);
    }

    public function create(){
        $city = "";
        $countries = Country::where('status',1)->orderBy('name', 'asc')->get();

        return view('admin.cities.create', compact('city','countries'));

    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'status' => 'required|in:0,1',
            'country_id' => 'required|exists:countries,id'
        ];
    
        $validator = Validator::make($request->all(), $rules);
    
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        if ($request->id) {
            $city = Cities::find($request->id);
    
            if (!$city) {
                return response()->json(['status' => 'error', 'message' => 'Emirate not found'], 404);
            }
    
            $existingCity = Cities::where('name', $request->name)
                ->where('id', '!=', $request->id)
                ->first();
    
            if ($existingCity) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The City name already exists.']
                    ]
                ], 422);
            }
    
            $city->name = $request->name;
            $city->name_ar = $request->name_ar;
            $city->status = $request->status;
            $city->country_id = $request->country_id;
            $city->save();
    
            return response()->json(['status' => 'success', 'message' => 'City updated successfully']);
        } else {
            $existingCity = Cities::where('name', $request->name)->first();
    
            if ($existingCity) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The City name already exists.']
                    ]
                ], 422);
            }
    
            $city = Cities::create([
                'name' => $request->name,
                'name_ar' => $request->name_ar,
                'status' => $request->status,
                'country_id' => $request->country_id
            ]);
    
            return response()->json(['status' => 'success', 'message' => 'City added successfully', 'emirate' => $city]);
        }
    }
  
    public function edit($id) {
        $city = Cities::findOrFail($id);
        $countries = Country::where('status',1)->orderBy('created_at', 'desc')->get();
        return view('admin.cities.create', compact('city','countries'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $emirate = Cities::findOrFail($id);           
            $emirate->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'City deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'City not found.'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while deleting the company.'
            ], 500);
        }
    }

    public function statusChange(Request $request, $id) {
        $city = Cities::find($id);

        if (!$city) {
            return response()->json([
                'status' => 'error',
                'message' => 'City not found.'
            ], 404);
        }
    
        $city->status = $request->status;
        $city->save();
    
        return response()->json([
            'status' => 'success',
            'message' => 'City status updated successfully.'
        ]);
    }
}
