<?php
// Add CORS headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Credentials: true");
header('Content-Type: application/json');

// ADD THIS - Your admin secret (must match main.js)
define('ADMIN_SECRET', 'mana-location-whatsapp-bot');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Get POST data
        $receiver = $_POST['receiver'] ?? '';
        $filename = $_POST['filename'] ?? '';
        $caption = $_POST['caption'] ?? ''; 
        $type = $_POST['type'] ?? ''; 

        // Validate required fields
        if (empty($receiver) || empty($filename) || empty($caption) || empty($type)) {
            throw new Exception('Missing required fields');
        }

        // Get the uploaded file
        if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('File upload failed');
        }

        $file = $_FILES['image'];
        $cfile = new CURLFile($file['tmp_name'], $file['type'], $filename . '.png');

        // Prepare cURL request with HARDCODED secret
        $postData = [
            'receiver' => $receiver,
            'filename' => $filename,
            'caption' => $caption,
            'type' => $type,
            'secret' => ADMIN_SECRET, // Secret added here automatically
            'file' => $cfile,
        ];

        $ch = curl_init('https://www.mana-location.com/wwjs/upload');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Accept: application/json'
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($response === false) {
            throw new Exception('cURL Error: ' . curl_error($ch));
        }

        // Decode the response
        $decodedResponse = json_decode($response, true);
        
        // Close curl
        curl_close($ch);

        // Return success response
        echo json_encode([
            'success' => true,
            'message' => 'File uploaded successfully',
            'response' => $decodedResponse
        ]);

    } catch (Exception $e) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => $e->getMessage()
        ]);
    }
    exit;
}
?>
