<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Your admin secret key (MUST match the one in main.js)
define('ADMIN_SECRET', 'mana-location-whatsapp-bot'); // Change this to your actual secret

// Helper functions
function setCorsHeaders() {
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization");
    header("Access-Control-Allow-Credentials: true");
}

function sanitizeInput($data) {
    return htmlspecialchars(strip_tags(trim($data)));
}

function logRequest($type, $data) {
    $logDir = __DIR__ . '/logs';
    if (!file_exists($logDir)) {
        mkdir($logDir, 0777, true);
    }
    $logFile = $logDir . '/api_requests.log';
    $logEntry = date('Y-m-d H:i:s') . " - [$type] " . json_encode($data) . PHP_EOL;
    file_put_contents($logFile, $logEntry, FILE_APPEND);
}

function logError($message, $context = []) {
    $logDir = __DIR__ . '/logs';
    if (!file_exists($logDir)) {
        mkdir($logDir, 0777, true);
    }
    $logFile = $logDir . '/errors.log';
    $logEntry = date('Y-m-d H:i:s') . " - ERROR: $message " . json_encode($context) . PHP_EOL;
    file_put_contents($logFile, $logEntry, FILE_APPEND);
}

function makeApiRequest($endpoint, $data, $isMultipart = false) {
    $apiUrl = 'https://www.mana-location.com/wwjs/' . $endpoint;
    
    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    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));
    }
    
    curl_close($ch);
    
    return json_decode($response, true);
}

// Handle API requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    setCorsHeaders();
    
    try {
        // Check if file was uploaded
        if (!isset($_FILES['file'])) {
            throw new Exception('No file uploaded');
        }

        // Validate other fields
        $requiredFields = ['receiver', 'filename', 'caption', 'type'];
        foreach ($requiredFields as $field) {
            if (!isset($_POST[$field]) || empty($_POST[$field])) {
                throw new Exception("Missing required field: $field");
            }
        }

        // Get and validate secret
        $secret = $_POST['secret'] ?? '';
        if (empty($secret) || $secret !== ADMIN_SECRET) {
            throw new Exception('Unauthorized - Invalid or missing secret key');
        }

        $file = $_FILES['file'];
        if ($file['error'] !== UPLOAD_ERR_OK) {
            $uploadErrors = [
                UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize',
                UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE',
                UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
                UPLOAD_ERR_NO_FILE => 'No file was uploaded',
                UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
                UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
                UPLOAD_ERR_EXTENSION => 'File upload stopped by extension'
            ];
            $errorMsg = $uploadErrors[$file['error']] ?? 'Unknown upload error';
            throw new Exception('File upload error: ' . $errorMsg);
        }

        // Validate file size (max 10MB for images)
        if ($file['size'] > 10 * 1024 * 1024) {
            throw new Exception('File size exceeds 10MB limit');
        }

        // Validate file type
        $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
        if (!in_array($file['type'], $allowedTypes)) {
            throw new Exception('Invalid file type. Only images are allowed (JPEG, PNG, GIF, WEBP)');
        }

        $data = [
            'receiver' => sanitizeInput($_POST['receiver']),
            'filename' => sanitizeInput($_POST['filename']),
            'caption' => sanitizeInput($_POST['caption']),
            'type' => sanitizeInput($_POST['type']),
            'secret' => $secret, // Include secret in request
            'file' => new CURLFile($file['tmp_name'], $file['type'], $file['name'])
        ];

        logRequest('image-upload', array_diff_key($data, ['file' => null]));
        $response = makeApiRequest('upload', $data, true);
        
        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'response' => $response]);
        exit;
        
    } catch (Exception $e) {
        logError($e->getMessage(), ['file' => 'upload_image.php']);
        http_response_code(400);
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        exit;
    }
}

