<?php

namespace App\Controllers\View;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\RedirectResponse;

final class SchoolYearSelectionController extends BaseController
{
    public function select(): RedirectResponse
    {
        $schoolYearId = (int) ($this->request->getPost('school_year_id') ?? 0);
        $returnTo = (string) ($this->request->getPost('return_to') ?? '');

        if ($schoolYearId <= 0) {
            return redirect()->to($this->safeReturnTo($returnTo))
                ->with('error', 'Please select a valid school year.');
        }

        try {
            service('schoolYearContext')->select($schoolYearId);
            return redirect()->to($this->safeReturnTo($returnTo));
        } catch (\Throwable $e) {
            log_message('warning', 'School-year selection failed: {message}', [
                'message' => $e->getMessage(),
            ]);

            return redirect()->to($this->safeReturnTo($returnTo))
                ->with('error', 'The selected school year is not available.');
        }
    }

    public function reset(): RedirectResponse
    {
        service('schoolYearContext')->clearSelection();

        return redirect()->to($this->safeReturnTo((string) ($this->request->getPost('return_to') ?? '')));
    }

    private function safeReturnTo(string $returnTo): string
    {
        $fallback = $this->dashboardRoute();
        $returnTo = trim($returnTo);

        if ($returnTo === '') {
            return $fallback;
        }

        $parts = parse_url($returnTo);
        if ($parts === false) {
            return $fallback;
        }

        if (isset($parts['host']) && strcasecmp((string) $parts['host'], (string) $this->request->getUri()->getHost()) !== 0) {
            return $fallback;
        }

        $path = '/' . ltrim((string) ($parts['path'] ?? ''), '/');
        if ($path === '/' || str_starts_with($path, '//')) {
            return $fallback;
        }

        $path = $this->normalizeSchoolYearReturnPath($path);

        $query = [];
        if (! empty($parts['query'])) {
            parse_str((string) $parts['query'], $query);
            foreach (['school_year_id', 'school_year', 'schoolYear', 'year'] as $key) {
                unset($query[$key]);
            }
        }

        $cleanQuery = http_build_query($query);

        return $path . ($cleanQuery !== '' ? '?' . $cleanQuery : '');
    }

    private function normalizeSchoolYearReturnPath(string $path): string
    {
        if (preg_match('#^/(parent|teacher|admin)/progress/view/\d+$#', $path, $matches) === 1) {
            return '/' . $matches[1] . '/progress';
        }

        return $path;
    }

    private function dashboardRoute(): string
    {
        try {
            return service('roleService')->bestDashboardRouteFor((array) session()->get('roles'));
        } catch (\Throwable) {
            return '/landing_page/guest_dashboard';
        }
    }
}
