<?php

namespace App\Http\Controllers\Finance;

use App\Http\Controllers\Controller;
use App\Models\Finance\BankAccount;
use App\Models\Finance\FundSchedule;
use App\Models\System\Holiday;
use App\Services\FundScheduleService;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Response;

class FundScheduleController extends Controller
{
    public function __construct(
        private FundScheduleService $fundScheduleService
    ) {}

    /**
     * 자금계획일정 목록 (캘린더 뷰)
     */
    public function index(): View|Response
    {
        if (request()->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('finance.fund-schedules.index', request()->only('year', 'month')));
        }

        // 현재 연월
        $year = (int) request('year', now()->year);
        $month = (int) request('month', now()->month);

        // 월별 일정 데이터
        $calendarData = $this->fundScheduleService->getCalendarData($year, $month);

        // 월별 요약
        $summary = $this->fundScheduleService->getMonthlySummary($year, $month);

        // 계좌 목록 (필터용)
        $accounts = BankAccount::active()->ordered()->get(['id', 'bank_name', 'account_number']);

        // 휴일 데이터 (달력 표시용)
        $tenantId = session('selected_tenant_id', 1);
        $holidayMap = $this->getHolidayMap($tenantId, $year, $month);

        return view('finance.fund-schedules.index', compact(
            'year',
            'month',
            'calendarData',
            'summary',
            'accounts',
            'holidayMap'
        ));
    }

    /**
     * 자금계획일정 등록 폼
     */
    public function create(): View
    {
        $accounts = BankAccount::active()->ordered()->get(['id', 'bank_name', 'account_number', 'account_name']);
        $types = FundSchedule::getTypeOptions();
        $statuses = FundSchedule::getStatusOptions();
        $recurrenceOptions = FundSchedule::getRecurrenceOptions();

        // 기본 날짜 (쿼리스트링에서)
        $defaultDate = request('date', now()->toDateString());

        return view('finance.fund-schedules.create', compact(
            'accounts',
            'types',
            'statuses',
            'recurrenceOptions',
            'defaultDate'
        ));
    }

    /**
     * 자금계획일정 수정 폼
     */
    public function edit(int $id): View
    {
        $schedule = $this->fundScheduleService->getScheduleById($id);

        if (! $schedule) {
            abort(404, '일정을 찾을 수 없습니다.');
        }

        $accounts = BankAccount::active()->ordered()->get(['id', 'bank_name', 'account_number', 'account_name']);
        $types = FundSchedule::getTypeOptions();
        $statuses = FundSchedule::getStatusOptions();
        $recurrenceOptions = FundSchedule::getRecurrenceOptions();

        return view('finance.fund-schedules.edit', compact(
            'schedule',
            'accounts',
            'types',
            'statuses',
            'recurrenceOptions'
        ));
    }

    /**
     * 자금계획일정 상세
     */
    public function show(int $id): View
    {
        $schedule = $this->fundScheduleService->getScheduleById($id);

        if (! $schedule) {
            abort(404, '일정을 찾을 수 없습니다.');
        }

        return view('finance.fund-schedules.show', compact('schedule'));
    }

    /**
     * 해당 월의 휴일 맵 생성 (날짜 => 휴일명)
     */
    private function getHolidayMap(int $tenantId, int $year, int $month): array
    {
        $startOfMonth = \Carbon\Carbon::create($year, $month, 1)->startOfWeek(\Carbon\Carbon::SUNDAY);
        $endOfMonth = \Carbon\Carbon::create($year, $month, 1)->endOfMonth()->endOfWeek(\Carbon\Carbon::SATURDAY);

        $holidays = Holiday::forTenant($tenantId)
            ->where('start_date', '<=', $endOfMonth->toDateString())
            ->where('end_date', '>=', $startOfMonth->toDateString())
            ->get();

        $map = [];
        foreach ($holidays as $holiday) {
            $start = $holiday->start_date->copy();
            $end = $holiday->end_date->copy();
            for ($d = $start; $d->lte($end); $d->addDay()) {
                $key = $d->format('Y-m-d');
                $map[$key] = $holiday->name;
            }
        }

        return $map;
    }
}
