<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit;
}

$pdo = getDB();

// Create table if not exists
$pdo->exec("CREATE TABLE IF NOT EXISTS app_versions (
    id INT PRIMARY KEY AUTO_INCREMENT,
    version VARCHAR(20) NOT NULL,
    build_number INT NOT NULL,
    download_url TEXT NOT NULL,
    changelog TEXT,
    is_mandatory BOOLEAN DEFAULT 0,
    is_active BOOLEAN DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add') {
            $downloadUrl = $_POST['download_url'] ?? '';
            
            // Handle file upload
            if (isset($_FILES['app_file']) && $_FILES['app_file']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = '../downloads/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $fileName = 'app-v' . $_POST['version'] . '.exe';
                $uploadPath = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['app_file']['tmp_name'], $uploadPath)) {
                    $downloadUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/rssecurity_backend/downloads/' . $fileName;
                }
            }
            
            if (empty($downloadUrl)) {
                $error = "Please provide either a file upload or download URL";
            } else {
                $stmt = $pdo->prepare("INSERT INTO app_versions (version, build_number, download_url, changelog, is_mandatory) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$_POST['version'], $_POST['build_number'], $downloadUrl, $_POST['changelog'], isset($_POST['is_mandatory']) ? 1 : 0]);
                $success = "Version added successfully!";
            }
        } elseif ($_POST['action'] === 'delete') {
            $stmt = $pdo->prepare("DELETE FROM app_versions WHERE id = ?");
            $stmt->execute([$_POST['id']]);
            $success = "Version deleted successfully!";
        }
    }
}

// Fetch versions
$versions = $pdo->query("SELECT * FROM app_versions ORDER BY build_number DESC")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>App Versions - RSecurity Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100">
    <div class="flex h-screen">
        <?php include 'sidebar.php'; ?>
        
        <main class="flex-1 overflow-y-auto">
            <div class="p-8">
                <div class="flex justify-between items-center mb-6">
                    <h1 class="text-3xl font-bold text-gray-800">App Versions</h1>
                    <button onclick="document.getElementById('addModal').classList.remove('hidden')" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                        Add Version
                    </button>
                </div>
                
                <?php if (isset($success)): ?>
                <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6">
                    <?= htmlspecialchars($success) ?>
                </div>
                <?php endif; ?>
                
                <?php if (isset($error)): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
                    <?= htmlspecialchars($error) ?>
                </div>
                <?php endif; ?>
                
                <div class="bg-white rounded-lg shadow-md overflow-hidden">
                    <table class="min-w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Version</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Build</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Download URL</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Mandatory</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Created</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php foreach ($versions as $version): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap font-semibold"><?= htmlspecialchars($version['version']) ?></td>
                                <td class="px-6 py-4 whitespace-nowrap"><?= $version['build_number'] ?></td>
                                <td class="px-6 py-4 text-sm text-blue-600 truncate max-w-xs"><?= htmlspecialchars($version['download_url']) ?></td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php if ($version['is_mandatory']): ?>
                                        <span class="px-2 py-1 text-xs bg-red-100 text-red-800 rounded">Yes</span>
                                    <?php else: ?>
                                        <span class="px-2 py-1 text-xs bg-gray-100 text-gray-800 rounded">No</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm"><?= date('Y-m-d', strtotime($version['created_at'])) ?></td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <form method="POST" class="inline" onsubmit="return confirm('Delete this version?')">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $version['id'] ?>">
                                        <button type="submit" class="text-red-600 hover:text-red-900">Delete</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>

    <!-- Add Modal -->
    <div id="addModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
        <div class="bg-white rounded-lg p-8 max-w-md w-full">
            <h2 class="text-2xl font-bold mb-4">Add New Version</h2>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="add">
                <div class="mb-4">
                    <label class="block text-gray-700 font-semibold mb-2">Version</label>
                    <input type="text" name="version" placeholder="1.0.1" class="w-full px-4 py-2 border rounded-lg" required>
                </div>
                <div class="mb-4">
                    <label class="block text-gray-700 font-semibold mb-2">Build Number</label>
                    <input type="number" name="build_number" placeholder="2" class="w-full px-4 py-2 border rounded-lg" required>
                </div>
                <div class="mb-4">
                    <label class="block text-gray-700 font-semibold mb-2">Upload File (.exe)</label>
                    <input type="file" name="app_file" accept=".exe" class="w-full px-4 py-2 border rounded-lg" onchange="document.getElementById('urlField').disabled = this.files.length > 0">
                    <p class="text-xs text-gray-500 mt-1">Or provide download URL below</p>
                </div>
                <div class="mb-4">
                    <label class="block text-gray-700 font-semibold mb-2">Download URL</label>
                    <input type="url" id="urlField" name="download_url" placeholder="http://..." class="w-full px-4 py-2 border rounded-lg">
                </div>
                <div class="mb-4">
                    <label class="block text-gray-700 font-semibold mb-2">Changelog</label>
                    <textarea name="changelog" rows="3" class="w-full px-4 py-2 border rounded-lg"></textarea>
                </div>
                <div class="mb-4">
                    <label class="flex items-center">
                        <input type="checkbox" name="is_mandatory" class="mr-2">
                        <span class="text-gray-700">Mandatory Update</span>
                    </label>
                </div>
                <div class="flex gap-2">
                    <button type="submit" class="flex-1 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">Add</button>
                    <button type="button" onclick="document.getElementById('addModal').classList.add('hidden')" class="flex-1 bg-gray-300 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-400">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>
