<?php

namespace App\Http\Controllers\Admin;

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

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

    public function getMaritalStatusList(Request $request)
    {
        $sqlBuilder = MaritalStatus::select([
            'marital_statuses.id',
            'marital_statuses.name',
            'marital_statuses.name_ar',
            'marital_statuses.gender',
            'marital_statuses.status',
        ]);

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

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

        return view('admin.marital_statuses.create', compact('maritalStatus'));
    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'gender' => 'required|in:Male,Female',
            '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) {
            $maritalStatus = MaritalStatus::find($request->id);

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

            $maritalStatus->name = $request->name;
            $maritalStatus->name_ar = $request->name_ar;
            $maritalStatus->gender = $request->gender;
            $maritalStatus->status = $request->status;
            $maritalStatus->show_wife_children_option = $request->show_wife_children_option;
            $maritalStatus->show_wife = $request->show_wife;
            $maritalStatus->save();

            return response()->json(['status' => 'success', 'message' => 'Marital Status updated successfully']);
        } else {
            $alreadyExists = MaritalStatus::where('name', $request->name)->where('gender', $request->gender)->first();
            if ($alreadyExists) {
                return response()->json(['status' => 'error', 'message' => 'Marital Status already exists'], 422);
            }
            $maritalStatus = MaritalStatus::create([
                'name' => $request->name,
                'name_ar' => $request->name_ar,
                'gender' => $request->gender,
                'status' => $request->status,
                'show_wife_children_option' => $request->show_wife_children_option,
                'show_wife' => $request->show_wife,
            ]);

            return response()->json(['status' => 'success', 'message' => 'Marital Status added successfully', 'maritalStatus' => $maritalStatus]);
        }
    }

    public function edit($id)
    {
        $maritalStatus = MaritalStatus::findOrFail($id);

        return view('admin.marital_statuses.create', compact('maritalStatus'));
    }

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

    public function statusChange(Request $request, $id)
    {
        $maritalStatus = MaritalStatus::find($id);

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

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

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