<?php
// Note: This script is intended to be run as a background worker via 'exec()' and should not output to the browser.
// It uses error_log() for logging status and failures.

// Define file paths
const WHATSAPP_SETTINGS_FILE = __DIR__ . '/../../database/whatsapp_settings.json';
const GENERAL_SETTINGS_FILE  = __DIR__ . '/../../admin/database/settings/settings.json';
// Path to read the logged webhook data from
const LOG_FILE_PATH          = __DIR__ . '/../../database/webhook.json'; 

// Function to safely read and decode a JSON file
function getJsonFileContent(string $filePath): ?array
{
    if (!file_exists($filePath)) {
        error_log("Error: Configuration file not found at " . $filePath);
        return null;
    }
    $content = file_get_contents($filePath);
    if ($content === false) {
        error_log("Error: Could not read file at " . $filePath);
        return null;
    }
    $data = json_decode($content, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log("Error: Invalid JSON format in file " . $filePath);
        return null;
    }
    return $data;
}

// Function to clean a phone number
function cleanPhoneNumber(string $phone): string
{
    // Remove all non-digit characters
    return preg_replace('/[^0-9]/', '', $phone);
}

// Function to build a list of line items
function buildLineItemsList(array $line_items): string
{
    $list = '';
    foreach ($line_items as $item) {
        // Format: - Product Name (Qty x Price)
        $list .= "\n- {$item['name']} ({$item['quantity']} x {$item['total']})";
    }
    return trim($list);
}

// Function to safely execute the WhatsApp API call using cURL
function sendWhatsAppMessage(string $sendEndpoint, string $apiKey, string $device, string $recipient, string $message): array
{
    // Ensure the endpoint is correctly structured for sending a message
    $sendEndpoint = str_ireplace('generate-qr', 'send-message', $sendEndpoint);
    if (strpos($sendEndpoint, 'send-message') === false) {
        $sendEndpoint = rtrim($sendEndpoint, '/') . '/send-message';
    }

    $postData = [
        'api_key' => $apiKey,
        'device' => cleanPhoneNumber($device), 
        'number' => cleanPhoneNumber($recipient),
        'message' => $message,
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $sendEndpoint);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error    = curl_error($ch);
    curl_close($ch);

    if ($error) {
        error_log('WhatsApp send cURL error: ' . $error);
        return ['status' => 'error', 'message' => 'cURL error: ' . $error];
    }
    
    $data = json_decode($response, true);
    
    if ($httpCode >= 200 && $httpCode < 300 && $data && (isset($data['status']) && $data['status'] === true)) {
        return ['status' => 'success', 'message' => 'Message sent successfully.'];
    }
    
    error_log("WhatsApp API failure. HTTP Code: {$httpCode}, Response: " . ($response ?: 'No response body'));
    return ['status' => 'failure', 'message' => 'API rejected message or received an error.'];
}

// --- Main Worker Execution Logic ---

// 1. READ DATA FROM LOG FILE (Instead of raw POST body)
$log_data_raw = file_get_contents(LOG_FILE_PATH);
$received_data = json_decode($log_data_raw, true);

if (empty($received_data) || !is_array($received_data)) {
    // Cannot proceed without logged data.
    error_log('Worker Error: Could not read or decode data from log file: ' . LOG_FILE_PATH);
    exit;
}

// Process the latest update (the final entry in the log file array)
$order_data = end($received_data);

// Basic order data validation
if (!isset($order_data['id']) || !isset($order_data['status'])) {
    error_log('Worker Error: Missing essential order data (id or status) in latest log entry.');
    exit;
}

// Standardize status format (e.g., 'completed' -> 'Completed')
$order_status = ucfirst(strtolower($order_data['status'])); 
$recipient    = $order_data['billing']['phone'] ?? null;
$customerName = $order_data['billing']['first_name'] ?? 'Customer';

if (empty($recipient)) {
    error_log('Worker Success: Order processed, but no recipient phone number found. Skipping WhatsApp send.');
    exit;
}

// 2. Load WhatsApp notification settings and check for enabled status
$whatsapp_settings_config = getJsonFileContent(WHATSAPP_SETTINGS_FILE);

if (!$whatsapp_settings_config) {
    error_log('Worker Error: Failed to load WhatsApp message configuration.');
    exit;
}

if (!isset($whatsapp_settings_config[$order_status]) || ($whatsapp_settings_config[$order_status]['enabled'] ?? false) !== true) {
    error_log("Worker Success: No action: WhatsApp message disabled for status '{$order_status}'.");
    exit;
}

$template_message = $whatsapp_settings_config[$order_status]['message'];

