<?php
declare(strict_types=1);

require_once __DIR__ . '/../pandadoc_integration/bootstrap.php';
require_once __DIR__ . '/../pandadoc_integration/db.php';
require_once __DIR__ . '/../pandadoc_integration/pandadoc.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;
}

$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();
$documentId = trim((string)($body['document_id'] ?? ($_GET['document_id'] ?? '')));
$orderId = (int)($body['order_id'] ?? ($_GET['order_id'] ?? 0));

pd_db_ensure_tables();

if ($documentId === '' && $orderId > 0) {
    $pdo = pd_db();
    $stmt = $pdo->prepare('SELECT pandadoc_document_id FROM pandadoc_orders WHERE shopify_order_id = ? LIMIT 1');
    $stmt->execute([$orderId]);
    /**
     * @var mixed $fetched
     */
    $fetched = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!is_array($fetched) || empty($fetched['pandadoc_document_id'])) {
        pd_json(404, ['success' => false, 'error' => 'No pandadoc_document_id for this order']);
    }
    $documentId = trim((string)$fetched['pandadoc_document_id']);
}

if ($documentId === '') {
    pd_json(400, ['success' => false, 'error' => 'Provide document_id or order_id']);
}

$shopifyForFile = $orderId > 0 ? $orderId : null;
$store = pandadoc_store_document_pdf_clean($documentId, $shopifyForFile);

if (!$store['success']) {
    pd_json(400, ['success' => false, 'error' => $store['error'] ?? 'Store failed', 'http' => $store['http'] ?? null, 'details' => $store]);
}

if ($orderId > 0) {
    pd_db_update_order($orderId, [
        'completed_pdf_path' => (string)($store['original_path'] ?? ''),
        'completed_pdf_clean_path' => (string)($store['clean_path'] ?? ($store['original_path'] ?? '')),
    ]);
}

pd_json(200, [
    'success' => true,
    'original_path' => $store['original_path'] ?? null,
    'clean_path' => $store['clean_path'] ?? null,
    'bytes' => $store['original_bytes'] ?? 0,
    'removed_pages' => $store['removed_pages'] ?? [],
    'document_id' => $documentId,
    'order_id' => $orderId > 0 ? $orderId : null,
]);
