<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\Event\EventInterface;
use Cake\Http\Exception\ForbiddenException;
use Cake\I18n\DateTime;


class AdminController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('Authentication.Authentication');
    }

    public function beforeFilter(EventInterface $event): void
    {
        parent::beforeFilter($event);

        $result = $this->Authentication->getResult();
        if (!$result || !$result->isValid()) {
            $this->redirect(['controller' => 'Auth', 'action' => 'login']);
            return;
        }

        $identity = $this->request->getAttribute('identity');
        $role = $identity->role ?? null;
        if (!in_array($role, ['admin', 'super'], true)) {
            throw new ForbiddenException('Admins only.');
        }
    }

    /**
     * Admin dashboard
     */
    public function index()
    {
        $identity = $this->request->getAttribute('identity');
        $role = $identity->role ?? 'admin';
        $isSuper = ($role === 'super');

        $pendingCount = 0;
        if ($isSuper) {
            $ChangeRequests = $this->fetchTable('ChangeRequests');
            $pendingCount = $ChangeRequests->find()
                ->where(['status' => 'pending'])
                ->count();
        }

        $this->set(compact('pendingCount', 'isSuper', 'role'));
    }
}
