<?php

namespace App\Http\Controllers\Admin;

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

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

    public function getDressCodeList(Request $request)
    {
        $sqlBuilder = DressCode::select([
            'dress_codes.id',
            'dress_codes.name',
            'dress_codes.name_ar',
            'dress_codes.gender',
            'dress_codes.status',
            'dress_codes.image',
        ]);

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

    public function create()
    {
        $dressCode = "";

        return view('admin.dress_codes.create', compact('dressCode'));
    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'gender' => 'required|in:Male,Female',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,svg|max:2048',
            '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) {
            $dressCode = DressCode::find($request->id);

            if (!$dressCode) {
                return response()->json(['status' => 'error', 'message' => 'Dress Code not found'], 404);
            }

            $dressCode->name = $request->name;
            $dressCode->name_ar = $request->name_ar;
            $dressCode->gender = $request->gender;
            $dressCode->status = $request->status;
            $dressCode->save();

            if($request->file("image")){
                $response = image_upload($request,config('global.dress_code_image_upload_dir'),'image');
                if($response['status']){
                    $dressCode->image = $response['link'];
                    $dressCode->save();
                }
            }

            return response()->json(['status' => 'success', 'message' => 'Dress Code updated successfully']);
        } else {
            $alreadyExists = DressCode::where('name', $request->name)->orWhere('name_ar', $request->name_ar)->first();
            if ($alreadyExists) {
                return response()->json(['status' => 'error', 'message' => 'Dress Code already exists'], 422);
            }
            $dressCode = DressCode::create([
                'name' => $request->name,
                'name_ar' => $request->name_ar,
                'gender' => $request->gender,
                'status' => $request->status,
            ]);

            if($request->file("image")){
                $response = image_upload($request,config('global.dress_code_image_upload_dir'),'image');
                if($response['status']){
                    $dressCode->image = $response['link'];
                    $dressCode->save();
                }
            }

            return response()->json(['status' => 'success', 'message' => 'Dress Code added successfully', 'dressCode' => $dressCode]);
        }
    }

    public function edit($id)
    {
        $dressCode = DressCode::findOrFail($id);

        return view('admin.dress_codes.create', compact('dressCode'));
    }

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

    public function statusChange(Request $request, $id)
    {
        $dressCode = DressCode::find($id);

        if (!$dressCode) {
            return response()->json([
                'status' => 'error',
                'message' => 'Dress Code not found.'
            ], 404);
        }

        $dressCode->status = $request->status;
        $dressCode->save();

        return response()->json([
            'status' => 'success',
            'message' => 'Dress Code status updated successfully.'
        ]);
    }
}
