<?php

namespace App\Http\Controllers;

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

class HolidayDsgMapController extends Controller
{
 public function index(Request $request)
    {
        try {
            $query = HolidayDsgMap::with(['holidayMaster', 'designationMaster']);

            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('Dsg_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}%");
                    });

                    // Designation master me search
                    $q->orWhereHas('designationMaster', function($q3) use ($search) {
                        $q3->where('Dsg_Title', 'LIKE', "%{$search}%")
                          ->orWhere('Dsg_Desc', 'LIKE', "%{$search}%")
                          ->orWhere('Dsg_EName', 'LIKE', "%{$search}%");
                    });
                });
            }

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

            return response()->json([
                'success' => true,
                'data' => $maps,
                'message' => 'Holiday designation 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 = HolidayDsgMap::with(['holidayMaster', 'designationMaster']);

            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('Dsg_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}%");
                    });

                    // Designation master
                    $q->orWhereHas('designationMaster', function($q3) use ($search) {
                        $q3->where('Dsg_Title', 'LIKE', "%{$search}%")
                          ->orWhere('Dsg_Desc', 'LIKE', "%{$search}%")
                          ->orWhere('Dsg_EName', 'LIKE', "%{$search}%");
                    });
                });
            }

            $maps = $query->get();

            return response()->json([
                'success' => true,
                'data' => $maps,
                'message' => 'All holiday designation 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 = HolidayDsgMap::with(['holidayMaster', 'designationMaster'])->findOrFail($id);

        return response()->json([
            'success' => true,
            'data' => $map,
            'message' => 'Holiday designation 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' => 'nullable|integer|exists:holiday_master,HL_Id',
                'Dsg_Id' => 'nullable|integer|exists:designation_master,Dsg_Id',
                'HDS_Status' => 'nullable|boolean'
            ]);

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

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

            return response()->json([
                'success' => true,
                'data' => $map,
                'message' => 'Holiday designation 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' => 'nullable|integer|exists:holiday_master,HL_Id',
                'Dsg_Id' => 'nullable|integer|exists:designation_master,Dsg_Id',
                'HDS_Status' => 'nullable|boolean'
            ]);

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

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

            return response()->json([
                'success' => true,
                'data' => $map,
                'message' => 'Holiday designation 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 = HolidayDsgMap::findOrFail($id);
            $map->delete();

            return response()->json([
                'success' => true,
                'message' => 'Holiday designation 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);
        }
    }
}
