<?php

namespace App\Http\Controllers;

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

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

    /**
     * Get a specific SecurityAgency record by SA_Id.
     */
    public function show($id)
    {
        $agency = SecurityAgency::with(['society', 'user', 'resourceBook'])->find($id);

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

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

    /**
     * Create a new SecurityAgency record.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'SocId' => 'required|integer|exists:society_master,SocId',
            'U_Id' => 'required|integer|exists:users_master,U_Id',
            'SR_Id' => 'nullable|integer|exists:soci_reso_books,SR_Id',
            'BusinessName' => 'nullable|string|max:255',
            'Registration' => 'nullable|string|max:25',
            'TaxRegistration' => 'nullable|string|max:25',
            'STDate' => 'nullable|date_format:d/m/Y H:i:s',
            'EdDate' => 'nullable|date_format:d/m/Y H:i:s|after:STDate',
            'Status' => 'nullable|string|in:A,I|max:1',
        ]);

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

        $validated = $validator->validated();

        // Convert date fields to MySQL format
        try {
            $validated['STDate'] = Carbon::createFromFormat('d/m/Y H:i:s', $request->input('STDate'), 'Asia/Kolkata')
                ->format('Y-m-d H:i:s');
            $validated['EdDate'] = Carbon::createFromFormat('d/m/Y H:i:s', $request->input('EdDate'), 'Asia/Kolkata')
                ->format('Y-m-d H:i:s');
        } catch (\Exception $e) {
            return response()->json(['error' => 'Invalid date format for STDate or EdDate. Use dd/mm/yyyy HH:mm:ss'], 422);
        }

        $agency = SecurityAgency::create($validated);

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

    /**
     * Update a SecurityAgency record by SA_Id.
     */
    public function update(Request $request, $id)
    {
        $agency = SecurityAgency::find($id);

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

        $validator = Validator::make($request->all(), [
           'SocId' => 'required|integer|exists:society_master,SocId',
            'U_Id' => 'required|integer|exists:users_master,U_Id',
            'SR_Id' => 'nullable|integer|exists:soci_reso_books,SR_Id',
            'BusinessName' => 'nullable|string|max:255',
            'Registration' => 'nullable|string|max:25',
            'TaxRegistration' => 'nullable|string|max:25',
            'STDate' => 'nullable|date_format:d/m/Y H:i:s',
            'EdDate' => 'nullable|date_format:d/m/Y H:i:s|after:STDate',
            'Status' => 'nullable|string|in:A,I|max:1',
        ]);

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

        $validated = array_filter($validator->validated(), fn($value) => !is_null($value));

        // Convert date fields to MySQL format
        if ($request->filled('STDate')) {
            try {
                $validated['STDate'] = Carbon::createFromFormat('d/m/Y H:i:s', $request->input('STDate'), 'Asia/Kolkata')
                    ->format('Y-m-d H:i:s');
            } catch (\Exception $e) {
                return response()->json(['error' => 'Invalid date format for STDate. Use dd/mm/yyyy HH:mm:ss'], 422);
            }
        }
        if ($request->filled('EdDate')) {
            try {
                $validated['EdDate'] = Carbon::createFromFormat('d/m/Y H:i:s', $request->input('EdDate'), 'Asia/Kolkata')
                    ->format('Y-m-d H:i:s');
            } catch (\Exception $e) {
                return response()->json(['error' => 'Invalid date format for EdDate. Use dd/mm/yyyy HH:mm:ss'], 422);
            }
        }

        $agency->update($validated);

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

    /**
     * Delete a SecurityAgency record by SA_Id.
     */
    public function destroy($id)
    {
        $agency = SecurityAgency::find($id);

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

        $agency->delete();
        return response()->json(['message' => 'Security agency deleted successfully']);
    }
}
