<?php
declare(strict_types=1);

require_once __DIR__ . '/../../system/bootstrap.php';
require_once __DIR__ . '/../../system/auth.php';
require_once __DIR__ . '/../../system/audit.php';
require_once __DIR__ . '/../../system/pdf/MdPdfGenerator.php';

header('Content-Type: application/json');

$user = require_auth($pdo);

/* =========================================================
   METHOD ENFORCEMENT
   ========================================================= */

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'POST required']);
    exit;
}

/* =========================================================
   INPUT
   ========================================================= */

$input = json_decode(file_get_contents('php://input'), true);
$declarationId = (int)($input['declaration_id'] ?? 0);

if ($declarationId <= 0) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid declaration_id']);
    exit;
}

/* =========================================================
   GENERATION
   ========================================================= */

try {

    /**
     * MdPdfGenerator MUST:
     * - verify declaration exists
     * - verify status = completed
     * - verify shiftboss signature exists
     * - return existing PDF path if already generated
     * - otherwise generate + persist PDF
     */
    $result = MdPdfGenerator::generate($pdo, $declarationId);

    audit_log(
        $pdo,
        $user,
        'generate',
        'md_pdf',
        $declarationId,
        [
            'pdf_path' => $result['path'],
            'regenerated' => $result['regenerated'] ?? false
        ]
    );

    echo json_encode([
        'success' => true,
        'pdf_path' => $result['path'],
        'generated_at' => $result['generated_at'] ?? date('c')
    ]);

} catch (Throwable $e) {

    http_response_code(409);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
