<?php

namespace App\Http\Controllers;

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

class GuardDutyAttanController extends Controller
{
    /**
     * Get all GuardDutyAttan records.
     */
    public function index()
    {
        $dutyAttans = GuardDutyAttan::with('guardDutyRegister')->get();
        return response()->json($dutyAttans);
    }

    /**
     * Get a specific GuardDutyAttan record by GA_ID.
     */
    public function show($id)
    {
        $dutyAttan = GuardDutyAttan::with('guardDutyRegister')->find($id);

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

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

    /**
     * Create a new GuardDutyAttan record.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'GD_Id' => 'required|integer|exists:guard_duty_register,GD_Id',
            'LoginTime' => 'nullable|date_format:h:i A',
            'LogoutTime' => 'nullable|date_format:h:i A',
            'LogInDate' => 'nullable|date_format:d/m/Y',
        ]);

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

        DB::beginTransaction(); // Start transaction

        try {
            $validated = $validator->validated();

            // Convert time fields to MySQL TIME format (H:i:s)
            $validated['LoginTime'] = $request->filled('LoginTime')
                ? Carbon::createFromFormat('h:i A', $request->input('LoginTime'), 'Asia/Kolkata')
                    ->format('H:i:s')
                : null;
            $validated['LogoutTime'] = $request->filled('LogoutTime')
                ? Carbon::createFromFormat('h:i A', $request->input('LogoutTime'), 'Asia/Kolkata')
                    ->format('H:i:s')
                : null;
            $validated['LogInDate'] = $request->filled('LogInDate')
                ? Carbon::createFromFormat('d/m/Y', $request->input('LogInDate'), 'Asia/Kolkata')
                    ->format('Y-m-d')
                : null;

            // Create Guard Duty Attendance
            $dutyAttan = GuardDutyAttan::create($validated);

            DB::commit(); // Commit transaction

            // Eager load the related guard duty register
            $dutyAttan->load('guardDutyRegister');

            return response()->json([
                'message' => 'Guard duty attendance registered successfully!',
                'duty_attan' => $dutyAttan
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack(); // Rollback on failure
            return response()->json(['error' => 'Guard duty attendance registration failed!', 'details' => $e->getMessage()], 500);
        }
    }

    /**
     * Update a GuardDutyAttan record by GA_ID.
     */
    public function update(Request $request, $id)
    {
        $dutyAttan = GuardDutyAttan::find($id);

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

        $validator = Validator::make($request->all(), [
            'GD_Id' => 'nullable|integer|exists:guard_duty_register,GD_Id',
            'LoginTime' => 'nullable|date_format:h:i A',
            'LogoutTime' => 'nullable|date_format:h:i A',
            'LogInDate' => 'nullable|date_format:d/m/Y',
        ]);

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

        $validated = array_filter($validator->validated());

        // Convert time fields to MySQL TIME format (H:i:s)
        if ($request->filled('LoginTime')) {
            $validated['LoginTime'] = Carbon::createFromFormat('h:i A', $request->input('LoginTime'), 'Asia/Kolkata')
                ->format('H:i:s');
        }
        if ($request->filled('LogoutTime')) {
            $validated['LogoutTime'] = Carbon::createFromFormat('h:i A', $request->input('LogoutTime'), 'Asia/Kolkata')
                ->format('H:i:s');
        }
        if ($request->filled('LogInDate')) {
            $validated['LogInDate'] = Carbon::createFromFormat('d/m/Y', $request->input('LogInDate'), 'Asia/Kolkata')
                ->format('Y-m-d');
        }

        $dutyAttan->update($validated);

        $dutyAttan->load('guardDutyRegister');

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

    /**
     * Delete a GuardDutyAttan record by GA_ID.
     */
    public function destroy($id)
    {
        $dutyAttan = GuardDutyAttan::find($id);

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

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