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

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

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

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

try {
    $pdo = getDBConnection();
    
    // Get launch configuration settings
    $stmt = $pdo->prepare("
        SELECT setting_key, setting_value 
        FROM settings 
        WHERE setting_key IN (
            'app_version', 'min_android_version', 'min_ios_version', 
            'force_update', 'update_message', 'play_store_url', 
            'app_store_url', 'maintenance_mode', 'maintenance_message',
            'system_enabled'
        )
    ");
    $stmt->execute();
    
    $settings = [];
    while ($row = $stmt->fetch()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    
    // Set default values if not found
    $launch_config = [
        'app_version' => $settings['app_version'] ?? '1.0.0',
        'min_android_version' => $settings['min_android_version'] ?? '6.0',
        'min_ios_version' => $settings['min_ios_version'] ?? '12.0',
        'force_update' => ($settings['force_update'] ?? '0') === '1',
        'update_message' => $settings['update_message'] ?? 'A new version of the app is available. Please update to continue using all features.',
        'play_store_url' => $settings['play_store_url'] ?? 'https://play.google.com/store/apps/details?id=my.astroguru.astro',
        'app_store_url' => $settings['app_store_url'] ?? '',
        'maintenance_mode' => ($settings['maintenance_mode'] ?? '0') === '1',
        'maintenance_message' => $settings['maintenance_message'] ?? 'The app is currently under maintenance. Please try again later.',
        'system_enabled' => ($settings['system_enabled'] ?? '1') === '1'
    ];
    
    echo json_encode([
        'success' => true,
        'launch_config' => $launch_config,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred'
    ]);
}
?> 