<?php
declare(strict_types=1);

require_once __DIR__ . '/../pandadoc_integration/db.php';
require_once __DIR__ . '/../pandadoc_integration/shopify.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// PandaDoc signature verification (accept signature from query param OR header so URL can be used without ?signature=).
// Webhook URL to enter in PandaDoc: https://vintage.espirevox.com/php/webhooks/pandadoc_status.php
$sharedKey = (string)pd_env('PANDADOC_WEBHOOK_SHARED_KEY', '');
$receivedSig = (string)($_GET['signature'] ?? $_SERVER['HTTP_X_PANDADOC_SIGNATURE'] ?? '');
$raw = pd_raw_body();
if ($sharedKey === '' || $receivedSig === '') {
    pd_json(403, ['success' => false, 'error' => 'Missing webhook verification']);
}
$expectedSig = hash_hmac('sha256', $raw, $sharedKey);
if (!hash_equals($expectedSig, $receivedSig)) {
    pd_log('PandaDoc webhook signature mismatch', ['expected' => $expectedSig, 'received' => $receivedSig]);
    pd_json(403, ['success' => false, 'error' => 'Invalid signature']);
}

$payload = json_decode($raw, true);
if (!is_array($payload)) {
    pd_json(200, ['success' => true, 'ignored' => true]);
}

pd_db_ensure_tables();

// Payload can be an array of events. We handle document_state_changed.
$events = isset($payload[0]) && is_array($payload[0]) ? $payload : [$payload];

$handled = [];
foreach ($events as $evt) {
    if (!is_array($evt)) continue;
    $eventName = (string)($evt['event'] ?? '');
    $data = $evt['data'] ?? null;
    if ($eventName === '' || !is_array($data)) continue;

    if ($eventName !== 'document_state_changed') continue;

    $docId = (string)($data['id'] ?? '');
    $status = (string)($data['status'] ?? '');
    if ($docId === '' || $status === '') continue;

    $row = pd_db_find_by_pandadoc_document($docId);
    if (!$row) {
        pd_log('PandaDoc webhook: document not mapped', ['docId' => $docId, 'status' => $status]);
        $handled[] = ['docId' => $docId, 'status' => $status, 'mapped' => false];
        continue;
    }

    $orderId = (int)$row['shopify_order_id'];
    $new = null;
    if ($status === 'document.completed') $new = 'completed';
    elseif ($status === 'document.viewed') $new = 'viewed';
    elseif ($status === 'document.sent') $new = 'sent';
    elseif ($status === 'document.declined' || $status === 'document.cancelled') $new = 'declined';

    if ($new) {
        pd_db_update_order($orderId, ['status' => $new, 'last_error' => null]);
        $metafields = [
            ['namespace' => 'custom', 'key' => 'document_status', 'type' => 'single_line_text_field', 'value' => $new],
        ];
        if ($new === 'completed') {
            $metafields[] = ['namespace' => 'custom', 'key' => 'document_generate', 'type' => 'boolean', 'value' => true];
            $metafields[] = ['namespace' => 'custom', 'key' => 'document_generate_locked', 'type' => 'boolean', 'value' => true];
        }
        shopify_set_order_metafields($orderId, $metafields);
    }

    $handled[] = ['order_id' => $orderId, 'docId' => $docId, 'status' => $status, 'mapped' => true, 'set' => $new];
}

pd_json(200, ['success' => true, 'handled' => $handled]);

