<?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);

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

$fulfillment_id = $fulfillment['id'];
$order_id = $fulfillment['order_id'];
$status = $fulfillment['status'];
$shipment_status = $fulfillment['shipment_status'] ?? 'pending';
$tracking_company = $fulfillment['tracking_company'] ?? null;
$tracking_number = $fulfillment['tracking_number'] ?? null;
$tracking_url = $fulfillment['tracking_url'] ?? null;
$created_at = $fulfillment['created_at'];

$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_fulfillments (fulfillment_id, order_id, status, shipment_status, tracking_company, tracking_number, tracking_url, created_at, updated_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (fulfillment_id) DO NOTHING;"; 
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$fulfillment_id, $order_id, $status, $shipment_status, $tracking_company, $tracking_number, $tracking_url, $created_at, $created_at]);
} catch (PDOException $e) { error_log("DB Error: " . $e->getMessage()); }
?>