<?php

/**
 * Created by Satyam for interakt WhatsApp Chatbot on 01-03-2025
 * Last updated by Satyam for add UTM Link needed in Interakt for centralized work report on 03-10-2025
 * Last updated by Satyam for log request data on 05-03-2026
 **/

// Function to handle logging (replacement for Mage::log)
function customLog($message, $level = null, $file = 'contacts-webhook.log', $forceLog = false)
{
    $logDir = __DIR__ . '/logs';

    // Create logs directory if it doesn't exist
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }

    $logPath = $logDir . '/' . $file;
    $timestamp = date('Y-m-d H:i:s');
    $formattedMessage = "[$timestamp] $message" . PHP_EOL;

    file_put_contents($logPath, $formattedMessage, FILE_APPEND);
}

function getBaseDir()
{
    return __DIR__;
}

// Process webhook request
function processAvailabilityWebhook()
{
    // Define a secret key for security
    $secretKey = '23f5a3b5c55407475c2193e47674d617';

    customLog("Webhook Request Data: Start ", null, 'contacts_webhook.log');

    // Get request headers
    $headers = getallheaders();
    // Updated by Satyam on 18-11-2025 ude to header paramter changed by interakt
    $receivedSecret = isset($headers['X-Webhook-Secret']) ? $headers['X-Webhook-Secret'] : '';
    // $receivedSecret = isset($headers['x-webhook-secret']) ? $headers['x-webhook-secret'] : '';

    customLog("Webhook Request Data: receivedSecret: $headers", null, 'contacts_webhook.log');
    customLog(json_encode($headers), null, 'contacts_webhook.log');

    // Verify the secret key
    if ($receivedSecret !== $secretKey) {
        http_response_code(403);
        echo json_encode(["status" => "error", "message" => "Unauthorized"]);
        customLog("Webhook Request Data: Not Verified Header", null, 'contacts_webhook.log');
        exit;
    }

    customLog("Webhook Request Data: Verified Header", null, 'contacts_webhook.log');

    // Read JSON input
    $requestData = file_get_contents('php://input');
    $data = json_decode($requestData, true);
    // sanitizeArray($data); // Remove formatting from all values

    // Log the webhook data
    customLog("Webhook Request Data: " . $requestData, null, 'contacts_webhook.log');

    // Validate incoming data
    if (!isset($data['trigger_hash'])) {
        http_response_code(400);
        echo json_encode(["status" => "error", "message" => "Invalid payload for Trigger"]);
        exit;
    }
    $triggerHash = $data['trigger_hash'];
    $triggerHash = preg_replace('/^ydwf_ikt /', '', $triggerHash);
    $magentoResult = callMagentoInquiryApi($triggerHash);

    if ($magentoResult['success'] != 'success') {
        echo json_encode(array(
            'status' => 'fail',
            'message' => 'Failed to fetch inquiry from Magento'
        ));
        exit;
    }

    $baseUrl = 'https://yatradham.org';
    $reply   = buildCustomerReply($magentoResult, $baseUrl);

    customLog("Webhook Response Data: " . print_r($reply, true), null, 'contacts_webhook.log');
    header('Content-Type: application/json');
    echo json_encode($reply, JSON_UNESCAPED_SLASHES);
    exit;
}

function callMagentoInquiryApi($triggerHash)
{
    $url = 'https://yatradham.org/restapiv2.php?apiname=contactus';

    // Prepare the payload data for the POST body
    $payload = http_build_query(array(
        // 'apiname' => 'contactus',
        'inquiry' => 'hash_workflow',
        'select_query' => $triggerHash
    ));

    $ch = curl_init();

    curl_setopt_array($ch, array(
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $payload,         // Attaches the JSON body
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_TIMEOUT        => 8,
        CURLOPT_HTTPHEADER     => array(
            'Accept: application/json',
            'token: p1OfsrCuc3ma0GdZAqoubsW3LbLgmcWUMwrVyzN+2T2ZQk0AOutjwqRHqyXGZlPLcBa1C48Nr8ORJRsXufw2qR+DH2m8QUsU6qctBPS8CSClihoANJERuQ=='
        ),
    ));

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error    = curl_error($ch);

    curl_close($ch);

    if ($response === false) {
        return array(
            'status' => 'fail',
            'message' => 'cURL error: ' . $error
        );
    }

    $data = json_decode($response, true);

    if (!is_array($data)) {
        return array(
            'status' => 'fail',
            'message' => 'Invalid JSON response from Magento.'
        );
    }

    return array(
        'success'   => ($httpCode >= 200 && $httpCode < 300 && !empty($data['status'])),
        'http_code' => $httpCode,
        'data'      => $data
    );
}

