<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Models\System\Holiday;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class HolidayController extends Controller
{
    public function index(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('system.holidays.index'));
        }

        return view('system.holidays.index');
    }

    public function list(Request $request): JsonResponse
    {
        $tenantId = session('selected_tenant_id', 1);
        $year = $request->input('year', now()->year);

        $holidays = Holiday::forTenant($tenantId)
            ->forYear($year)
            ->orderBy('start_date')
            ->get()
            ->map(function ($h) {
                return [
                    'id' => $h->id,
                    'startDate' => $h->start_date->format('Y-m-d'),
                    'endDate' => $h->end_date->format('Y-m-d'),
                    'name' => $h->name,
                    'type' => $h->type,
                    'isRecurring' => $h->is_recurring,
                    'memo' => $h->memo,
                    'days' => $h->start_date->diffInDays($h->end_date) + 1,
                ];
            });

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

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'name' => 'required|string|max:100',
            'startDate' => 'required|date',
            'endDate' => 'required|date|after_or_equal:startDate',
            'type' => 'required|in:public,company,alternative,temporary',
            'isRecurring' => 'boolean',
            'memo' => 'nullable|string|max:500',
        ]);

        $tenantId = session('selected_tenant_id', 1);

        // 중복 체크: 같은 날짜 + 같은 이름
        $exists = Holiday::forTenant($tenantId)
            ->where('start_date', $request->input('startDate'))
            ->where('end_date', $request->input('endDate'))
            ->where('name', $request->input('name'))
            ->exists();

        if ($exists) {
            return response()->json([
                'success' => false,
                'message' => '동일한 휴일이 이미 등록되어 있습니다.',
            ], 422);
        }

        $holiday = Holiday::create([
            'tenant_id' => $tenantId,
            'start_date' => $request->input('startDate'),
            'end_date' => $request->input('endDate'),
            'name' => $request->input('name'),
            'type' => $request->input('type', 'public'),
            'is_recurring' => $request->input('isRecurring', false),
            'memo' => $request->input('memo'),
        ]);

        return response()->json([
            'success' => true,
            'message' => '휴일이 등록되었습니다.',
            'data' => ['id' => $holiday->id],
        ]);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $tenantId = session('selected_tenant_id', 1);
        $holiday = Holiday::forTenant($tenantId)->findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:100',
            'startDate' => 'required|date',
            'endDate' => 'required|date|after_or_equal:startDate',
            'type' => 'required|in:public,company,alternative,temporary',
            'isRecurring' => 'boolean',
            'memo' => 'nullable|string|max:500',
        ]);

        $holiday->update([
            'start_date' => $request->input('startDate'),
            'end_date' => $request->input('endDate'),
            'name' => $request->input('name'),
            'type' => $request->input('type'),
            'is_recurring' => $request->input('isRecurring', false),
            'memo' => $request->input('memo'),
        ]);

        return response()->json([
            'success' => true,
            'message' => '휴일이 수정되었습니다.',
        ]);
    }

    public function destroy(int $id): JsonResponse
    {
        $tenantId = session('selected_tenant_id', 1);
        $holiday = Holiday::forTenant($tenantId)->findOrFail($id);
        $holiday->delete();

        return response()->json([
            'success' => true,
            'message' => '휴일이 삭제되었습니다.',
        ]);
    }

    public function bulkStore(Request $request): JsonResponse
    {
        $request->validate([
            'holidays' => 'required|array|min:1',
            'holidays.*.name' => 'required|string|max:100',
            'holidays.*.startDate' => 'required|date',
            'holidays.*.endDate' => 'required|date|after_or_equal:holidays.*.startDate',
            'holidays.*.type' => 'required|in:public,company,alternative,temporary',
            'holidays.*.isRecurring' => 'boolean',
        ]);

        $tenantId = session('selected_tenant_id', 1);
        $count = 0;
        $skipped = 0;

        foreach ($request->input('holidays') as $item) {
            // 중복 체크
            $exists = Holiday::forTenant($tenantId)
                ->where('start_date', $item['startDate'])
                ->where('end_date', $item['endDate'])
                ->where('name', $item['name'])
                ->exists();

            if ($exists) {
                $skipped++;

                continue;
            }

            Holiday::create([
                'tenant_id' => $tenantId,
                'start_date' => $item['startDate'],
                'end_date' => $item['endDate'],
                'name' => $item['name'],
                'type' => $item['type'] ?? 'public',
                'is_recurring' => $item['isRecurring'] ?? false,
                'memo' => $item['memo'] ?? null,
            ]);
            $count++;
        }

        $message = "{$count}건의 휴일이 등록되었습니다.";
        if ($skipped > 0) {
            $message .= " (중복 {$skipped}건 제외)";
        }

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

    /**
     * 해당 연도의 모든 휴일 삭제
     */
    public function destroyByYear(Request $request): JsonResponse
    {
        $request->validate([
            'year' => 'required|integer|min:2000|max:2100',
        ]);

        $tenantId = session('selected_tenant_id', 1);
        $year = $request->input('year');

        $count = Holiday::forTenant($tenantId)
            ->forYear($year)
            ->delete();

        return response()->json([
            'success' => true,
            'message' => "{$year}년도 휴일 {$count}건이 삭제되었습니다.",
            'data' => ['deleted' => $count],
        ]);
    }
}
