<?php

namespace App\Http\Controllers\Modules\Employee;

use App\Http\Controllers\Controller;
use App\Http\Traits\HasRoleViews;
use App\Models\Holiday;
use App\Services\Employee\HolidayService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

/**
 * Unified Holiday Controller
 *
 * Handles holiday management for all roles.
 * Reference: SuperAdminHolidayController
 */
class HolidayController extends Controller
{
    use HasRoleViews;

    protected HolidayService $holidayService;

    public function __construct(HolidayService $holidayService)
    {
        $this->holidayService = $holidayService;
    }

    /**
     * Display the holiday list page
     */
    public function index(Request $request)
    {
        $year = $request->input('year', now()->year);
        $holidays = $this->holidayService->getForYear($year);
        $years = range(now()->year - 2, now()->year + 2);
        $summary = $this->holidayService->getYearlySummary($year);

        return $this->roleView('employee.holiday', compact('holidays', 'years', 'year', 'summary'));
    }

    /**
     * Store a newly created holiday
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'date' => 'required|date',
            'type' => 'required|string|in:' . implode(',', [
                Holiday::TYPE_PUBLIC,
                Holiday::TYPE_OPTIONAL,
                Holiday::TYPE_COMPANY,
                Holiday::TYPE_RESTRICTED,
            ]),
            'description' => 'nullable|string|max:1000',
        ]);

        try {
            $date = Carbon::parse($validated['date']);
            $validated['day'] = $date->format('l');

            $this->holidayService->createHoliday($validated);

            return redirect()->back()->with('success', 'Holiday added successfully.');
        } catch (\Exception $e) {
            Log::error('Failed to create holiday: ' . $e->getMessage());
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * Update the specified holiday
     */
    public function update(Request $request, int $id)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'date' => 'required|date',
            'type' => 'required|string|in:' . implode(',', [
                Holiday::TYPE_PUBLIC,
                Holiday::TYPE_OPTIONAL,
                Holiday::TYPE_COMPANY,
                Holiday::TYPE_RESTRICTED,
            ]),
            'description' => 'nullable|string|max:1000',
        ]);

        try {
            $date = Carbon::parse($validated['date']);
            $validated['day'] = $date->format('l');

            $this->holidayService->updateHoliday($id, $validated);

            return redirect()->back()->with('success', 'Holiday updated successfully.');
        } catch (\Exception $e) {
            Log::error('Failed to update holiday: ' . $e->getMessage());
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * Toggle holiday status
     */
    public function toggleStatus(int $id): JsonResponse
    {
        try {
            $holiday = $this->holidayService->toggleStatus($id);
            return response()->json([
                'success' => true,
                'message' => 'Holiday status updated',
                'status' => $holiday->status,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Remove the specified holiday
     */
    public function destroy(int $id): JsonResponse
    {
        if (!$this->isSuperAdmin() && !$this->isManager()) {
            return response()->json(['success' => false, 'message' => 'Unauthorized.'], 403);
        }

        try {
            $this->holidayService->delete($id);
            return response()->json([
                'success' => true,
                'message' => 'Holiday deleted successfully',
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to delete holiday: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete holiday',
            ], 500);
        }
    }

    /**
     * Get upcoming holidays (API)
     */
    public function upcoming(Request $request): JsonResponse
    {
        $limit = $request->input('limit', 5);
        $holidays = $this->holidayService->getUpcoming($limit);

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

    /**
     * Check if a date is a holiday (API)
     */
    public function checkDate(Request $request): JsonResponse
    {
        $date = $request->input('date');

        if (!$date) {
            return response()->json([
                'success' => false,
                'message' => 'Date is required',
            ], 400);
        }

        $isHoliday = $this->holidayService->isHoliday($date);

        return response()->json([
            'success' => true,
            'is_holiday' => $isHoliday,
        ]);
    }
}
