<?php
declare(strict_types=1);

require_once __DIR__ . '/../pandadoc_integration/orchestrator.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// Simple shared-secret auth for manual triggering (optional).
$expected = (string)pd_env('PANDADOC_ACTION_TOKEN', '');
if ($expected !== '') {
    $auth = (string)($_SERVER['HTTP_AUTHORIZATION'] ?? '');
    $token = '';
    if (preg_match('~^Bearer\\s+(.+)$~i', trim($auth), $m)) $token = trim($m[1]);
    if ($token === '') $token = (string)($_GET['token'] ?? '');
    if (!hash_equals($expected, $token)) {
        pd_json(403, ['success' => false, 'error' => 'Forbidden']);
    }
}

$body = pd_json_body();
$orderId = (int)($body['order_id'] ?? ($_GET['order_id'] ?? 0));
$drivePdfUrl = $body['drive_pdf_url'] ?? ($_GET['drive_pdf_url'] ?? null);

if ($orderId <= 0) {
    pd_json(400, ['success' => false, 'error' => 'Provide order_id']);
}

$result = pd_run_generate_for_order($orderId, is_string($drivePdfUrl) ? $drivePdfUrl : null);
pd_json($result['success'] ? 200 : 500, $result);

