<?php
/**
 * Smart Database Connection - Optimized for PHP 8.2
 * Auto-detects environment (Local vs Live)
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * Universal Security Helpers - MOVED TO TOP for PHP 8.2 Stability
 */
if (!function_exists('h')) {
    function h(?string $value): string {
        return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('escape')) {
    function escape(?string $string): string {
        global $conn;
        if ($string === null) return '';
        return mysqli_real_escape_string($conn, $string);
    }
}

// Enable strict MySQLi error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// --- ENVIRONMENT DETECTION ---
$is_localhost = (($_SERVER['SERVER_NAME'] ?? '') == 'localhost' || ($_SERVER['REMOTE_ADDR'] ?? '') == '127.0.0.1' || PHP_SAPI == 'cli');

if ($is_localhost) {
    $servername = "127.0.0.1";
    $username = "root";
    $password = ""; 
    $dbname = "bhartiya_seva";
} else {
    // LIVE SERVER (PHP 8.2 cPanel)
    $servername = "localhost";
    $username = "flightbo_donation";
    $password = "flightbo_donation"; 
    $dbname = "flightbo_donation"; 
}

try {
    $conn = new mysqli($servername, $username, $password);
    
    // Auto-select or create DB
    try {
        $conn->select_db($dbname);
    } catch (Exception $e) {
        if ($is_localhost) {
            $conn->query("CREATE DATABASE IF NOT EXISTS " . $dbname);
            $conn->select_db($dbname);
        } else {
            throw $e;
        }
    }
    
    $conn->set_charset("utf8mb4");

} catch (mysqli_sql_exception $e) {
    // PHP 8.2 Maintenance Message
    $server_name = $_SERVER['SERVER_NAME'] ?? 'Local';
    die("<div style='text-align:center; padding:50px; font-family:sans-serif;'>
            <h2 style='color:#1e3a8a;'>System Maintenance (PHP 8.2)</h2>
            <p>We are optimizing the database for <b>" . h($server_name) . "</b>.</p>
            <p style='color:#666;'>Please verify credentials in <b>includes/db.php</b>.</p>
            <div style='background:#f8d7da; color:#721c24; padding:15px; border-radius:5px; display:inline-block; margin-top:20px; font-size:0.9rem;'>
                <strong>Connection Error:</strong> " . h($e->getMessage()) . "
            </div>
         </div>");
}
?>
