<?php
$shopify_secrets = ['53cd28d916557246c57cf34db136e06401469273f016096cac7fe67c957df892', '83e70c1bad76d62e66532c8e1fe9f751734d5b97b4fb577470ec9b61e13c0d1b'];
$webhook_content = file_get_contents('php://input');
$shopify_hmac = isset($_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256']) ? $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'] : '';
$is_authorized = false;

foreach ($shopify_secrets as $secret) {
    if (hash_equals(base64_encode(hash_hmac('sha256', $webhook_content, $secret, true)), $shopify_hmac)) {
        $is_authorized = true; break;
    }
}
if (!$is_authorized) { http_response_code(401); exit; }
http_response_code(200);

$order = json_decode($webhook_content, true);
if (!$order || !isset($order['id'])) exit;

$shopify_order_id = $order['id'];
$cancelled_at = $order['cancelled_at'] ?? date('c');
$cancel_reason = $order['cancel_reason'] ?? 'unknown';
$financial_status = $order['financial_status'] ?? 'unknown';

$host = 'database.xhost.co.in'; $db = 'db_iqpj6ze2cf'; $user = 'db_iqpj6ze2cf'; $pass = 'O*9Mp;%5PPDyv8oD';
$dsn = "pgsql:host=$host;port=5432;dbname=$db";

try {
    $pdo = new PDO($dsn, $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    $sql = "INSERT INTO shopify_cancellations (shopify_order_id, cancelled_at, cancel_reason, financial_status) 
            VALUES (?, ?, ?, ?) ON CONFLICT (shopify_order_id) 
            DO UPDATE SET cancelled_at = EXCLUDED.cancelled_at, cancel_reason = EXCLUDED.cancel_reason, financial_status = EXCLUDED.financial_status;"; 
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$shopify_order_id, $cancelled_at, $cancel_reason, $financial_status]);
} catch (PDOException $e) { error_log("DB Error: " . $e->getMessage()); }
?>