<?php
// webhook.php
$config = require __DIR__ . '/config.php';
require __DIR__ . '/db.php';

// Function to verify Shopify webhook
function verify_webhook($data, $hmac_header, $secret) {
    $calculated_hmac = base64_encode(hash_hmac('sha256', $data, $secret, true));
    return hash_equals($calculated_hmac, $hmac_header);
}

$hmac_header = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'] ?? '';
$topic = $_SERVER['HTTP_X_SHOPIFY_TOPIC'] ?? '';
$shop = $_SERVER['HTTP_X_SHOPIFY_SHOP_DOMAIN'] ?? '';

$raw_data = file_get_contents('php://input');

// Verify authenticity
if (!verify_webhook($raw_data, $hmac_header, $config['shopify_webhook_secret'])) {
    http_response_code(401);
    die('Unauthorized');
}

// Return 200 immediately to Shopify
http_response_code(200);

// We should ideally process in background, but for simplicity here we do it inline.
// Ignore fastcgi_finish_request() if not available, but try to use it to close connection
if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
}

$data = json_decode($raw_data, true);

if (!$data) exit;

try {
    switch ($topic) {
        case 'products/create':
        case 'products/update':
            $pid = $data['id'];
            $handle = $data['handle'];
            $title = $data['title'];
            $vendor = $data['vendor'];
            $status = $data['status'];
            
            // Calculate min/max price from variants
            $min_price = PHP_INT_MAX;
            $max_price = 0;
            
            if (isset($data['variants']) && is_array($data['variants'])) {
                foreach ($data['variants'] as $variant) {
                    $price = (float)$variant['price'];
                    if ($price < $min_price) $min_price = $price;
                    if ($price > $max_price) $max_price = $price;
                }
            }
            if ($min_price === PHP_INT_MAX) $min_price = 0;
            
            db_execute($pdo, "INSERT INTO products (id, handle, title, vendor, min_price, max_price, status) VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE handle=VALUES(handle), title=VALUES(title), vendor=VALUES(vendor), min_price=VALUES(min_price), max_price=VALUES(max_price), status=VALUES(status)", [
                $pid, $handle, $title, $vendor, $min_price, $max_price, $status
            ]);
            
            // To update product collections, it's better to fetch from GraphQL since REST payload might not have all custom collections.
            // But this requires a background job to not block webhook. 
            // For now, if we get custom collections info, we update it. If not, a periodic full sync might be better.
            break;
            
        case 'products/delete':
            $pid = $data['id'];
            db_execute($pdo, "DELETE FROM products WHERE id = ?", [$pid]);
            break;
            
        case 'collections/create':
        case 'collections/update':
            $cid = $data['id'];
            $handle = $data['handle'];
            $title = $data['title'];
            db_execute($pdo, "INSERT INTO collections (id, handle, title) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE handle=VALUES(handle), title=VALUES(title)", [
                $cid, $handle, $title
            ]);
            break;
            
        case 'collections/delete':
            $cid = $data['id'];
            db_execute($pdo, "DELETE FROM collections WHERE id = ?", [$cid]);
            break;
    }
} catch (Exception $e) {
    // Log error
    error_log("Webhook Error: " . $e->getMessage());
}
