<?php
// 1. Shopify Secrets (.com and .in)
$shopify_secrets = [
    '53cd28d916557246c57cf34db136e06401469273f016096cac7fe67c957df892', // .com secret
    '83e70c1bad76d62e66532c8e1fe9f751734d5b97b4fb577470ec9b61e13c0d1b'  // .in secret
];

// 2. Read the raw data sent by Shopify
$webhook_content = file_get_contents('php://input');

// DEBUG LOGGING — records every incoming webhook hit (topic, order id, tags) so we can
// diagnose exactly what Shopify sent and whether/why a specific order's update did or
// didn't come through. Same pattern as clickpost_debug_log.txt.
$_debug_topic = $_SERVER['HTTP_X_SHOPIFY_TOPIC'] ?? 'unknown';
$_debug_order = json_decode($webhook_content, true);
$_debug_line = date('[Y-m-d H:i:s] ') . 'topic=' . $_debug_topic
    . ' order=' . ($_debug_order['name'] ?? '?')
    . ' tags=[' . ($_debug_order['tags'] ?? '') . ']' . PHP_EOL;
file_put_contents('shopify_debug_log.txt', $_debug_line, FILE_APPEND);

// 3. Verify security signature against BOTH secrets
$shopify_hmac = isset($_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256']) ? $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'] : '';
$is_authorized = false;

foreach ($shopify_secrets as $secret) {
    $calculated_hmac = base64_encode(hash_hmac('sha256', $webhook_content, $secret, true));
    if (hash_equals($calculated_hmac, $shopify_hmac)) {
        $is_authorized = true;
        break; // A match was found, stop checking
    }
}

if (!$is_authorized) {
    http_response_code(401);
    error_log('Unauthorized webhook attempt.');
    exit('Unauthorized');
}

// 4. IMMEDIATELY tell Shopify "We got it!" to prevent 5-second timeouts
http_response_code(200);

// 5. Convert JSON to PHP array
$order = json_decode($webhook_content, true);
if (!$order || !isset($order['id'])) exit;

// --- EXTRACT ORDER DATA ---
$shopify_order_id = $order['id'];
$order_name = $order['name'];
$email = $order['email'];
$phone = $order['phone'] ?? null;
$customer_name = ($order['customer']['first_name'] ?? '') . ' ' . ($order['customer']['last_name'] ?? '');
$financial_status = $order['financial_status'];
$paid_at = $order['processed_at'] ?? null;
$fulfillment_status = $order['fulfillment_status'] ?? 'unfulfilled';
$subtotal = $order['subtotal_price'];
$total = $order['total_price'];
$created_at = $order['created_at'];

$discount_code = $order['discount_codes'][0]['code'] ?? null;
$discount_amount = $order['discount_codes'][0]['amount'] ?? 0.00;
$shipping_method = $order['shipping_lines'][0]['title'] ?? null;

// Billing & Shipping extraction
$b = $order['billing_address'] ?? [];
$billing_name = $b['name'] ?? null; $billing_company = $b['company'] ?? null;
$billing_address1 = $b['address1'] ?? null; $billing_address2 = $b['address2'] ?? null;
$billing_city = $b['city'] ?? null; $billing_zip = $b['zip'] ?? null;
$billing_province = $b['province'] ?? null; $billing_country = $b['country'] ?? null;
$billing_phone = $b['phone'] ?? null;

$s = $order['shipping_address'] ?? [];
$shipping_name = $s['name'] ?? null; $shipping_company = $s['company'] ?? null;
$shipping_address1 = $s['address1'] ?? null; $shipping_address2 = $s['address2'] ?? null;
$shipping_city = $s['city'] ?? null; $shipping_zip = $s['zip'] ?? null;
$shipping_province = $s['province'] ?? null; $shipping_country = $s['country'] ?? null;
$shipping_phone = $s['phone'] ?? null;

$notes = $order['note'] ?? null;
$cancelled_at = $order['cancelled_at'] ?? null;
$payment_method = $order['payment_gateway_names'][0] ?? null;
$tags = $order['tags'] ?? null;

// Smart JSON columns
$line_items_json = json_encode($order['line_items']);
$note_attributes_json = json_encode($order['note_attributes']);

// --- CONNECT TO POSTGRESQL & INSERT/UPDATE ---
// Your exact DV Database Credentials
$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]);

    // CHANGED: was "ON CONFLICT (shopify_order_id) DO NOTHING" — that silently discarded every
    // update (e.g. the "On Hold" tag being added by GoKwik/Shopify Flow AFTER order creation, since
    // that always fires a SECOND webhook call for the same order, not the first one). Now we UPDATE
    // the Shopify-owned fields (tags, financial_status, fulfillment_status, cancelled_at, etc.) on
    // every webhook hit for that order, while explicitly NOT touching agent-owned columns
    // (telecaller_status, agent, internal_remarks, risk_level, payment_terms_name,
    // next_payment_due_at) so nothing an agent has set inside the OMS ever gets overwritten.
    $sql = "INSERT INTO shopify_orders (
        shopify_order_id, order_name, customer_name, email, phone, financial_status, paid_at, 
        fulfillment_status, subtotal, total, discount_code, discount_amount, shipping_method, created_at, 
        line_items, billing_name, billing_company, billing_address1, billing_address2, billing_city, 
        billing_zip, billing_province, billing_country, billing_phone, shipping_name, shipping_company, 
        shipping_address1, shipping_address2, shipping_city, shipping_zip, shipping_province, 
        shipping_country, shipping_phone, notes, note_attributes, cancelled_at, payment_method, tags, telecaller_status
    ) VALUES (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'New Lead'
    )
    ON CONFLICT (shopify_order_id) DO UPDATE SET
        tags                = EXCLUDED.tags,
        financial_status    = EXCLUDED.financial_status,
        fulfillment_status  = EXCLUDED.fulfillment_status,
        paid_at             = EXCLUDED.paid_at,
        cancelled_at        = EXCLUDED.cancelled_at,
        total               = EXCLUDED.total,
        subtotal            = EXCLUDED.subtotal,
        discount_code       = EXCLUDED.discount_code,
        discount_amount     = EXCLUDED.discount_amount,
        line_items          = EXCLUDED.line_items,
        note_attributes     = EXCLUDED.note_attributes,
        notes               = EXCLUDED.notes,
        payment_method      = EXCLUDED.payment_method
        -- telecaller_status, agent, internal_remarks, risk_level, payment_terms_name,
        -- next_payment_due_at are intentionally NOT in this list — those are agent-owned
        -- fields set inside the OMS and must never be reset by a Shopify webhook re-fire.
    ;"; 

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $shopify_order_id, $order_name, $customer_name, $email, $phone, $financial_status, $paid_at, 
        $fulfillment_status, $subtotal, $total, $discount_code, $discount_amount, $shipping_method, $created_at, 
        $line_items_json, $billing_name, $billing_company, $billing_address1, $billing_address2, $billing_city, 
        $billing_zip, $billing_province, $billing_country, $billing_phone, $shipping_name, $shipping_company, 
        $shipping_address1, $shipping_address2, $shipping_city, $shipping_zip, $shipping_province, 
        $shipping_country, $shipping_phone, $notes, $note_attributes_json, $cancelled_at, $payment_method, $tags
    ]);

} catch (PDOException $e) {
    error_log("DB Error: " . $e->getMessage());
}
?>