<?php

namespace App\Http\Controllers\Admin;

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

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

    public function getChronicDiseaseList(Request $request)
    {
        $sqlBuilder = ChronicDisease::select([
            'chronic_diseases.id',
            'chronic_diseases.name',
            'chronic_diseases.name_ar',
            'chronic_diseases.status',
        ]);

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

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

        return view('admin.chronic_diseases.create', compact('chronicDisease'));
    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'status' => 'required|in:0,1',
            'variants' => 'nullable|array',
            'variants.*.name' => 'string|max:255',
            'variants.*.name_ar' => 'string|max:255',
        ];

        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }

        if ($request->id) {
            $chronicDisease = ChronicDisease::find($request->id);

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

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

            if ($request->has('variants') && is_array($request->variants)) {
                $createdRecords = [];
                foreach ($request->variants as $variant) {
                    if (isset($variant['id']) && $variant['id']) {
                        $existingVariant = ChronicDiseaseVariant::find($variant['id']);
                        if ($existingVariant) {
                            $existingVariant->name = $variant['name'];
                            $existingVariant->name_ar = $variant['name_ar'];
                            $existingVariant->save();
                            $createdRecords[] = $existingVariant->id;
                        }
                    } else {
                        $recordCreated = ChronicDiseaseVariant::create([
                            'name' => $variant['name'],
                            'name_ar' => $variant['name_ar'],
                            'chronic_disease_id' => $chronicDisease->id,
                        ]);
                        $createdRecords[] = $recordCreated->id;
                    }
                }
                ChronicDiseaseVariant::where('chronic_disease_id', $chronicDisease->id)
                    ->whereNotIn('id', $createdRecords)
                    ->delete();
            }

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

            if ($request->has('variants') && is_array($request->variants)) {
                foreach ($request->variants as $variant) {
                    ChronicDiseaseVariant::create([
                        'name' => $variant['name'],
                        'name_ar' => $variant['name_ar'],
                        'chronic_disease_id' => $chronicDisease->id,
                    ]);
                }
            }

            return response()->json(['status' => 'success', 'message' => 'Chronic Disease added successfully', 'chronicDisease' => $chronicDisease]);
        }
    }

    public function edit($id)
    {
        $chronicDisease = ChronicDisease::findOrFail($id);

        return view('admin.chronic_diseases.create', compact('chronicDisease'));
    }

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

    public function statusChange(Request $request, $id)
    {
        $chronicDisease = ChronicDisease::find($id);

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

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

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