<?php
// Environment + database configuration.
// This is the only file that changes when moving from XAMPP to shared
// hosting (Phase 11) — everything else in the app reads through it.

// 'development' shows PHP errors on screen; 'production' logs them and
// shows the user a generic message only. This is the one line that changes
// when going live (docs/DEPLOY.md, step 5) — flip it to 'production' only
// after HTTPS is enforced and both temporary passwords are changed.
define('APP_ENV', 'development');

// The app runs in China (Section 1, blueprint) — every date()/time() call
// in the app (today's default date, the dashboard greeting, "saved"
// timestamps, etc.) must use China's clock, not the server's. Without this,
// a server running in UTC computes "morning/afternoon/evening" and "today"
// from a time up to 8 hours behind the household's actual wall clock.
date_default_timezone_set('Asia/Shanghai');

define('DB_HOST', 'mysql');
define('DB_NAME', 'xnzgc0gigsjr3cg6_monthly_ledger');
define('DB_USER', 'xnzgc0gigsjr3cg6_root');
define('DB_PASS', 'AIRtech@DOCs#2023');
define('DB_CHARSET', 'utf8mb4');

define('APP_LOG_FILE', __DIR__ . '/../logs/app.log');

if (APP_ENV === 'development') {
    ini_set('display_errors', '1');
    error_reporting(E_ALL);
} else {
    // Section 17: nothing PHP-generated ever reaches the screen in
    // production — every failure is logged, and the visitor sees one
    // generic, calm message (plain HTML, or a JSON envelope for fetch
    // calls, matching every api/*.php error shape elsewhere in the app).
    ini_set('display_errors', '0');
    error_reporting(E_ALL);
    ini_set('log_errors', '1');
    ini_set('error_log', APP_LOG_FILE);

    function render_generic_error(): void
    {
        http_response_code(500);
        if (($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '') === 'XMLHttpRequest') {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'error' => 'Something went wrong. Please try again.']);
            return;
        }
        echo '<!doctype html><html><head><meta charset="utf-8"><title>Something went wrong</title></head>'
            . '<body style="font-family:-apple-system,sans-serif;text-align:center;padding:4rem 1rem;color:#20242e;">'
            . '<h1>Something went wrong</h1><p>Please try again in a moment.</p></body></html>';
    }

    set_exception_handler(function (Throwable $e): void {
        error_log(sprintf(
            'Uncaught %s: %s in %s:%d%s%s',
            get_class($e),
            $e->getMessage(),
            $e->getFile(),
            $e->getLine(),
            "\n",
            $e->getTraceAsString()
        ));
        render_generic_error();
    });

    // set_exception_handler() doesn't catch fatal errors (e.g. a parse
    // error in a required file) — this does.
    register_shutdown_function(function (): void {
        $error = error_get_last();
        if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
            error_log(sprintf('Fatal error: %s in %s:%d', $error['message'], $error['file'], $error['line']));
            if (!headers_sent()) {
                render_generic_error();
            }
        }
    });
}

// Session / remember-me cookie hardening — used by includes/auth.php.
define('REMEMBER_COOKIE_NAME', 'remember_me');
define('REMEMBER_COOKIE_DAYS', 180);
define('LOGIN_MAX_ATTEMPTS', 5);
define('LOGIN_LOCKOUT_MINUTES', 5);

/** True when the request arrived over HTTPS (directly or via a proxy header). */
function app_is_https(): bool
{
    return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
}
