<?php
/**
 * Check Maintenance Mode API
 * Ultra-lightweight endpoint for fast app startup check
 * Returns maintenance status and custom message
 */

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

// Security headers
$apiKey = $_SERVER['HTTP_X_API_KEY'] ?? '';
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

if ($apiKey !== 'ensi_app_2025_secure_key_v1' || strpos($userAgent, 'ensi-flutter-app') === false) {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

require_once 'config.php';

try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
        DB_USER,
        DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    // Get maintenance settings (super fast query)
    $stmt = $pdo->prepare("
        SELECT setting_key, setting_value 
        FROM app_settings 
        WHERE setting_key IN ('maintenance_mode', 'maintenance_title', 'maintenance_message', 'app_version', 'force_update')
    ");
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

    // Build response
    $response = [
        'success' => true,
        'maintenance_mode' => (int)($settings['maintenance_mode'] ?? 0) === 1,
        'maintenance_title' => $settings['maintenance_title'] ?? 'Under Construction',
        'maintenance_message' => $settings['maintenance_message'] ?? 'We are updating the app. Please check back soon!',
        'app_version' => $settings['app_version'] ?? '1.0.0',
        'force_update' => (int)($settings['force_update'] ?? 0) === 1,
        'timestamp' => time()
    ];

    echo json_encode($response);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database error',
        'maintenance_mode' => false // Fail-safe: allow access if DB error
    ]);
}
