<?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';

const APP_LATEST_VERSION = '1.10.7';
const APP_LATEST_BUILD_NUMBER = 22;
const APP_DEFAULT_UPDATE_MESSAGE = 'AstroSidhi ka naya update available hai. Wallet, PhonePe, live call aur notification fixes ke liye update karein.';
const APP_DEFAULT_UPDATE_URL = 'https://play.google.com/store/apps/details?id=my.astrosidhi.guru';

try {
    $pdo = getDBConnection();
    
    // Get current app version from request
    $input = json_decode(file_get_contents('php://input'), true);
    $currentVersion = trim((string)($input['current_version'] ?? '1.0.0'));
    $currentBuildNumber = (int)($input['current_build_number'] ?? 0);
    
    // Get app settings from database
    $stmt = $pdo->prepare("
        SELECT setting_key, setting_value 
        FROM settings 
        WHERE setting_key IN ('app_version', 'app_build_number', 'force_update', 'update_message', 'update_url')
    ");
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    // Default values if not set
    $configuredVersion = $settings['app_version'] ?? APP_LATEST_VERSION;
    $latestVersion = version_compare($configuredVersion, APP_LATEST_VERSION, '<')
        ? APP_LATEST_VERSION
        : $configuredVersion;
    $latestBuildNumber = max((int)($settings['app_build_number'] ?? 0), APP_LATEST_BUILD_NUMBER);
    $forceUpdate = $settings['force_update'] ?? '0';
    $updateMessage = $settings['update_message'] ?? APP_DEFAULT_UPDATE_MESSAGE;
    $updateUrl = $settings['update_url'] ?? APP_DEFAULT_UPDATE_URL;
    
    // Compare versions
    $needsUpdate = version_compare($currentVersion, $latestVersion, '<');
    if (!$needsUpdate && $currentVersion === $latestVersion && $currentBuildNumber > 0 && $currentBuildNumber < $latestBuildNumber) {
        $needsUpdate = true;
    }
    $forceUpdateEnabled = ($forceUpdate === '1' || $forceUpdate === 1) && $needsUpdate;
    
    echo json_encode([
        'success' => true,
        'needs_update' => $needsUpdate,
        'current_version' => $currentVersion,
        'current_build_number' => $currentBuildNumber,
        'latest_version' => $latestVersion,
        'latest_build_number' => $latestBuildNumber,
        'force_update' => $forceUpdateEnabled,
        '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'
    ]);
}
?>
