<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Emirate;
use App\Models\Country;
use App\Models\Emirates;
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 EmirateController extends Controller
{
    public function index()
    {
        $emirates = Emirate::orderBy('created_at', 'desc')->get();

        return view('admin.emirates.index', compact('emirates'));
    }

    public function getEmirateList(Request $request){
        $sqlBuilder = Emirate::select([
            'emirates.id',
            'emirates.name as emirate_name',
            'emirates.name_ar as emirate_name_ar',
            'emirates.status',
            'countries.name as country_name',
        ])->join('countries', 'emirates.country_id', '=', 'countries.id');

        return DataTables::of($sqlBuilder)
        ->filter(function ($query) use ($request) {
            if ($request->has('search') && !empty($request->search['value'])) {
                $query->where('emirates.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.emirates.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.emirates.edit', ['id' => $data->id]) . '">Edit</a></li>
                                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.emirates.destroy', ['id' => $data->id]) . '">Delete</a></li>
                                        </ul>
                                    </div>';
            return $html;
            })
            ->rawColumns(['country_name','status','action'])
            ->make(true);
    }

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

        return view('admin.emirates.create', compact('emirate','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) {
            $emirate = Emirate::find($request->id);
    
            if (!$emirate) {
                return response()->json(['status' => 'error', 'message' => 'Emirate not found'], 404);
            }
    
            $existingEmirate = Emirate::where('name', $request->name)
                ->where('id', '!=', $request->id)
                ->first();
    
            if ($existingEmirate) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Emirate name already exists.']
                    ]
                ], 422);
            }
    
            $emirate->name = $request->name;
            $emirate->name_ar = $request->name_ar;
            $emirate->status = $request->status;
            $emirate->country_id = $request->country_id;
            $emirate->save();
    
            return response()->json(['status' => 'success', 'message' => 'Emirate updated successfully']);
        } else {
            $existingEmirate = Emirate::where('name', $request->name)->first();
    
            if ($existingEmirate) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Emirate name already exists.']
                    ]
                ], 422);
            }
    
            $emirate = Emirate::create([
                'name' => $request->name,
                'name_ar' => $request->name_ar,
                'status' => $request->status,
                'country_id' => $request->country_id
            ]);
    
            return response()->json(['status' => 'success', 'message' => 'Emirate added successfully', 'emirate' => $emirate]);
        }
    }
  
    public function edit($id) {
        $emirate = Emirate::findOrFail($id);
        $countries = Country::where('status',1)->orderBy('created_at', 'desc')->get();
        return view('admin.emirates.create', compact('emirate','countries'));
    }

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

    public function statusChange(Request $request, $id) {
        $emirate = Emirate::find($id);

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