<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Holiday;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Carbon\Carbon;

class HolidayController extends Controller
{
    /**
     * Get list of holidays
     */
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();

        $query = Holiday::where(function ($q) use ($user) {
            $q->whereNull('company_id')
                ->orWhere('company_id', $user->company_id);
        })
            ->where('is_active', true)
            ->orderBy('date');

        // Filter by year
        if ($request->has('year')) {
            $query->whereYear('date', $request->year);
        } else {
            // Default: current year
            $query->whereYear('date', now()->year);
        }

        // Filter by month
        if ($request->has('month')) {
            $query->whereMonth('date', $request->month);
        }

        $holidays = $query->get();

        return response()->json([
            'success' => true,
            'holidays' => $holidays->map(function ($holiday) {
                return [
                    'id' => $holiday->id,
                    'date' => $holiday->date->format('Y-m-d'),
                    'name' => $holiday->name,
                    'description' => $holiday->description,
                    'is_recurring' => $holiday->is_recurring,
                    'day_name' => $holiday->date->translatedFormat('l'),
                ];
            }),
        ]);
    }

    /**
     * Check if a specific date is a holiday
     */
    public function check(Request $request): JsonResponse
    {
        $user = $request->user();
        $company = $user->company;

        $validated = $request->validate([
            'date' => 'required|date',
        ]);

        $date = Carbon::parse($validated['date']);
        $isWeekend = $company->isWeekend($date);
        $isTanggalMerah = Holiday::isHoliday($date, $company->id);
        $isHoliday = $isWeekend || $isTanggalMerah;

        $holidayInfo = null;
        if ($isTanggalMerah) {
            $holiday = Holiday::where(function ($q) use ($user) {
                $q->whereNull('company_id')
                    ->orWhere('company_id', $user->company_id);
            })
                ->where('is_active', true)
                ->where('date', $date->toDateString())
                ->first();

            if ($holiday) {
                $holidayInfo = [
                    'name' => $holiday->name,
                    'description' => $holiday->description,
                ];
            }
        }

        $dayName = $date->translatedFormat('l');

        return response()->json([
            'success' => true,
            'date' => $date->format('Y-m-d'),
            'day_name' => $dayName,
            'is_holiday' => $isHoliday,
            'is_weekend' => $isWeekend,
            'is_tanggal_merah' => $isTanggalMerah,
            'holiday_info' => $holidayInfo,
            'can_overtime' => $isHoliday && $company->overtime_enabled,
        ]);
    }

    /**
     * Get upcoming holidays
     */
    public function upcoming(Request $request): JsonResponse
    {
        $user = $request->user();
        $limit = $request->limit ?? 5;

        $holidays = Holiday::where(function ($q) use ($user) {
            $q->whereNull('company_id')
                ->orWhere('company_id', $user->company_id);
        })
            ->where('is_active', true)
            ->where('date', '>=', now()->toDateString())
            ->orderBy('date')
            ->limit($limit)
            ->get();

        return response()->json([
            'success' => true,
            'holidays' => $holidays->map(function ($holiday) {
                return [
                    'id' => $holiday->id,
                    'date' => $holiday->date->format('Y-m-d'),
                    'name' => $holiday->name,
                    'description' => $holiday->description,
                    'day_name' => $holiday->date->translatedFormat('l'),
                    'days_until' => now()->diffInDays($holiday->date),
                ];
            }),
        ]);
    }

    /**
     * Store a new holiday (admin only)
     */
    public function store(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['super_admin', 'admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Hanya admin yang dapat menambahkan hari libur',
            ], 403);
        }

        $validated = $request->validate([
            'date' => 'required|date',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string|max:500',
            'is_recurring' => 'boolean',
            'is_company_specific' => 'boolean',
        ]);

        $holiday = Holiday::create([
            'company_id' => ($validated['is_company_specific'] ?? false) ? $user->company_id : null,
            'date' => $validated['date'],
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'is_recurring' => $validated['is_recurring'] ?? false,
            'is_active' => true,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Hari libur berhasil ditambahkan',
            'holiday' => $holiday,
        ], 201);
    }

    /**
     * Update a holiday (admin only)
     */
    public function update(Request $request, Holiday $holiday): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['super_admin', 'admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Hanya admin yang dapat mengubah hari libur',
            ], 403);
        }

        // Check access (company specific holiday)
        if ($holiday->company_id && $holiday->company_id !== $user->company_id) {
            return response()->json([
                'success' => false,
                'message' => 'Tidak memiliki akses',
            ], 403);
        }

        $validated = $request->validate([
            'date' => 'sometimes|date',
            'name' => 'sometimes|string|max:255',
            'description' => 'nullable|string|max:500',
            'is_recurring' => 'sometimes|boolean',
            'is_active' => 'sometimes|boolean',
        ]);

        $holiday->update($validated);

        return response()->json([
            'success' => true,
            'message' => 'Hari libur berhasil diperbarui',
            'holiday' => $holiday,
        ]);
    }

    /**
     * Delete a holiday (admin only)
     */
    public function destroy(Request $request, Holiday $holiday): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['super_admin', 'admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Hanya admin yang dapat menghapus hari libur',
            ], 403);
        }

        // Check access (company specific holiday)
        if ($holiday->company_id && $holiday->company_id !== $user->company_id) {
            return response()->json([
                'success' => false,
                'message' => 'Tidak memiliki akses',
            ], 403);
        }

        $holiday->delete();

        return response()->json([
            'success' => true,
            'message' => 'Hari libur berhasil dihapus',
        ]);
    }

    /**
     * Get weekend settings
     */
    public function weekendSettings(Request $request): JsonResponse
    {
        $user = $request->user();
        $company = $user->company;

        $days = [
            ['value' => 0, 'label' => 'Minggu'],
            ['value' => 1, 'label' => 'Senin'],
            ['value' => 2, 'label' => 'Selasa'],
            ['value' => 3, 'label' => 'Rabu'],
            ['value' => 4, 'label' => 'Kamis'],
            ['value' => 5, 'label' => 'Jumat'],
            ['value' => 6, 'label' => 'Sabtu'],
        ];

        return response()->json([
            'success' => true,
            'weekend_days' => $company->weekend_days ?? [0, 6],
            'available_days' => $days,
        ]);
    }

    /**
     * Update weekend settings (admin only)
     */
    public function updateWeekendSettings(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole('super_admin')) {
            return response()->json([
                'success' => false,
                'message' => 'Hanya super admin yang dapat mengubah pengaturan hari libur',
            ], 403);
        }

        $validated = $request->validate([
            'weekend_days' => 'required|array',
            'weekend_days.*' => 'integer|between:0,6',
        ]);

        $company = $user->company;
        $company->update(['weekend_days' => $validated['weekend_days']]);

        return response()->json([
            'success' => true,
            'message' => 'Pengaturan hari libur berhasil diperbarui',
            'weekend_days' => $company->weekend_days,
        ]);
    }
}
