<?php

namespace App\Http\Controllers;

use App\Models\ComplaintBook;
use App\Models\CompCategory;
use App\Models\CompAction;
use App\Models\CompActionLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Barryvdh\DomPDF\Facade\Pdf;
use DateTimeZone;

class FilterController extends Controller
{
    /**
     * Filter ComplaintBook records.
     */
    public function filterComplaints(Request $request)
    {
        // Validate filter parameters
        $validator = Validator::make($request->all(), [
            'Cmp_Id' => 'nullable|integer|exists:complaint_books,Cmp_Id',
            '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:250',
            'CompType' => 'nullable|string|max:1',
            'Severity' => 'nullable|string|max:1',
            'Status' => 'nullable|string|in:P,I,C',
            'CompMode' => 'nullable|string|in:M,C',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
        ]);

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

        // Build query
        $query = ComplaintBook::with(['category', 'society', 'user']);

        if ($request->has('Cmp_Id')) {
            $query->where('Cmp_Id', $request->input('Cmp_Id'));
        }

        if ($request->has('CC_Id')) {
            $query->where('CC_Id', $request->input('CC_Id'));
        }

        if ($request->has('SocId')) {
            $query->where('SocId', $request->input('SocId'));
        }

        if ($request->has('U_ID')) {
            $query->where('U_ID', $request->input('U_ID'));
        }

        if ($request->has('Title')) {
            $query->where('Title', 'like', '%' . $request->input('Title') . '%');
        }

        if ($request->has('Description')) {
            $query->where('Description', 'like', '%' . $request->input('Description') . '%');
        }

        if ($request->has('CompType')) {
            $query->where('CompType', $request->input('CompType'));
        }

        if ($request->has('Severity')) {
            $query->where('Severity', $request->input('Severity'));
        }

        if ($request->has('Status')) {
            $query->where('Status', $request->input('Status'));
        }

        if ($request->has('CompMode')) {
            $query->where('CompMode', $request->input('CompMode'));
        }

        if ($request->has('start_date') && $request->has('end_date')) {
            $query->where(function ($q) use ($request) {
                $q->whereBetween('InProgre_At', [$request->input('start_date'), $request->input('end_date')])
                  ->orWhereBetween('Complited_At', [$request->input('start_date'), $request->input('end_date')]);
            });
        }

        $complaints = $query->get();

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

    /**
     * Generate PDF for filtered ComplaintBook records.
     */
    public function generateComplaintPDF(Request $request)
    {
        // Set timezone to IST
        date_default_timezone_set('Asia/Kolkata');

        // Validate filter parameters
        $validator = Validator::make($request->all(), [
            'Cmp_Id' => 'nullable|integer|exists:complaint_books,Cmp_Id',
            '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:250',
            'CompType' => 'nullable|string|max:1',
            'Severity' => 'nullable|string|max:1',
            'Status' => 'nullable|string|in:P,I,C',
            'CompMode' => 'nullable|string|in:M,C',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
        ]);

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

        // Build query
        $query = ComplaintBook::with(['category', 'society', 'user']);

        if ($request->has('Cmp_Id')) {
            $query->where('Cmp_Id', $request->input('Cmp_Id'));
        }

        if ($request->has('CC_Id')) {
            $query->where('CC_Id', $request->input('CC_Id'));
        }

        if ($request->has('SocId')) {
            $query->where('SocId', $request->input('SocId'));
        }

        if ($request->has('U_ID')) {
            $query->where('U_ID', $request->input('U_ID'));
        }

        if ($request->has('Title')) {
            $query->where('Title', 'like', '%' . $request->input('Title') . '%');
        }

        if ($request->has('Description')) {
            $query->where('Description', 'like', '%' . $request->input('Description') . '%');
        }

        if ($request->has('CompType')) {
            $query->where('CompType', $request->input('CompType'));
        }

        if ($request->has('Severity')) {
            $query->where('Severity', $request->input('Severity'));
        }

        if ($request->has('Status')) {
            $query->where('Status', $request->input('Status'));
        }

        if ($request->has('CompMode')) {
            $query->where('CompMode', $request->input('CompMode'));
        }

        if ($request->has('start_date') && $request->has('end_date')) {
            $query->where(function ($q) use ($request) {
                $q->whereBetween('InProgre_At', [$request->input('start_date'), $request->input('end_date')])
                  ->orWhereBetween('Complited_At', [$request->input('start_date'), $request->input('end_date')]);
            });
        }

        $complaints = $query->get();
        $socId = $request->input('SocId');
        $socName = $socId ? $complaints->first()->society->SocName ?? 'All Societies' : 'All Societies';

        // Generate PDF
        $pdf = Pdf::loadView('pdf.complaints', compact('complaints', 'socName'));
        return $pdf->download('complaints_report.pdf');
    }

    /**
     * Filter CompCategory records by CC_Desc.
     */
    public function filterCategories(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'CC_Desc' => 'nullable|string|max:100',
        ]);

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

        $query = CompCategory::query();

        if ($request->has('CC_Desc')) {
            $query->where('CC_Desc', 'like', '%' . $request->input('CC_Desc') . '%');
        }

        $categories = $query->get();

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

    /**
     * Filter CompAction records by CA_Desc or Ca_Flag.
     */
    public function filterActions(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'CA_Desc' => 'nullable|string|max:255',
            'Ca_Flag' => 'nullable|string|max:1',
        ]);

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

        $query = CompAction::query();

        if ($request->has('CA_Desc')) {
            $query->where('CA_Desc', 'like', '%' . $request->input('CA_Desc') . '%');
        }

        if ($request->has('Ca_Flag')) {
            $query->where('Ca_Flag', $request->input('Ca_Flag'));
        }

        $actions = $query->get();

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

    /**
     * Filter CompActionLog records by Cmp_Id or Act_U_ID.
     */
    public function filterActionLogs(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'Cmp_Id' => 'nullable|integer|exists:complaint_books,Cmp_Id',
            'Act_U_ID' => 'nullable|integer|exists:users_master,U_Id',
        ]);

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

        $query = CompActionLog::with(['complaint', 'actionUser', 'compAction']);

        if ($request->has('Cmp_Id')) {
            $query->where('Cmp_Id', $request->input('Cmp_Id'));
        }

        if ($request->has('Act_U_ID')) {
            $query->where('Act_U_ID', $request->input('Act_U_ID'));
        }

        $logs = $query->get();

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