<?php
// Set the content type to application/json for the response
header('Content-Type: application/json');

// --- FILE PATHS ---
$logFilePath = 'database/webhook.json';
$templateFilePath = 'database/whatsapp_settings.json';
$settingsFilePath = 'admin/database/settings/settings.json';
$sentLogPath = 'database/sent_notifications.json';
$messageLogPath = 'database/message_log.json'; // NEW LOG FILE PATH

// --- HELPER FUNCTIONS ---

/**
 * Safely loads and decodes a JSON file.
 * @param string $path The path to the JSON file.
 * @return array|null Decoded JSON array or null on failure.
 */
function loadJsonFile(string $path): ?array {
    if (!file_exists($path) || !is_readable($path)) {
        return null;
    }
    
    $content = file_get_contents($path);
    if ($content === false) {
        return null;
    }
    
    $data = json_decode($content, true);
    
    // Return array, or empty array if file was empty/null
    return is_array($data) ? $data : [];
}

/**
 * Safely appends a new entry to a JSON log file.
 * @param string $path The path to the JSON log file.
 * @param array $newEntry The entry data to log.
 * @return bool True on success, false on failure.
 */
function appendToJsonLog(string $path, array $newEntry): bool {
    // 1. Load existing data
    $logData = loadJsonFile($path) ?? [];
    
    // 2. Append the new entry
    $logData[] = $newEntry;
    
    // 3. Save the updated data
    return file_put_contents($path, json_encode($logData, JSON_PRETTY_PRINT)) !== false;
}

/**
 * Creates a formatted list of line items.
 * @param array $lineItems The array of line items from the order data.
 * @return string The newline-separated list.
 */
function get_line_items_list(array $lineItems): string {
    $list = [];
    foreach ($lineItems as $item) {
        $list[] = "- " . ($item['quantity'] ?? 1) . "x " . ($item['name'] ?? 'Item');
    }
    return implode("\n", $list);
}

/**
 * Replaces placeholders in the message template using order data.
 * @param string $message The message template with placeholders.
 * @param array $data The complete order data.
 * @return string The message with placeholders replaced.
 */
function replace_placeholders(string $message, array $data): string {
    // 1. Special handling for line items list
    if (strpos($message, '{{order.line_items_list}}') !== false && isset($data['line_items'])) {
        $list_items = get_line_items_list($data['line_items']);
        $message = str_replace('{{order.line_items_list}}', $list_items, $message);
    }

    // 2. Dynamic replacement for all {{order.path.to.field}} patterns
    $message = preg_replace_callback('/\{\{order\.([a-zA-Z0-9\._]+)\}\}/', function ($matches) use ($data) {
        $path = explode('.', $matches[1]);
        $value = $data;
        $found = true;

        foreach ($path as $key) {
            if (isset($value[$key])) {
                $value = $value[$key];
            } else {
                $found = false;
                break;
            }
        }

        if ($found && is_scalar($value)) {
            return $value;
        }
        return $matches[0];
    }, $message);

    // 3. Simple replacement for currency_symbol and payment_url (for safety)
    if (isset($data['currency_symbol'])) {
        $message = str_replace('{{order.currency_symbol}}', $data['currency_symbol'], $message);
    }
    if (isset($data['payment_url'])) {
        $message = str_replace('{{order.payment_url}}', $data['payment_url'], $message);
    }

    return $message;
}


// --- WEBHOOK DATA COLLECTION & INITIAL LOGGING ---

$requestData = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $jsonBody = file_get_contents('php://input');
    $requestData = !empty($jsonBody) ? json_decode($jsonBody, true) : $_POST;
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $requestData = $_GET;
}

if (empty($requestData)) {
    echo json_encode(['status' => 'error', 'message' => 'No data received.']);
    exit;
}

// Log the incoming request immediately
$webhookLogEntry = $requestData;
$webhookLogEntry['timestamp'] = date('Y-m-d H:i:s');
$webhookLogEntry['method'] = $_SERVER['REQUEST_METHOD'];

if (!appendToJsonLog($logFilePath, $webhookLogEntry)) {
    echo json_encode(['status' => 'error', 'message' => 'Failed to write webhook data to log file. Check file permissions.']);
    exit;
}

// --- WHATSAPP NOTIFICATION LOGIC ---

$notificationStatus = ['status' => 'success', 'message' => 'Webhook data successfully stored.'];
$messageLogEntry = [
    'timestamp' => date('Y-m-d H:i:s'),
    'order_id' => $requestData['id'] ?? null,
    'status' => 'Processing',
    'attempt_status' => 'Skipped: Not an order update.'
];

$orderStatus = $requestData['status'] ?? null;
$customerPhone = $requestData['billing']['phone'] ?? null;
$orderId = $requestData['id'] ?? null;

