<?php

namespace App\Http\Controllers;

use App\Models\LeaveTypeMaster;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class LeaveTypeMasterController extends Controller
{
    public function index(Request $request)
    {
        try {
            $query = LeaveTypeMaster::query();

            if ($request->has('search') && !empty($request->search)) {
                $search = $request->search;

                $query->where(function ($q) use ($search) {
                    $q->where('LT_code', 'LIKE', "%{$search}%")
                        ->orWhere('LT_name', 'LIKE', "%{$search}%")
                        ->orWhere('Max_days', 'LIKE', "%{$search}%")
                        ->orWhere('Is_Paid', 'LIKE', "%{$search}%")
                        ->orWhere('Is_Active', 'LIKE', "%{$search}%");
                });
            }

            $perPage = $request->get('per_page', 15);
            $leaveTypes = $query->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => $leaveTypes,
                'message' => 'Leave types retrieved successfully'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving leave types',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    public function all(Request $request)
    {
        try {
            $query = LeaveTypeMaster::query();

            if ($request->has('search') && !empty($request->search)) {
                $search = $request->search;

                $query->where(function ($q) use ($search) {
                    $q->where('LT_code', 'LIKE', "%{$search}%")
                        ->orWhere('LT_name', 'LIKE', "%{$search}%")
                        ->orWhere('Max_days', 'LIKE', "%{$search}%")
                        ->orWhere('Is_Paid', 'LIKE', "%{$search}%")
                        ->orWhere('Is_Active', 'LIKE', "%{$search}%");
                });
            }

            $leaveTypes = $query->get();

            return response()->json([
                'success' => true,
                'data' => $leaveTypes,
                'message' => 'All leave types retrieved successfully'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving leave types',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'LT_code' => 'nullable|string|max:20',
                'LT_name' => 'required|string|max:100',
                // 'Attn_type' => 'nullable|in:A,L',
                'Max_days' => 'nullable|integer',

                // ✅ FIXED FIELDS
                'Alw_Gen' => 'nullable|in:M,F,A', // ENUM
                'Min_ApBf' => 'nullable|integer',
                'Min_ApDy' => 'nullable|numeric',
                'Max_ApDy' => 'nullable|numeric',
                'Acr_Plcy' => 'required|in:YEARLY,HALF_YEARLY,QUARTERLY,MONTHLY',
                'Acr_Days' => 'nullable|integer',
                'Is_Encash' => 'nullable|boolean',
                'Is_CryFw' => 'nullable|boolean',
                'Max_CfAl' => 'nullable|integer',
                'Is_HfDy' => 'nullable|boolean',

                'Is_Paid' => 'nullable|boolean',
                'Is_Active' => 'nullable|boolean'
            ]);

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

            $leaveType = LeaveTypeMaster::create($request->all());

            return response()->json([
                'success' => true,
                'data' => $leaveType,
                'message' => 'Leave type created successfully'
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error creating leave type',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    public function show($id)
    {
        try {
            $leaveType = LeaveTypeMaster::findOrFail($id);

            return response()->json([
                'success' => true,
                'data' => $leaveType,
                'message' => 'Leave type retrieved successfully'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Leave type not found'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving leave type',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $validator = Validator::make($request->all(), [
                'LT_code' => 'sometimes|nullable|string|max:20',
                'LT_name' => 'sometimes|nullable|string|max:100',
                'Attn_type' => 'sometimes|nullable|in:A,L',
                'Max_days' => 'sometimes|nullable|integer',

                // ✅ FIXED FIELDS
                'Alw_Gen' => 'sometimes|nullable|in:M,F,A', // ENUM
                'Min_ApBf' => 'sometimes|nullable|integer',
                'Min_ApDy' => 'sometimes|nullable|numeric',
                'Max_ApDy' => 'sometimes|nullable|numeric',
                'Acr_Plcy' => 'sometimes|nullable|in:YEARLY,HALF_YEARLY,QUARTERLY,MONTHLY',
                'Acr_Days' => 'sometimes|nullable|integer',
                'Is_Encash' => 'sometimes|nullable|boolean',
                'Is_CryFw' => 'sometimes|nullable|boolean',
                'Max_CfAl' => 'sometimes|nullable|integer',
                'Is_HfDy' => 'sometimes|nullable|boolean',

                'Is_Paid' => 'sometimes|nullable|boolean',
                'Is_Active' => 'sometimes|nullable|boolean'
            ]);

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

            $leaveType = LeaveTypeMaster::findOrFail($id);
            $leaveType->update($request->all());

            return response()->json([
                'success' => true,
                'data' => $leaveType,
                'message' => 'Leave type updated successfully'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Leave type not found'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error updating leave type',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    public function destroy($id)
    {
        try {
            $leaveType = LeaveTypeMaster::findOrFail($id);
            $leaveType->delete();

            return response()->json([
                'success' => true,
                'message' => 'Leave type deleted successfully'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Leave type not found'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error deleting leave type',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }
}
