<?php
header('Content-Type: application/json');
require_once '../config.php';

$currentVersion = $_GET['version'] ?? '1.0.0';
$currentBuild = (int)($_GET['build'] ?? 1);

try {
    $pdo = getDB();
    
    // Get latest version
    $stmt = $pdo->query("SELECT * FROM app_versions WHERE is_active = 1 ORDER BY build_number DESC LIMIT 1");
    $latestVersion = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$latestVersion) {
        echo json_encode(['success' => false, 'error' => 'No versions available']);
        exit;
    }
    
    $updateAvailable = $latestVersion['build_number'] > $currentBuild;
    
    echo json_encode([
        'success' => true,
        'update_available' => $updateAvailable,
        'latest_version' => $latestVersion['version'],
        'latest_build' => $latestVersion['build_number'],
        'download_url' => $latestVersion['download_url'],
        'changelog' => $latestVersion['changelog'],
        'is_mandatory' => (bool)$latestVersion['is_mandatory']
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => 'Failed to check updates']);
}