function buildCustomerReply(array $magentoResponse, $baseUrl)
{
    if (
        empty($magentoResponse['success']) ||
        empty($magentoResponse['data']['data'])
    ) {
        return array(
            'status' => 'fail',
            'message' => 'No inquiry data found.'
        );
    }

    $payload = $magentoResponse['data']['data'];

    $name        = isset($payload['name']) ? $payload['name'] : 'Customer';
    $destination  = isset($payload['destination']) ? $payload['destination'] : '';
    $checkInDate  = isset($payload['check_in_date']) ? $payload['check_in_date'] : '';
    $guests      = isset($payload['guests']) ? (int)$payload['guests'] : 0;
    $properties   = array();

    if (!empty($payload['suggested_properties']) && is_array($payload['suggested_properties'])) {
        foreach ($payload['suggested_properties'] as $item) {
            $propertyName = isset($item['property_name']) ? trim($item['property_name']) : '';
            $propertyUrl  = isset($item['property_url']) ? trim($item['property_url']) : '';

            if ($propertyUrl !== '') {
                $fullUrl = rtrim($baseUrl, '/') . '/' . ltrim($propertyUrl, '/');

                $properties[] = array(
                    'name' => $propertyName !== '' ? $propertyName : $fullUrl,
                    'url'  => $fullUrl
                );
            }
        }
    }

    if (empty($properties)) {
        return array(
            'status' => 'success',
            'message' => "Hi {$name}, we received your inquiry for {$destination}, but no available properties were found right now."
        );
    }

    // Sanitize inputs for premium presentation
    // $cleanName = ucfirst(trim($name));
    // $cleanDestination = ucfirst(trim($destination));

    // Main Greeting & Stay Summary
    // $text = "Hello *{$cleanName}*! 👋\n\n";
    // $text .= "We have found some great stay options for your upcoming trip to *{$cleanDestination}*! 📍\n\n";
    // $text .= "📅 *Check-in Date:* {$checkInDate}\n";
    // $text .= "👥 *Total Guests:* {$guests}\n\n";
    // $text .= "Here are our top-rated recommendations for you:\n";
    // $text .= "────────────────────\n\n";

    // // Loop through available properties
    // $i = 1;
    // foreach ($properties as $property) {
    //     // Extract property name cleanly
    //     $propertyName = trim(str_replace(['*', '_', '~'], '', $property['name']));

    //     $text .= "*Option {$i}: {$propertyName}*\n";
    //     $text .= "🔗 Click to View & Book: {$property['url']}\n\n";
    //     $i++;
    // }

    // // Clear Call to Action (CTA) & Closing
    // $text .= "────────────────────\n";
    // $text .= "💡 *Pro-Tip:* These properties are filling up fast for your dates. Tap the links above to check real-time availability and secure your room!\n\n";
    // $text .= "If you need any modifications or immediate assistance, simply reply directly to this chat. Enjoy your stay! 😊";

    $text = "Hello {$name}, thank you for sharing your stay requirement.\n\n";
    $text .= "Based on your request, here are some suitable stay options for *{$destination}* on *{$checkInDate}* for *{$guests} guest(s)*:\n\n";

    $i = 1;
    foreach ($properties as $property) {
        $text .= $i . '. ' . $property['name'] . "\n";
        $text .= $property['url'] . "\n\n";
        $i++;
    }

    $text .= "Please review the options and reply with the property number you prefer. If you have received these suggestions, tap *Got It*.";

    return array(
        'status'   => 'success',
        'message'   => trim($text),
        'properties' => $properties
    );
}

// Process the webhook
processAvailabilityWebhook();
