<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Country;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Http\JsonResponse;
class CountryController extends Controller
{
    public function index()
    {
        $countries = Country::orderBy('created_at', 'desc')->get();
        
        return view('admin.country.index', compact('countries'));

    }

    public function getCountryList(Request $request){
        $sqlBuilder = Country::select([
            'countries.id',
            'countries.name',
            'countries.name_ar',
            'countries.flag_icon',
            'countries.status',
        ]);

        return DataTables::of($sqlBuilder)
            ->filter(function ($query) use ($request) {
                if ($request->has('search') && !empty($request->search['value'])) {
                    $query->where('countries.name', 'ilike', "%" . $request->search['value'] . "%");
                }
            })
            ->editColumn('flag_icon', function ($data) {
                $profileImage = !empty($data->flag_icon) ? $data->flag_icon : asset('assets/images/camera_placeholder.png');
                return '<div style="text-align:center;"><img src="' . $profileImage . '" class="rounded-circle avatar-xs" alt="profile-image"></div>';
                
            })
            ->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.countries.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.countries.edit', ['id' => $data->id]) . '">Edit</a></li>
                                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.countries.destroy', ['id' => $data->id]) . '">Delete</a></li>
                                        </ul>
                                    </div>';
            return $html;
            })
            ->rawColumns(['flag_icon','status','action'])
            ->make(true);
    }

    public function create(){
        $today = date("Y-m-d");
        $country = "";
        $title       = "";
        return view('admin.country.create', compact('today', 'country'));

    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'dial_code' => 'required|string|max:5',
            'status' => 'required|in:0,1',
            'flag_icon' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
        ];
    
        $validator = Validator::make($request->all(), $rules);
    
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        if ($request->id) {
            $country = Country::find($request->id);
    
            if (!$country) {
                return response()->json(['status' => 'error', 'message' => 'Country not found'], 404);
            }
    
            $existingCountry = Country::where('name', $request->name)
                ->where('id', '!=', $request->id)
                ->first();
    
            if ($existingCountry) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The country name already exists.']
                    ]
                ], 422);
            }
    
            $country->name = $request->name;
            $country->name_ar = $request->name_ar;
            $country->dial_code = $request->dial_code;
            $country->status = $request->status;
            if($request->file("flag_icon")){
                $response = image_upload($request,config('global.flag_image_upload_dir'),'flag_icon');
                if($response['status']){
                    $country->flag_icon = $response['link'];
                }
            }
            $country->save();
    
            return response()->json(['status' => 'success', 'message' => 'Country updated successfully']);
        } else {
            $existingCountry = Country::where('name', $request->name)->first();
    
            if ($existingCountry) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The country name already exists.']
                    ]
                ], 422);
            }
    
            $country = Country::create([
                'name' => $request->name,
                'name_ar' => $request->name_ar,
                'dial_code' => $request->dial_code, 
                'status' => $request->status,
            ]);

            if ($request->hasFile('flag_icon')) {
                $file = $request->file('flag_icon');
                    if ($file->isValid()) {
                        // Store the file and get the path
                        $storedPath = $file->store(config('global.flag_image_upload_dir'), config('global.upload_bucket'));
                        
                        // Extract the filename from the stored path
                        $storedFilename = basename($storedPath);

                        $country->flag_icon = $storedFilename;
                        $country->save();
                    }
            }
    
            return response()->json(['status' => 'success', 'message' => 'Country added successfully', 'country' => $country]);
        }
    }
    


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

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

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