<?php

namespace App\Http\Controllers\HR;

use App\Http\Controllers\Controller;
use App\Services\HR\LeaveService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class LeavePromotionController extends Controller
{
    public function __construct(
        private LeaveService $leaveService
    ) {}

    public function index(Request $request): \Illuminate\Contracts\View\View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('hr.leave-promotions.index'));
        }

        $year = (int) ($request->get('year', now()->year));

        $candidates = $this->leaveService->getPromotionCandidates($year);

        $stats = [
            'total' => $candidates->count(),
            'not_sent' => $candidates->where('promotion_status', 'not_sent')->count(),
            'first_sent' => $candidates->where('promotion_status', 'first_sent')->count(),
            'completed' => $candidates->where('promotion_status', 'completed')->count(),
        ];

        return view('hr.leave-promotions.index', [
            'candidates' => $candidates,
            'stats' => $stats,
            'year' => $year,
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'employee_ids' => 'required|array|min:1',
            'employee_ids.*' => 'integer',
            'notice_type' => 'required|in:1st,2nd',
            'deadline' => 'required_if:notice_type,1st|date',
            'designated_dates' => 'nullable|array',
            'designated_dates.*' => 'date',
        ]);

        $year = (int) ($request->get('year', now()->year));
        $noticeType = $request->get('notice_type');
        $employeeIds = $request->get('employee_ids');

        $result = $this->leaveService->sendPromotionNotices(
            employeeIds: $employeeIds,
            noticeType: $noticeType,
            year: $year,
            deadline: $request->get('deadline'),
            designatedDates: $request->get('designated_dates', []),
        );

        return response()->json([
            'success' => true,
            'message' => count($result['created']).'건의 연차촉진 통지서가 생성되었습니다.',
            'created' => $result['created'],
            'skipped' => $result['skipped'],
        ]);
    }
}
