<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

require_once '../config/database.php';

try {
    $pdo = getDBConnection();
    
    // Get current app version from request
    $input = json_decode(file_get_contents('php://input'), true);
    $currentVersion = $input['current_version'] ?? '1.11.2';
    
    // Get app settings from database
    $stmt = $pdo->prepare("
        SELECT setting_key, setting_value 
        FROM settings 
        WHERE setting_key IN ('app_version', 'force_update', 'update_message', 'update_url')
    ");
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    // Default values if not set
    $latestVersion = $settings['app_version'] ?? '1.0.0';
    $forceUpdate = $settings['force_update'] ?? '0';
    $updateMessage = $settings['update_message'] ?? 'A new version of the app is available. Please update to continue using all features.';
    $updateUrl = $settings['update_url'] ?? 'https://play.google.com/store/apps/details?id=my.astrosidhi.guru';
    
    // Compare versions
    $needsUpdate = version_compare($currentVersion, $latestVersion, '<');
    
    // If force update is enabled, always show update
    if ($forceUpdate === '1' || $forceUpdate === 1) {
        $needsUpdate = true;
    }
    
    echo json_encode([
        'success' => true,
        'needs_update' => $needsUpdate,
        'current_version' => $currentVersion,
        'latest_version' => $latestVersion,
        'force_update' => $forceUpdate === '1' || $forceUpdate === 1,
        'update_message' => $updateMessage,
        'update_url' => $updateUrl,
        'update_available' => $needsUpdate
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Error checking app update: ' . $e->getMessage()
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred'
    ]);
}
?>
