<?php

namespace App\Http\Controllers;

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

class HolidayEmpTyMapController extends Controller
{
   public function index(Request $request)
    {
        try {
            $query = HolidayEmpTyMap::with(['holidayMaster', 'empTypeMaster']);

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

                $query->where(function($q) use ($search) {
                    // Direct fields me search
                    $q->where('HL_Id', 'LIKE', "%{$search}%")
                      ->orWhere('ETy_Id', 'LIKE', "%{$search}%");

                    // Holiday master me search
                    $q->orWhereHas('holidayMaster', function($q2) use ($search) {
                        $q2->where('HL_Name', 'LIKE', "%{$search}%")
                          ->orWhere('HL_Code', 'LIKE', "%{$search}%")
                          ->orWhere('HL_Type', 'LIKE', "%{$search}%")
                          ->orWhere('HL_Cate', 'LIKE', "%{$search}%")
                          ->orWhere('Remarks', 'LIKE', "%{$search}%");
                    });

                    // Employee Type master me search
                    $q->orWhereHas('empTypeMaster', function($q3) use ($search) {
                        $q3->where('ETy_Name', 'LIKE', "%{$search}%")
                          ->orWhere('ETy_Code', 'LIKE', "%{$search}%");
                    });
                });
            }

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

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

    public function all(Request $request)
    {
        try {
            $query = HolidayEmpTyMap::with(['holidayMaster', 'empTypeMaster']);

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

                $query->where(function($q) use ($search) {
                    // Direct fields
                    $q->where('HL_Id', 'LIKE', "%{$search}%")
                      ->orWhere('ETy_Id', 'LIKE', "%{$search}%");

                    // Holiday master
                    $q->orWhereHas('holidayMaster', function($q2) use ($search) {
                        $q2->where('HL_Name', 'LIKE', "%{$search}%")
                          ->orWhere('HL_Code', 'LIKE', "%{$search}%")
                          ->orWhere('HL_Type', 'LIKE', "%{$search}%")
                          ->orWhere('HL_Cate', 'LIKE', "%{$search}%")
                          ->orWhere('Remarks', 'LIKE', "%{$search}%");
                    });

                    // Employee Type master
                    $q->orWhereHas('empTypeMaster', function($q3) use ($search) {
                        $q3->where('ETy_Name', 'LIKE', "%{$search}%")
                          ->orWhere('ETy_Code', 'LIKE', "%{$search}%");
                    });
                });
            }

            $maps = $query->get();

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


public function show($id)
{
    try {
        $map = HolidayEmpTyMap::with(['holidayMaster', 'empTypeMaster'])->findOrFail($id);

        return response()->json([
            'success' => true,
            'data' => $map,
            'message' => 'Holiday employee type map retrieved successfully'
        ], 200);
    } catch (ModelNotFoundException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Map not found'
        ], 404);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error retrieving map',
            '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(), [
                'HL_Id' => 'required|integer|exists:holiday_master,HL_Id',
                'ETy_Id' => 'required|integer|exists:emp_type_master,ETy_Id',
                'HET_Status' => 'nullable|boolean'
            ]);

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

            $map = HolidayEmpTyMap::create($request->all());

            return response()->json([
                'success' => true,
                'data' => $map,
                'message' => 'Holiday employee type map created successfully'
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error creating map',
                '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(), [
                'HL_Id' => 'required|integer|exists:holiday_master,HL_Id',
                'ETy_Id' => 'required|integer|exists:emp_type_master,ETy_Id',
                'HET_Status' => 'nullable|boolean'
            ]);

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

            $map = HolidayEmpTyMap::findOrFail($id);
            $map->update($request->all());

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

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

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