<?php

require_once __DIR__ . '/../includes/config.php';

function db_config(): array
{
    return [
        'host' => defined('DB_HOST') ? DB_HOST : '127.0.0.1',
        'user' => defined('DB_USER') ? DB_USER : 'root',
        'pass' => defined('DB_PASS') ? DB_PASS : '',
        'name' => defined('DB_NAME') ? DB_NAME : 'expenses',
        'port' => defined('DB_PORT') ? (int) DB_PORT : 3306,
    ];
}

function db(): mysqli
{
    static $conn = null;

    if ($conn instanceof mysqli) {
        return $conn;
    }

    mysqli_report(MYSQLI_REPORT_OFF);

    $config = db_config();
    $conn = @new mysqli(
        $config['host'],
        $config['user'],
        $config['pass'],
        $config['name'],
        $config['port']
    );

    if ($conn->connect_errno) {
        http_response_code(500);
        $safeDetails = htmlspecialchars($conn->connect_error ?: 'Unknown database connection error.');
        $safeHost = htmlspecialchars($config['host']);
        $safeDb = htmlspecialchars($config['name']);
        $safePort = htmlspecialchars((string) $config['port']);

        die(
            '<div style="font-family: Inter, Arial, sans-serif; max-width: 760px; margin: 48px auto; padding: 24px; border: 1px solid #e5e7eb; border-radius: 16px; background: #fff;">'
            . '<h2 style="margin:0 0 12px; color:#111827;">Database connection failed</h2>'
            . '<p style="margin:0 0 10px; color:#374151;">Unable to connect to MySQL for database <strong>' . $safeDb . '</strong> on <strong>' . $safeHost . ':' . $safePort . '</strong>.</p>'
            . '<p style="margin:0 0 16px; color:#b91c1c;">' . $safeDetails . '</p>'
            . '<div style="color:#4b5563; line-height:1.6;">'
            . '<div>Check these items in XAMPP:</div>'
            . '<div>1. Start MySQL in the XAMPP Control Panel.</div>'
            . '<div>2. Confirm the database <strong>' . $safeDb . '</strong> exists in phpMyAdmin.</div>'
            . '<div>3. If MySQL uses a different port, update <code>includes/config.php</code>.</div>'
            . '</div>'
            . '</div>'
        );
    }

    $conn->set_charset('utf8mb4');

    return $conn;
}

$conn = db();
