<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Nationality;
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 NationalityController extends Controller
{
    public function index()
    {
        $nationalities = [];
        
        return view('admin.nationalities.index', compact('nationalities'));

    }

    public function getNationalityList(Request $request) 
    {
        $sqlBuilder = Nationality::select([
            'nationalities.id',
            'nationalities.name',
            'nationalities.name_ar',
            'nationalities.status',
        ]);

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

    public function create(){
        $nationality = "";
        return view('admin.nationalities.create', compact('nationality'));

    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'status' => 'required|in:0,1',
        ];
    
        $validator = Validator::make($request->all(), $rules);
    
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        if ($request->id) {
            $nationality = Nationality::find($request->id);
    
            if (!$nationality) {
                return response()->json(['status' => 'error', 'message' => 'Nationality not found'], 404);
            }
    
            $existingNationality = Nationality::where('name', $request->name)
                ->where('id', '!=', $request->id)
                ->first();
    
            if ($existingNationality) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Nationality name already exists.']
                    ]
                ], 422);
            }
    
            $nationality->name = $request->name;
            $nationality->name_ar = $request->name_ar;
            $nationality->status = $request->status;
            $nationality->save();
    
            return response()->json(['status' => 'success', 'message' => 'Nationality updated successfully']);
        } else {
            $existingNationality = Nationality::where('name', $request->name)->first();
    
            if ($existingNationality) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Nationality name already exists.']
                    ]
                ], 422);
            }
    
            $nationality = Nationality::create([
                'name' => $request->name,
                'name_ar' => $request->name_ar,
                'status' => $request->status,
            ]);
    
            return response()->json(['status' => 'success', 'message' => 'Nationality added successfully', 'emirate' => $nationality]);
        }
    }
    


  
    public function edit($id) {
        $nationality = Nationality::findOrFail($id);
        return view('admin.nationalities.create', compact('nationality'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $emirate = Nationality::findOrFail($id);           
            $emirate->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Nationality deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Nationality 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) {
        $nationality = Nationality::find($id);

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