<?php
ob_start();
require_once 'config.php';

$db = getDB();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $action = $_GET['action'] ?? 'current';
    
    if ($action === 'history') {
        $stmt = $db->query("SELECT * FROM app_downloads ORDER BY uploaded_at DESC");
        $versions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'data' => $versions]);
    } else {
        $stmt = $db->query("SELECT * FROM app_downloads WHERE status = 'active' ORDER BY uploaded_at DESC LIMIT 1");
        $latest = $stmt->fetch(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'data' => $latest]);
    }
    
} elseif ($method === 'POST') {
    if (!isset($_FILES['apk'])) {
        echo json_encode(['success' => false, 'message' => 'No se recibió archivo']);
        exit;
    }
    
    $file = $_FILES['apk'];
    $version = $_POST['version'] ?? '1.0.0';
    $notes = $_POST['release_notes'] ?? '';
    
    $filename = 'cler_' . $version . '_' . time() . '.apk';
    $uploadPath = __DIR__ . '/../uploads/' . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
        $db->exec("UPDATE app_downloads SET status = 'archived' WHERE status = 'active'");
        
        $stmt = $db->prepare("INSERT INTO app_downloads (version, apk_filename, apk_size, release_notes, status) VALUES (?, ?, ?, ?, 'active')");
        $stmt->execute([$version, $filename, $file['size'], $notes]);
        
        echo json_encode(['success' => true, 'message' => 'APK subido correctamente']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error al subir archivo']);
    }
    
} elseif ($method === 'PUT') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (isset($input['rollback_id'])) {
        $db->exec("UPDATE app_downloads SET status = 'archived' WHERE status = 'active'");
        $stmt = $db->prepare("UPDATE app_downloads SET status = 'active' WHERE id = ?");
        $stmt->execute([$input['rollback_id']]);
        echo json_encode(['success' => true, 'message' => 'Versión restaurada']);
    } else {
        $stmt = $db->prepare("UPDATE app_downloads SET download_count = download_count + 1 WHERE id = ?");
        $stmt->execute([$input['id']]);
        echo json_encode(['success' => true]);
    }
}
