<?php
declare(strict_types=1);

namespace App\Modules\HR\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\HR\Models\HrHoliday;

class HolidayController extends Controller
{
    public function index(Request $request): Response
    {
        $year = (int) $request->get('year', (int) date('Y'));

        $holidays = HrHoliday::getForYear($year);

        return $this->view('HR.Views.holidays.index', [
            'holidays' => $holidays,
            'year'     => $year,
        ]);
    }

    public function create(Request $request): Response
    {
        return $this->view('HR.Views.holidays.form', [
            'holiday' => null,
        ]);
    }

    public function store(Request $request): Response
    {
        $data = $this->extractData($request);
        $errors = $this->validateInput($data);

        if (!empty($errors)) {
            return $this->flashErrorsAndRedirect($errors, $request, '/hr/holidays/create');
        }

        HrHoliday::create($data);

        return $this->redirect('/hr/holidays')->withSuccess('تم إنشاء العطلة بنجاح');
    }

    public function edit(Request $request, string $id): Response
    {
        $holiday = HrHoliday::find((int) $id);
        if (!$holiday) {
            return $this->redirect('/hr/holidays')->withError('العطلة غير موجودة');
        }

        return $this->view('HR.Views.holidays.form', [
            'holiday' => $holiday,
        ]);
    }

    public function update(Request $request, string $id): Response
    {
        $holiday = HrHoliday::find((int) $id);
        if (!$holiday) {
            return $this->redirect('/hr/holidays')->withError('العطلة غير موجودة');
        }

        $data = $this->extractData($request);
        $errors = $this->validateInput($data);

        if (!empty($errors)) {
            return $this->flashErrorsAndRedirect($errors, $request, '/hr/holidays/' . $id . '/edit');
        }

        $holiday->update($data);

        return $this->redirect('/hr/holidays')->withSuccess('تم تحديث العطلة بنجاح');
    }

    public function archive(Request $request, string $id): Response
    {
        $holiday = HrHoliday::find((int) $id);
        if (!$holiday) {
            return $this->redirect('/hr/holidays')->withError('العطلة غير موجودة');
        }

        $holiday->archive();

        return $this->redirect('/hr/holidays')->withSuccess('تم حذف العطلة بنجاح');
    }

    private function extractData(Request $request): array
    {
        return [
            'name_ar'      => trim((string) $request->post('name_ar', '')),
            'name_en'      => trim((string) $request->post('name_en', '')) ?: null,
            'date' => trim((string) $request->post('date', '')),
            'duration_days' => max(1, (int) $request->post('duration_days', 1)),
            'holiday_type' => trim((string) $request->post('holiday_type', 'national')),
            'is_recurring' => (int) ($request->post('is_recurring', 0)),
            'religion'     => trim((string) $request->post('religion', '')) ?: null,
            'is_active'    => (int) ($request->post('is_active', 1)),
        ];
    }

    private function validateInput(array $data): array
    {
        $errors = [];
        if ($data['name_ar'] === '' || mb_strlen($data['name_ar']) < 2) {
            $errors[] = 'اسم العطلة بالعربي مطلوب';
        }
        if ($data['date'] === '') {
            $errors[] = 'تاريخ العطلة مطلوب';
        }
        if (!in_array($data['holiday_type'], ['national', 'religious', 'company'], true)) {
            $errors[] = 'نوع العطلة غير صالح';
        }
        return $errors;
    }

    private function flashErrorsAndRedirect(array $errors, Request $request, string $url): Response
    {
        $session = App::getInstance()->session();
        $session->flash('_alerts', array_map(fn($e) => ['type' => 'error', 'message' => $e], $errors));
        $session->flash('_old_input', $request->all());
        return $this->redirect($url);
    }
}
