<?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\Training;
use App\Models\User;
use Core\Controller;
use Core\Session;
use Core\Tool;

/**
 * Training records + course catalogue.
 *   /Training                 → landing (both records + courses side-by-side)
 *   /Training/createCourse    → new course
 *   /Training/editCourse/{id} → edit course
 *   /Training/newRecord       → log a completion
 *   /Training/editRecord/{id} → edit a record
 *   /Training/showRecord/{id} → view + attach cert PDF
 */
final class TrainingController 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([
            'course_id' => $_GET['course_id'] ?? null,
            'user_id'   => $_GET['user_id']   ?? null,
            'status'    => $_GET['status']    ?? null,
        ]);
        $this->render('training/index', [
            'records'   => Training::recordsForTenant($tenantId, $filters),
            'courses'   => Training::coursesForTenant($tenantId),
            'users'     => User::listForTenant($tenantId),
            'counts'    => Training::countsForTenant($tenantId),
            'filters'   => $filters,
            'canManage' => $this->canManage(),
            'flash'     => Session::flash('hse_msg'),
        ]);
    }

    // ── Courses ─────────────────────────────────────────────────────────

    public function createCourse(): void
    {
        if (!$this->canManage()) redirect('/Training');
        $this->render('training/course-form', [
            'course' => null,
            'csrf'   => Tool::generateCsrf(),
        ]);
    }

    public function editCourse(int $id): void
    {
        if (!$this->canManage()) redirect('/Training');
        $course = Training::findCourse($this->tenantId(), $id);
        if (!$course) { Session::flash('hse_msg', 'Course not found.'); redirect('/Training'); }
        $this->render('training/course-form', [
            'course' => $course,
            'csrf'   => Tool::generateCsrf(),
        ]);
    }

    public function saveCourse(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/Training');
        if (!$this->canManage() || !Tool::checkCsrf($_POST['_csrf'] ?? null)) redirect('/Training');
        $tenantId = $this->tenantId();
        $id = (int) ($_POST['course_id'] ?? 0);
        if (trim((string) ($_POST['name'] ?? '')) === '') {
            Session::flash('hse_msg', 'Name is required.');
            redirect($id > 0 ? "/Training/editCourse/{$id}" : '/Training/createCourse');
        }
        if ($id > 0) {
            Training::updateCourse($tenantId, $id, $_POST);
            Session::flash('hse_msg', 'Course updated.');
        } else {
            Training::createCourse($tenantId, $_POST);
            Session::flash('hse_msg', 'Course added.');
        }
        redirect('/Training');
    }

    public function deleteCourse(int $id): void
    {
        if (!$this->canManage()) redirect('/Training');
        Training::softDeleteCourse($this->tenantId(), $id);
        Session::flash('hse_msg', 'Course removed.');
        redirect('/Training');
    }

    // ── Records ─────────────────────────────────────────────────────────

    public function newRecord(): void
    {
        if (!$this->canManage()) redirect('/Training');
        $tenantId = $this->tenantId();
        $this->render('training/record-form', [
            'record'  => null,
            'courses' => Training::coursesForTenant($tenantId, true),
            'users'   => User::listForTenant($tenantId),
            'csrf'    => Tool::generateCsrf(),
        ]);
    }

    public function editRecord(int $id): void
    {
        if (!$this->canManage()) redirect('/Training');
        $tenantId = $this->tenantId();
        $record = Training::findRecord($tenantId, $id);
        if (!$record) { Session::flash('hse_msg', 'Record not found.'); redirect('/Training'); }
        $this->render('training/record-form', [
            'record'  => $record,
            'courses' => Training::coursesForTenant($tenantId, true),
            'users'   => User::listForTenant($tenantId),
            'csrf'    => Tool::generateCsrf(),
        ]);
    }

    public function saveRecord(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') redirect('/Training');
        if (!$this->canManage() || !Tool::checkCsrf($_POST['_csrf'] ?? null)) redirect('/Training');
        $tenantId = $this->tenantId();
        $id = (int) ($_POST['record_id'] ?? 0);
        if (empty($_POST['course_id']) || empty($_POST['completed_at'])) {
            Session::flash('hse_msg', 'Course and completion date are required.');
            redirect($id > 0 ? "/Training/editRecord/{$id}" : '/Training/newRecord');
        }
        if ($id > 0) {
            Training::updateRecord($tenantId, $id, $_POST);
            Session::flash('hse_msg', 'Training record updated.');
        } else {
            $id = Training::createRecord($tenantId, $_POST);
            Session::flash('hse_msg', 'Training logged — attach the certificate PDF from the detail page.');
        }
        redirect('/Training/showRecord/' . $id);
    }

    public function showRecord(int $id): void
    {
        $tenantId = $this->tenantId();
        $record = Training::findRecord($tenantId, $id);
        if (!$record) { Session::flash('hse_msg', 'Record not found.'); redirect('/Training'); }
        $this->render('training/show-record', [
            'record'      => $record,
            'attachments' => Attachment::forOwner($tenantId, 'training_record', $id),
            'ownerType'   => 'training_record',
            'ownerId'     => $id,
            'canManage'   => $this->canManage(),
            'csrf'        => Tool::generateCsrf(),
            'flash'       => Session::flash('hse_msg') ?: Session::flash('attach_msg'),
        ]);
    }

    public function deleteRecord(int $id): void
    {
        if (!$this->canManage()) redirect('/Training');
        Training::softDeleteRecord($this->tenantId(), $id);
        Session::flash('hse_msg', 'Record removed.');
        redirect('/Training');
    }
}
