<?php
/**
 * Zalo Bot API Proxy
 * Proxy to bypass CORS when calling Zalo Bot API from browser
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Set response headers
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Only allow GET requests
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode([
        'ok' => false,
        'error' => 'Method not allowed. Only GET is supported.'
    ]);
    exit;
}

// Get bot token from query parameter
$botToken = isset($_GET['token']) ? trim($_GET['token']) : '';

if (empty($botToken)) {
    http_response_code(400);
    echo json_encode([
        'ok' => false,
        'error' => 'Missing bot token parameter'
    ]);
    exit;
}

// Build Zalo API URL
$zaloApiUrl = "https://bot-api.zapps.me/bot{$botToken}/getUpdates";

try {
    // Initialize cURL
    $ch = curl_init();
    
    // Set cURL options
    curl_setopt_array($ch, [
        CURLOPT_URL => $zaloApiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 60, // 60 seconds timeout for long polling
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Accept: application/json'
        ]
    ]);
    
    // Execute request
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    $curlErrno = curl_errno($ch);
    
    curl_close($ch);
    
    // Check for cURL errors
    if ($curlErrno !== 0) {
        http_response_code(502);
        echo json_encode([
            'ok' => false,
            'error' => 'cURL Error: ' . $curlError,
            'error_code' => $curlErrno
        ]);
        exit;
    }
    
    // Check HTTP status code
    if ($httpCode !== 200) {
        http_response_code($httpCode);
        echo json_encode([
            'ok' => false,
            'error' => 'Zalo API returned HTTP ' . $httpCode,
            'response' => $response
        ]);
        exit;
    }
    
    // Validate JSON response
    $jsonData = json_decode($response, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(502);
        echo json_encode([
            'ok' => false,
            'error' => 'Invalid JSON response from Zalo API',
            'json_error' => json_last_error_msg(),
            'raw_response' => substr($response, 0, 500) // First 500 chars for debugging
        ]);
        exit;
    }
    
    // Return the response from Zalo API
    http_response_code(200);
    echo json_encode($jsonData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'ok' => false,
        'error' => 'Server error: ' . $e->getMessage()
    ]);
}

