<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use App\Middleware\AuthSession;
use App\Middleware\TenantScope;
use App\Models\Asset;
use App\Models\Calibration;
use App\Models\Role;
use Core\Controller;
use Core\Session;
use Core\Tool;

final class CalibrationController extends Controller
{
    public function middleware(): array
    {
        return [AuthSession::class, TenantScope::class];
    }

    private function tenantId(): int { return (int) ($_SESSION['tenant_id'] ?? 0); }

    private function canManage(): bool
    {
        $role = Session::user()['role_code'] ?? '';
        return in_array($role, [Role::ADMIN, Role::EXECUTIVE, Role::PROJECT_MANAGER], true);
    }

    public function index(): void
    {
        $tenantId = $this->tenantId();
        $filters = array_filter(['status' => $_GET['status'] ?? null]);
        $this->render('calibration/index', [
            'schedules' => Calibration::listForTenant($tenantId, $filters),
            'counts'    => Calibration::countsForTenant($tenantId),
            'filters'   => $filters,
            'canManage' => $this->canManage(),
            'flash'     => Session::flash('cal_msg'),
        ]);
    }

    public function create(): void
    {
        if (!$this->canManage()) redirect('/Calibration');
        $tenantId = $this->tenantId();
        $this->render('calibration/form', [
            'schedule' => null,
            'assets'   => Asset::optionsForTenant($tenantId),
            'csrf'     => Tool::generateCsrf(),
        ]);
    }

    public function edit(int $id): void
    {
        if (!$this->canManage()) redirect('/Calibration');
        $tenantId = $this->tenantId();
        $sched = Calibration::findInTenant($tenantId, $id);
        if (!$sched) { Session::flash('cal_msg', 'Schedule not found.'); redirect('/Calibration'); }
        $this->render('calibration/form', [
            'schedule' => $sched,
            'assets'   => Asset::optionsForTenant($tenantId),
            'csrf'     => Tool::generateCsrf(),
        ]);
    }

    public function save(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/Calibration');
        if (!$this->canManage() || !Tool::checkCsrf($_POST['_csrf'] ?? null)) redirect('/Calibration');
        $tenantId = $this->tenantId();
        $id = (int) ($_POST['cal_schedule_id'] ?? 0);
        if (trim((string) ($_POST['name'] ?? '')) === '' || empty($_POST['asset_id'])) {
            Session::flash('cal_msg', 'Name and asset are required.');
            redirect($id > 0 ? "/Calibration/edit/{$id}" : '/Calibration/create');
        }
        if ($id > 0) {
            Calibration::updateSchedule($tenantId, $id, $_POST);
            Session::flash('cal_msg', 'Schedule updated.');
        } else {
            $id = Calibration::createSchedule($tenantId, $_POST);
            Session::flash('cal_msg', 'Schedule created.');
        }
        redirect('/Calibration/show/' . $id);
    }

    public function show(int $id): void
    {
        $tenantId = $this->tenantId();
        $sched = Calibration::findInTenant($tenantId, $id);
        if (!$sched) { Session::flash('cal_msg', 'Schedule not found.'); redirect('/Calibration'); }
        $this->render('calibration/show', [
            'schedule'  => $sched,
            'records'   => Calibration::recordsFor($id),
            'canManage' => $this->canManage(),
            'csrf'      => Tool::generateCsrf(),
            'flash'     => Session::flash('cal_msg'),
        ]);
    }

    public function delete(int $id): void
    {
        if (!$this->canManage()) redirect('/Calibration');
        Calibration::softDeleteSchedule($this->tenantId(), $id);
        Session::flash('cal_msg', 'Schedule deleted.');
        redirect('/Calibration');
    }

    public function record(int $id): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect("/Calibration/show/{$id}");
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) redirect("/Calibration/show/{$id}");
        $tenantId = $this->tenantId();
        $userId   = (int) (Session::user()['user_id'] ?? 0);
        Calibration::addRecord($tenantId, $id, $userId, $_POST);
        Session::flash('cal_msg', 'Calibration logged. Schedule rolled forward.');
        redirect("/Calibration/show/{$id}");
    }
}
