<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\ForbiddenHttpException;

/**
 * BaseController — extended by ALL controllers except SiteController.
 *
 * Position rules:
 *  - Guest       → redirect to login (except site/login, site/error)
 *  - admin       → full access everywhere
 *  - client      → only routes listed in $clientAllowedRoutes
 *  - other/unknown → 403 Forbidden
 */
class BaseController extends Controller
{
    /**
     * Routes clients are allowed to access.
     * Format: 'controller-id/action-id'
     */
    private array $clientAllowedRoutes = [
        // ── Client portal ─────────────────────────────────
        'client/dashboard',
        'client/my-cars',
        'client/view-car',
        'client/profile',
        'client/change-password',

        // ── Site ──────────────────────────────────────────
        'site/error',
        'site/logout',
        'site/contact',
        'site/about',
    ];

    public function beforeAction($action): bool
    {
        if (!parent::beforeAction($action)) {
            return false;
        }

        $currentRoute = $this->id . '/' . $action->id;

        // ── Guest → redirect to login ──────────────────────
        if (Yii::$app->user->isGuest) {
            $guestAllowed = ['site/login', 'site/error'];
            if (!in_array($currentRoute, $guestAllowed, true)) {
                Yii::$app->response->redirect(['/site/login']);
                return false;
            }
            return true;
        }

        $position = Yii::$app->user->identity->position ?? '';

        // ── Admin → full access ────────────────────────────
        if ($position === 'admin') {
            return true;
        }

        // ── Client → whitelist only ────────────────────────
        if ($position === 'client') {
            if (in_array($currentRoute, $this->clientAllowedRoutes, true)) {
                return true;
            }
            throw new ForbiddenHttpException(
                'You do not have permission to access this page.'
            );
        }

        // ── Unknown position ───────────────────────────────
        throw new ForbiddenHttpException('Access denied.');
    }
}
