<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use App\Middleware\AuthSession;
use App\Middleware\TenantScope;
use App\Models\Attachment;
use App\Models\Role;
use App\Models\Sds;
use Core\Controller;
use Core\Session;
use Core\Tool;

final class SdsController 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([
            'q'            => $_GET['q']            ?? null,
            'hazard_class' => $_GET['hazard_class'] ?? null,
            'due_soon'     => $_GET['due_soon']     ?? null,
        ]);
        $this->render('sds/index', [
            'sheets'    => Sds::listForTenant($tenantId, $filters),
            'counts'    => Sds::countsForTenant($tenantId),
            'filters'   => $filters,
            'canManage' => $this->canManage(),
            'flash'     => Session::flash('hse_msg'),
        ]);
    }

    public function create(): void
    {
        if (!$this->canManage()) redirect('/Sds');
        $this->render('sds/form', [
            'sheet' => null,
            'csrf'  => Tool::generateCsrf(),
        ]);
    }

    public function edit(int $id): void
    {
        if (!$this->canManage()) redirect('/Sds');
        $sheet = Sds::findInTenant($this->tenantId(), $id);
        if (!$sheet) { Session::flash('hse_msg', 'SDS not found.'); redirect('/Sds'); }
        $this->render('sds/form', [
            'sheet' => $sheet,
            'csrf'  => Tool::generateCsrf(),
        ]);
    }

    public function save(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/Sds');
        if (!$this->canManage() || !Tool::checkCsrf($_POST['_csrf'] ?? null)) redirect('/Sds');
        $tenantId = $this->tenantId();
        $id = (int) ($_POST['sds_id'] ?? 0);
        if (trim((string) ($_POST['name'] ?? '')) === '') {
            Session::flash('hse_msg', 'Name is required.');
            redirect($id > 0 ? "/Sds/edit/{$id}" : '/Sds/create');
        }
        if ($id > 0) {
            Sds::update($tenantId, $id, $_POST);
            Session::flash('hse_msg', 'SDS updated.');
        } else {
            $id = Sds::create($tenantId, $_POST);
            Session::flash('hse_msg', 'SDS added — attach the SDS PDF from the detail page.');
        }
        redirect('/Sds/show/' . $id);
    }

    public function show(int $id): void
    {
        $tenantId = $this->tenantId();
        $sheet = Sds::findInTenant($tenantId, $id);
        if (!$sheet) { Session::flash('hse_msg', 'SDS not found.'); redirect('/Sds'); }
        $this->render('sds/show', [
            'sheet'       => $sheet,
            'attachments' => Attachment::forOwner($tenantId, 'sds', $id),
            'ownerType'   => 'sds',
            'ownerId'     => $id,
            'canManage'   => $this->canManage(),
            'csrf'        => Tool::generateCsrf(),
            'flash'       => Session::flash('hse_msg') ?: Session::flash('attach_msg'),
        ]);
    }

    public function delete(int $id): void
    {
        if (!$this->canManage()) redirect('/Sds');
        Sds::softDelete($this->tenantId(), $id);
        Session::flash('hse_msg', 'SDS deleted.');
        redirect('/Sds');
    }
}