if ($orderStatus && $customerPhone && $orderId) {
    $templateKey = ucfirst($orderStatus);
    $uniqueNotificationKey = $orderId . '-' . $templateKey;
    $messageLogEntry['order_id'] = $orderId;
    $messageLogEntry['status'] = $templateKey;

    // 2. Idempotency Check
    $sentLog = loadJsonFile($sentLogPath) ?? [];

    if (isset($sentLog[$uniqueNotificationKey])) {
        $statusMsg = 'Skipped: Idempotency check passed. Notification already sent for ' . $uniqueNotificationKey;
        $notificationStatus['whatsapp_status'] = $statusMsg;
        $messageLogEntry['attempt_status'] = $statusMsg;
    } else {
        // 3. Load configurations
        $templates = loadJsonFile($templateFilePath);
        $settingsContainer = loadJsonFile($settingsFilePath);

        $whatsappSettings = $settingsContainer['whatsapp_settings'] ?? null;
        $enableAutoreply = $whatsappSettings['enable_autoreply'] ?? 'no';
        $enableDefaultFooter = $whatsappSettings['enable_default_footer'] ?? 'no'; 

        // Check conditions before proceeding
        if ($enableAutoreply !== 'yes') {
            $statusMsg = 'Skipped: Auto-reply disabled in settings.';
            $notificationStatus['whatsapp_status'] = $statusMsg;
            $messageLogEntry['attempt_status'] = $statusMsg;
        } elseif (!$templates || !$whatsappSettings) {
            $statusMsg = 'Error: Missing WhatsApp templates or API settings.';
            $notificationStatus['whatsapp_status'] = $statusMsg;
            $messageLogEntry['attempt_status'] = $statusMsg;
        } else {
            // 4. Check if a template exists and is enabled for the current status
            $template = $templates[$templateKey] ?? null;

            if ($template && ($template['enabled'] ?? false)) {
                
                $rawMessage = $template['message'] ?? '';
                $mainMessage = replace_placeholders($rawMessage, $requestData);
                
                $footerText = $whatsappSettings['default_footer_text'] ?? 'This is an automated message. Please do not reply.';
                
                // Conditional Footer Logic
                $footerForApi = ($enableDefaultFooter === 'yes' && !empty($footerText)) ? $footerText : '';

                $recipientNumber = preg_replace('/[^0-9]/', '', $customerPhone);

                if (empty($recipientNumber) || strlen($recipientNumber) < 10) {
                     $statusMsg = 'Error: Invalid recipient phone number.';
                     $notificationStatus['whatsapp_status'] = $statusMsg;
                     $messageLogEntry['attempt_status'] = $statusMsg;
                } else {
                    // 6. Prepare and send API request
                    $apiEndpoint = $whatsappSettings['api_endpoint'] ?? '';
                    $apiKey = $whatsappSettings['api_key'] ?? '';
                    $sender = $whatsappSettings['sender'] ?? ''; 

                    if (empty($apiEndpoint) || empty($apiKey) || empty($sender)) {
                        $statusMsg = 'Error: Incomplete WhatsApp API credentials (endpoint, key, or sender).';
                        $notificationStatus['whatsapp_status'] = $statusMsg;
                        $messageLogEntry['attempt_status'] = $statusMsg;
                    } else {
                        $apiUrl = rtrim($apiEndpoint, '/') . '/send-message';
                        
                        $apiPayload = json_encode([
                            'api_key' => $apiKey,
                            'sender' => $sender,
                            'number' => $recipientNumber,
                            'message' => $mainMessage,
                            'footer' => $footerForApi
                        ]);
                        
                        // Populate log entry before the cURL request
                        $messageLogEntry['recipient'] = $recipientNumber;
                        $messageLogEntry['sent_message'] = $mainMessage . (!empty($footerForApi) ? "\n\n---\n" . $footerForApi : '');
                        
                        $ch = curl_init($apiUrl);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_POST, true);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $apiPayload);
                        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Content-Length: ' . strlen($apiPayload)]);

                        $apiResponse = curl_exec($ch);
                        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                        $curlError = curl_error($ch);
                        curl_close($ch);
                        
                        $messageLogEntry['api_response'] = $apiResponse;
                        $messageLogEntry['http_code'] = $httpCode;

                        if ($curlError || $httpCode !== 200) {
                            $statusMsg = 'Error: API request failed. HTTP ' . $httpCode . ' / Curl Error: ' . $curlError . ' / Response: ' . $apiResponse;
                            $notificationStatus['whatsapp_status'] = $statusMsg;
                            $messageLogEntry['attempt_status'] = $statusMsg;
                        } else {
                            $decodedResponse = json_decode($apiResponse, true);
                            if (isset($decodedResponse['status']) && $decodedResponse['status'] === true) {
                                
                                // --- IDEMPOTENCY RECORDING ---
                                $sentLog[$uniqueNotificationKey] = date('Y-m-d H:i:s');
                                file_put_contents($sentLogPath, json_encode($sentLog, JSON_PRETTY_PRINT));
                                // --- END IDEMPOTENCY RECORDING ---

                                $statusMsg = 'Success: Message sent for Order #' . $orderId . ' (Status: ' . $orderStatus . ')';
                                $notificationStatus['whatsapp_status'] = $statusMsg;
                                $messageLogEntry['attempt_status'] = $statusMsg;
                            } else {
                                $statusMsg = 'Warning: API indicated failure. Response: ' . $apiResponse;
                                $notificationStatus['whatsapp_status'] = $statusMsg;
                                $messageLogEntry['attempt_status'] = $statusMsg;
                            }
                        }
                    }
                }
            } else {
                $statusMsg = 'Skipped: Template not found or disabled for status: ' . $templateKey;
                $notificationStatus['whatsapp_status'] = $statusMsg;
                $messageLogEntry['attempt_status'] = $statusMsg;
            }
        }
    }
    
    // --- FINAL MESSAGE LOGGING (After determining the outcome) ---
    appendToJsonLog($messageLogPath, $messageLogEntry);
    
} else {
    $notificationStatus['whatsapp_status'] = 'Skipped: Incoming data is not a recognized order update (missing status, phone, or ID).';
    // The initial $messageLogEntry will already contain this skip status for non-orders.
    if(isset($messageLogEntry)) {
        appendToJsonLog($messageLogPath, $messageLogEntry);
    }
}


// --- FINAL RESPONSE ---
// This ensures the webhook sender receives a prompt 200 OK
echo json_encode($notificationStatus);

?>