// 3. Load WhatsApp API credentials
$general_settings = getJsonFileContent(GENERAL_SETTINGS_FILE);

if (!$general_settings || !isset($general_settings['whatsapp_settings'])) {
    error_log('Worker Error: Failed to load general WhatsApp API configuration.');
    exit;
}

$config = $general_settings['whatsapp_settings'];

$apiKey = $config['api_key'] ?? '';
$sender = $config['sender'] ?? ''; 
$apiEndpoint = $config['api_endpoint'] ?? '';
$footerText = $config['default_footer_text'] ?? '';
$enabled = ($config['enable_autoreply'] ?? 'no') === 'yes';

if (!$enabled) {
    error_log('Worker Success: WhatsApp autoreply is globally disabled in settings.');
    exit;
}

if (empty($apiKey) || empty($sender) || empty($apiEndpoint)) {
    error_log('Worker Error: WhatsApp API configuration is incomplete (Key, Sender, or Endpoint missing).');
    exit;
}

// 4. Build the final message (Dynamic Variable Replacement)
$final_message = $template_message;

// --- Expanded Dynamic Variable Replacements ---
$replacements = [
    // Core Order Details
    '{{order.id}}'                  => $order_data['id'] ?? '',
    '{{order.status}}'              => $order_data['status'] ?? '',
    '{{order.total}}'               => $order_data['total'] ?? '0.00',
    '{{order.currency}}'            => $order_data['currency'] ?? '',
    '{{order.currency_symbol}}'     => $order_data['currency_symbol'] ?? '',
    '{{order.order_key}}'           => $order_data['order_key'] ?? '',
    '{{order.date_created}}'        => $order_data['date_created'] ?? '',
    
    // Billing Details
    '{{order.billing.first_name}}'  => $order_data['billing']['first_name'] ?? $customerName,
    '{{order.billing.last_name}}'   => $order_data['billing']['last_name'] ?? '',
    '{{order.billing.company}}'     => $order_data['billing']['company'] ?? '',
    '{{order.billing.address_1}}'   => $order_data['billing']['address_1'] ?? '',
    '{{order.billing.city}}'        => $order_data['billing']['city'] ?? '',
    '{{order.billing.state}}'       => $order_data['billing']['state'] ?? '',
    '{{order.billing.postcode}}'    => $order_data['billing']['postcode'] ?? '',
    '{{order.billing.country}}'     => $order_data['billing']['country'] ?? '',
    '{{order.billing.email}}'       => $order_data['billing']['email'] ?? '',
    '{{order.billing.phone}}'       => $order_data['billing']['phone'] ?? '',
    
    // Shipping Details
    '{{order.shipping.first_name}}' => $order_data['shipping']['first_name'] ?? '',
    '{{order.shipping.last_name}}'  => $order_data['shipping']['last_name'] ?? '',
    '{{order.shipping.address_1}}'  => $order_data['shipping']['address_1'] ?? '',
    '{{order.shipping.city}}'       => $order_data['shipping']['city'] ?? '',
    '{{order.shipping.state}}'      => $order_data['shipping']['state'] ?? '',
    '{{order.shipping.postcode}}'   => $order_data['shipping']['postcode'] ?? '',
    '{{order.shipping.country}}'    => $order_data['shipping']['country'] ?? '',

    // Financial/Payment Details
    '{{order.payment_method_title}}'=> $order_data['payment_method_title'] ?? '',
    '{{order.discount_total}}'      => $order_data['discount_total'] ?? '0.00',
    '{{order.shipping_total}}'      => $order_data['shipping_total'] ?? '0.00',
    '{{order.total_tax}}'           => $order_data['total_tax'] ?? '0.00',
    '{{order.payment_url}}'         => $order_data['payment_url'] ?? '', 
    
    // Custom/Processed Variables
    '{{order.line_items_list}}'     => buildLineItemsList($order_data['line_items'] ?? []),
];

$final_message = str_replace(array_keys($replacements), array_values($replacements), $final_message);
// --- End of Expanded Dynamic Variable Replacements ---

// Append configured footer text
if (!empty($footerText)) {
    $final_message .= "\n\n---\n" . $footerText;
}


// 5. Send the message
$send_result = sendWhatsAppMessage($apiEndpoint, $apiKey, $sender, $recipient, $final_message);

// 6. Log final result (Must use error_log for background workers)
if ($send_result['status'] === 'success') {
    error_log('Worker Success: Order status notification sent for order #' . $order_data['id'] . ' to ' . $recipient . '.');
} else {
    error_log('Worker Failed to send WhatsApp message for order #' . $order_data['id'] . ': ' . $send_result['message']);
}

// Exit silently
exit;

?>
