<?php

namespace App\Http\Controllers;

use App\Models\AttnRegularize;
use Illuminate\Http\Request;

class AttnRegularizeController extends Controller
{

    public function index(Request $request)
{
    $perPage = $request->get('per_page', 10);
    $search  = $request->get('search');

    $query = AttnRegularize::with([
        'employee',
        'hod',
        'statusRel',
        'RStatus'
    ]);

    
    if ($search) {
        $query->where(function ($q) use ($search) {

            $q->where('ARG_Code', 'like', "%$search%")
              ->orWhere('Reason', 'like', "%$search%")

              ->orWhereHas('employee', function ($q2) use ($search) {
                  $q2->where('First_Name', 'like', "%$search%")
                     ->orWhere('Last_Name', 'like', "%$search%");
              });
        });
    }

    
   if ($request->filled('Status')) {
    $statusIds = array_map('trim', explode(',', $request->Status));
    $query->whereIn('Status', $statusIds);
}

    return response()->json($query->paginate($perPage));
}

    public function store(Request $request)
    {
        $validated = $request->validate([
            'ARG_Code' => 'nullable|string|max:10',

            'Emp_Id' => 'nullable|exists:employee_master,Emp_Id',

            'ARG_FDt' => 'nullable|date',
            'ARG_TDt' => 'nullable|date',

            'ARG_Rsn' => 'nullable|in:BIOMETRIC_FAILURE,FORGOT_PUNCH,FIELD_DUTY,OFFICIAL_VISIT,TOUR,SYSTEM_ERROR,OTHER',

            'ARG_TIn' => 'nullable|date',
            'ARG_TOu' => 'nullable|date',

            'ARG_Days' => 'nullable|numeric',

            'PlaceVisit' => 'nullable|string|max:50',

            'HlDy_Btwn' => 'nullable|numeric',

            'ARG_HOD' => 'nullable|exists:user_master,Usr_Id',

            'Reason' => 'nullable|string|max:50',

            'Status' => 'nullable|exists:action_master,Act_Id',
            'R_Status' => 'nullable|exists:action_master,Act_Id',
            'Status_Remark' => 'nullable|string'
        ]);

        
        if ($request->filled('ARG_HOD')) {
            $validated['ARG_HDT'] = now();
        }

        $data = AttnRegularize::create($validated);

        return response()->json([
            'message' => 'Created Successfully',
            'data' => $data->load(['employee', 'hod', 'statusRel', 'RStatus'])
        ]);
    }


    public function show($id)
    {
        $data = AttnRegularize::with(['employee', 'hod', 'statusRel', 'RStatus'])
            ->findOrFail($id);

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


    public function update(Request $request, $id)
    {
        $data = AttnRegularize::findOrFail($id);

        $validated = $request->validate([
            'ARG_Code' => 'sometimes|string|max:10',

            'Emp_Id' => 'sometimes|exists:employee_master,Emp_Id',

            'ARG_FDt' => 'sometimes|date',
            'ARG_TDt' => 'sometimes|date',

            'ARG_Rsn' => 'nullable|in:BIOMETRIC_FAILURE,FORGOT_PUNCH,FIELD_DUTY,OFFICIAL_VISIT,TOUR,SYSTEM_ERROR,OTHER',

            'ARG_TIn' => 'nullable|date',
            'ARG_TOu' => 'nullable|date',

            'ARG_Days' => 'nullable|numeric',

            'PlaceVisit' => 'nullable|string|max:50',

            'HlDy_Btwn' => 'nullable|numeric',

            'ARG_HOD' => 'nullable|exists:user_master,Usr_Id',

            'Reason' => 'nullable|string|max:50',

            'Status' => 'nullable|exists:action_master,Act_Id',
            'R_Status' => 'sometimes|nullable|exists:action_master,Act_Id',
            'Status_Remark' => 'sometimes|nullable|string'
        ]);

        
        if ($request->has('ARG_HOD') && $request->ARG_HOD != $data->ARG_HOD) {
            $validated['ARG_HDT'] = now();
        }

        $data->update($validated);

        return response()->json([
            'message' => 'Updated Successfully',
            'data' => $data->load(['employee', 'hod', 'statusRel', 'RStatus'])
        ]);
    }


    public function destroy($id)
    {
        $data = AttnRegularize::findOrFail($id);
        $data->delete();

        return response()->json([
            'message' => 'Deleted Successfully'
        ]);
    }


     public function all()
    {
        try {

            $data = AttnRegularize::with([
                'employee',
                'hod',
                'statusRel',
                'RStatus'
            ])->orderBy('ARG_id', 'desc')->get();

            return response()->json([
                'success' => true,
                'total' => $data->count(),
                'data' => $data
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Something went wrong. Please try again later.'
            ]);
        }
    }


}
