<?php

namespace App\Http\Controllers;

use App\Models\ComplaintBook;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;

class ComplaintBookController extends Controller
{
    /**
     * Get all ComplaintBook records.
     */
    public function index()
    {
        $complaints = ComplaintBook::with(['category', 'society', 'user'])->get();
        return response()->json($complaints);
    }

    /**
     * Get a specific ComplaintBook record by Cmp_Id.
     */
    public function show($id)
    {
        $complaint = ComplaintBook::with(['category', 'society', 'user'])->find($id);

        if (!$complaint) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        return response()->json($complaint);
    }

    /**
     * Create a new ComplaintBook record.
     */
    public function store(Request $request)
    {
        // Validate request data
        $validator = Validator::make($request->all(), [
            'CC_Id'       => 'required|integer|exists:comp_categories,CC_Id',
            'SocId'       => 'required|integer|exists:society_master,SocId',
            'U_Id'        => 'required|integer|exists:users_master,U_Id',
            'Title'       => 'required|string|max:25',
            'Description' => 'required|string|max:500',
            'CompType'    => 'required|string|max:1',
            'Severity'    => 'required|string|max:1',
            'Status'      => 'required|string|in:P,I,C',
            'InProgre_At' => 'nullable|date',
            'Complited_At' => 'nullable|date',
            'CompMode'    => 'required|string|in:M,C',
        ]);

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

        // Create a new complaint record
        $complaint = ComplaintBook::create([
            'CC_Id'       => $request->input('CC_Id'),
            'SocId'       => $request->input('SocId'),
            'U_Id'        => $request->input('U_Id'),
            'Title'       => $request->input('Title'),
            'Description' => $request->input('Description'),
            'CompType'    => $request->input('CompType'),
            'Severity'    => $request->input('Severity'),
            'Status'      => $request->input('Status'),
            'InProgre_At' => $request->input('Status') === 'I' ? Carbon::now('Asia/Kolkata') : null,
            'Complited_At' => $request->input('Status') === 'C' ? Carbon::now('Asia/Kolkata') : null,
            'CompMode'    => $request->input('CompMode'),
        ]);

        return response()->json($complaint, 201);
    }

    /**
     * Update a ComplaintBook record by Cmp_Id.
     */
    public function update(Request $request, $id)
    {
        $complaint = ComplaintBook::find($id);

        if (!$complaint) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        // Validation rules (all fields optional)
        $validator = Validator::make($request->all(), [
            'CC_Id'       => 'nullable|integer|exists:comp_categories,CC_Id',
            'SocId'       => 'nullable|integer|exists:society_master,SocId',
            'U_Id'        => 'nullable|integer|exists:users_master,U_Id',
            'Title'       => 'nullable|string|max:25',
            'Description' => 'nullable|string|max:500',
            'CompType'    => 'nullable|string|max:1',
            'Severity'    => 'nullable|string|max:1',
            'Status'      => 'nullable|string|in:P,I,C',
            'InProgre_At' => 'nullable|date',
            'Complited_At' => 'nullable|date',
            'CompMode'    => 'nullable|string|in:M,C',
        ]);

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

        // Prepare update data
        $updateData = array_filter($request->only([
            'CC_Id', 'SocId', 'U_Id', 'Title', 'Description', 'CompType', 'Severity', 'Status', 'CompMode'
        ]));

        // Handle InProgre_At and Complited_At based on Status
        if ($request->has('Status')) {
            $newStatus = $request->input('Status');
            if ($newStatus === 'P') {
                $updateData['InProgre_At'] = null;
                $updateData['Complited_At'] = null;
            } elseif ($newStatus === 'I' && $complaint->Status !== 'I') {
                $updateData['InProgre_At'] = Carbon::now('Asia/Kolkata');
                $updateData['Complited_At'] = null;
            } elseif ($newStatus === 'C' && $complaint->Status !== 'C') {
                $updateData['Complited_At'] = Carbon::now('Asia/Kolkata');
                if ($complaint->Status !== 'I') {
                    $updateData['InProgre_At'] = Carbon::now('Asia/Kolkata');
                }
            }
        }

        // Update only the provided fields
        $complaint->update($updateData);

        return response()->json($complaint);
    }

    /**
     * Delete a ComplaintBook record by Cmp_Id.
     */
    public function destroy($id)
    {
        $complaint = ComplaintBook::find($id);

        if (!$complaint) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        $complaint->delete();
        return response()->json(['message' => 'Deleted successfully']);
    }
}
