<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use App\Middleware\AuthSession;
use App\Middleware\TenantScope;
use App\Models\Site;
use Core\Controller;
use Core\Session;
use Core\Tool;

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

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

    public function index(): void
    {
        $this->render('sites/index', [
            'sites' => Site::listForTenant($this->tenantId()),
            'flash' => Session::flash('sites_msg'),
        ]);
    }

    public function create(): void
    {
        $this->render('sites/form', [
            'site'    => null,
            'parents' => Site::optionsForTenant($this->tenantId()),
            'csrf'    => Tool::generateCsrf(),
        ]);
    }

    public function edit(int $id): void
    {
        $site = Site::findInTenant($this->tenantId(), $id);
        if (!$site) { Session::flash('sites_msg', 'Site not found.'); redirect('/Sites'); }
        $this->render('sites/form', [
            'site'    => $site,
            'parents' => Site::optionsForTenant($this->tenantId(), $id),
            'csrf'    => Tool::generateCsrf(),
        ]);
    }

    public function save(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/Sites');
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) {
            Session::flash('sites_msg', 'Session expired.');
            redirect('/Sites');
        }
        $tenantId = $this->tenantId();
        $userId   = (int) (Session::user()['user_id'] ?? 0);
        $id       = (int) ($_POST['site_id'] ?? 0);

        if (trim((string) ($_POST['name'] ?? '')) === '') {
            Session::flash('sites_msg', 'Name is required.');
            redirect($id > 0 ? "/Sites/edit/{$id}" : '/Sites/create');
        }

        if ($id > 0) {
            $existing = Site::findInTenant($tenantId, $id);
            if (!$existing) { Session::flash('sites_msg', 'Site not found.'); redirect('/Sites'); }
            Site::update($tenantId, $id, $_POST);
            Session::flash('sites_msg', 'Site updated.');
        } else {
            $id = Site::create($tenantId, $userId, $_POST);
            Session::flash('sites_msg', 'Site created.');
        }
        redirect("/Sites/show/{$id}");
    }

    public function show(int $id): void
    {
        $site = Site::findInTenant($this->tenantId(), $id);
        if (!$site) { Session::flash('sites_msg', 'Site not found.'); redirect('/Sites'); }
        $this->render('sites/show', [
            'site'  => $site,
            'flash' => Session::flash('sites_msg'),
        ]);
    }

    public function delete(int $id): void
    {
        Site::softDelete($this->tenantId(), $id);
        Session::flash('sites_msg', 'Site deleted.');
        redirect('/Sites');
    }
}
