<?php
// config.php
// Update these values for your environment.

date_default_timezone_set('Asia/Kuala_Lumpur');

// -------------------------
// Database
// -------------------------
define('DB_HOST', 'localhost');
define('DB_NAME', 'lalamove_shopify');
define('DB_USER', 'lalamove_shopify_user');
define('DB_PASS', 'rocuNSuk5TqJnocv');

// -------------------------
// Shopify
// -------------------------


define('SHOPIFY_WEBHOOK_SECRET', 'ac8a3a5e6d2bc65b160d64f66aeb01d9a8fe8fec69e34f19426109fdeea5e318');


define('SHOPIFY_CLIENT_ID', '72efb5792cae39246864763fe466e8a0');
define('SHOPIFY_CLIENT_SECRET', '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');
define('SHOPIFY_STORE_DOMAIN', 'farmers-bar.myshopify.com');
define('SHOPIFY_API_VERSION', '2026-01');

define('LALAMOVE_PUSH_TOKEN', '8f9b4c31c8d84b0f95d4d41f74e2d9c1_lalamove_push_secret');
// -------------------------
// Matching rules
// -------------------------
define('ADDRESS_MATCH_THRESHOLD', 70.00);
define('PHONE_MATCH_REQUIRED', true);
define('AUTO_SEND_TRACKING_WHEN_SHARE_LINK_EXISTS', true);

// -------------------------
// Playwright JSON import
// -------------------------
define('LALAMOVE_JSON_PATH', __DIR__ . '/latest-order.json');

// -------------------------
// Helpers
// -------------------------
function db(): mysqli
{
    static $mysqli = null;
    if ($mysqli instanceof mysqli) {
        return $mysqli;
    }

    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($mysqli->connect_error) {
        http_response_code(500);
        die('Database connection failed: ' . $mysqli->connect_error);
    }
    $mysqli->set_charset('utf8mb4');
    return $mysqli;
}

function json_response(array $data, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    exit;
}

function get_raw_body(): string
{
    $body = file_get_contents('php://input');
    return is_string($body) ? $body : '';
}

function get_header_value(string $name): string
{
    $key = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
    return isset($_SERVER[$key]) ? (string)$_SERVER[$key] : '';
}

function verify_shopify_webhook(string $rawBody, string $receivedHmac): bool
{
    if ($receivedHmac === '') {
        return false;
    }
    $calculated = base64_encode(hash_hmac('sha256', $rawBody, SHOPIFY_WEBHOOK_SECRET, true));
    return hash_equals($calculated, $receivedHmac);
}

function normalize_phone(?string $phone): string
{
    $phone = trim((string)$phone);
    if ($phone === '') {
        return '';
    }

    // Keep leading + only temporarily.
    $phone = preg_replace('/[^\d+]/', '', $phone);
    if ($phone === null) {
        return '';
    }

    // Malaysia-focused normalization -> digits only, usually starting with 60.
    if (strpos($phone, '+') === 0) {
        $phone = substr($phone, 1);
    }

    if (strpos($phone, '00') === 0) {
        $phone = substr($phone, 2);
    }

    if (strpos($phone, '60') === 0) {
        return $phone;
    }

    if (strpos($phone, '0') === 0) {
        return '60' . substr($phone, 1);
    }

    return $phone;
}

function normalize_address(?string $text): string
{
    $text = mb_strtolower(trim((string)$text), 'UTF-8');
    $text = preg_replace('/[^\p{L}\p{N}\s]/u', ' ', $text);
    $text = preg_replace('/\s+/u', ' ', (string)$text);
    return trim((string)$text);
}

function address_similarity_score(string $a, string $b): float
{
    $a = normalize_address($a);
    $b = normalize_address($b);

    if ($a === '' || $b === '') {
        return 0.0;
    }

    similar_text($a, $b, $percent);
    return round((float)$percent, 2);
}

function log_webhook(string $source, ?string $eventType, ?string $externalId, array $headers, string $payload, string $status = 'pending', ?string $error = null): int
{
    $mysqli = db();
    $stmt = $mysqli->prepare("
        INSERT INTO webhook_logs
        (source, event_type, external_id, headers, payload, process_status, error_message, received_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    if (!$stmt) {
        return 0;
    }

    $headersJson = json_encode($headers, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $stmt->bind_param('sssssss', $source, $eventType, $externalId, $headersJson, $payload, $status, $error);
    $stmt->execute();
    $id = (int)$stmt->insert_id;
    $stmt->close();
    return $id;
}

function update_webhook_log(int $id, string $status, ?string $error = null): void
{
    if ($id <= 0) {
        return;
    }
    $mysqli = db();
    $stmt = $mysqli->prepare("
        UPDATE webhook_logs
        SET process_status = ?, error_message = ?, processed_at = NOW()
        WHERE id = ?
    ");
    if (!$stmt) {
        return;
    }
    $stmt->bind_param('ssi', $status, $error, $id);
    $stmt->execute();
    $stmt->close();
}

function shopify_graphql(string $query, array $variables = []): array
{
    $url = 'https://' . SHOPIFY_STORE_DOMAIN . '/admin/api/' . SHOPIFY_API_VERSION . '/graphql.json';

    $payload = json_encode([
        'query' => $query,
        'variables' => $variables
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'X-Shopify-Access-Token: ' . SHOPIFY_ADMIN_API_TOKEN
        ],
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_TIMEOUT => 30,
    ]);

    $response = curl_exec($ch);
    $curlError = curl_error($ch);
    $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($response === false) {
        return [
            'ok' => false,
            'http_status' => $httpCode,
            'error' => 'cURL error: ' . $curlError,
            'raw' => null,
        ];
    }

    $decoded = json_decode($response, true);
    return [
        'ok' => ($httpCode >= 200 && $httpCode < 300),
        'http_status' => $httpCode,
        'error' => null,
        'raw' => $decoded,
    ];
}

function shopify_gid(string $type, $id): string
{
    return 'gid://shopify/' . $type . '/' . $id;
}