// Only output HTML if it's a GET request
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Image - WhatsApp Bot</title>
    <style>
        * {
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
            background: #075E54;
            margin: 0;
            padding: 20px;
            color: #333;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        h1 {
            color: #075E54;
            margin-top: 0;
            text-align: center;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #075E54;
        }
        input, select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }
        input[type="password"] {
            font-family: monospace;
        }
        button {
            background: #25D366;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            width: 100%;
        }
        button:hover {
            background: #128C7E;
        }
        .preview-container {
            margin: 15px 0;
            text-align: center;
        }
        #image-preview {
            max-width: 100%;
            max-height: 300px;
            display: none;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .alert {
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 20px;
            display: none;
        }
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info-text {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
        hr {
            margin: 20px 0;
            border: none;
            border-top: 1px solid #eee;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>📤 Upload Image to WhatsApp</h1>
        
        <div id="alert" class="alert"></div>
        
        <form id="upload-form" method="POST" enctype="multipart/form-data">
            <div class="form-group">
                <label for="secret">Admin Secret Key:</label>
                <input type="password" id="secret" name="secret" required autocomplete="off">
                <div class="info-text">Required for authentication</div>
            </div>
            
            <div class="form-group">
                <label for="receiver">Receiver:</label>
                <input type="text" id="receiver" name="receiver" required placeholder="e.g., 60123456789 or group-id">
                <div class="info-text">Phone number for individual, or group ID for group</div>
            </div>

            <div class="form-group">
                <label for="filename">Filename:</label>
                <input type="text" id="filename" name="filename" required placeholder="image_name">
                <div class="info-text">Name for the image (without extension)</div>
            </div>

            <div class="form-group">
                <label for="caption">Caption:</label>
                <input type="text" id="caption" name="caption" required placeholder="Image description">
            </div>

            <div class="form-group">
                <label for="type">Receiver Type:</label>
                <select id="type" name="type" required>
                    <option value="individual">Individual</option>
                    <option value="group">Group</option>
                </select>
            </div>

            <div class="form-group">
                <label for="file">Image:</label>
                <input type="file" id="file" name="file" accept="image/*" required>
                <div class="info-text">Max size: 10MB. Allowed: JPG, PNG, GIF, WEBP</div>
            </div>
            
            <div class="preview-container">
                <img id="image-preview" src="#" alt="Preview">
            </div>

            <button type="submit" id="submitBtn">📤 Upload Image</button>
        </form>
        
        <hr>
        
        <div style="text-align: center; font-size: 12px; color: #666;">
            <p>Images will be sent as viewable images (not as file attachments)</p>
            <p><a href="/wwjs" style="color: #25D366;">Go to Full Dashboard →</a></p>
        </div>
    </div>
    
    <script>
    // Image preview functionality
    document.getElementById('file').addEventListener('change', function(e) {
        const preview = document.getElementById('image-preview');
        const file = e.target.files[0];
        
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                preview.src = e.target.result;
                preview.style.display = 'block';
            }
            reader.readAsDataURL(file);
        } else {
            preview.style.display = 'none';
            preview.src = '#';
        }
    });

    function showAlert(message, type) {
        const alert = document.getElementById('alert');
        alert.className = `alert alert-${type}`;
        alert.innerHTML = message;
        alert.style.display = 'block';
        setTimeout(() => {
            alert.style.display = 'none';
        }, 5000);
    }

    // Form submission
    document.getElementById('upload-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const submitBtn = document.getElementById('submitBtn');
        const formData = new FormData(e.target);
        const secret = document.getElementById('secret').value;
        
        // Validate secret is provided
        if (!secret) {
            showAlert('Please enter the admin secret key', 'error');
            return;
        }
        
        submitBtn.disabled = true;
        submitBtn.innerHTML = '⏳ Uploading...';
        
        try {
            const response = await fetch(window.location.href, {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            
            if (result.success && result.response && result.response.success) {
                showAlert('✅ Image sent to WhatsApp successfully! Message ID: ' + result.response.messageId, 'success');
                e.target.reset();
                document.getElementById('image-preview').style.display = 'none';
                // Keep the secret field value
                document.getElementById('secret').value = secret;
            } else {
                const errorMsg = result.response?.error || result.error || 'Unknown error';
                showAlert('❌ Failed: ' + errorMsg, 'error');
            }
        } catch (error) {
            console.error('Upload error:', error);
            showAlert('❌ Network error: ' + error.message, 'error');
        } finally {
            submitBtn.disabled = false;
            submitBtn.innerHTML = '📤 Upload Image';
        }
    });
    </script>
</body>
</html>
<?php } ?>
