<?php
/**
 * Slate — central configuration.
 *
 * Loaded by every entry point. Defines constants, loads .env (dev) or
 * environment vars (prod), requires all core includes, starts the
 * session, boots the plugin loader.
 *
 * NEVER hardcode credentials in this file. Use .env locally or set
 * environment variables in your hosting panel. See .env.example.
 */

// ── Version + roots ──────────────────────────────────────────
// Guarded: install.php defines these before requiring config.php,
// so we skip the redefine to avoid a "Constant already defined" warning.
if (!defined('SLATE_VERSION')) define('SLATE_VERSION', '1.0.0');
if (!defined('SLATE_ROOT'))    define('SLATE_ROOT', __DIR__);

// ── Error reporting ──────────────────────────────────────────
// Never expose errors to end users. Log only.
ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');
error_reporting(E_ALL);
ini_set('log_errors', '1');

// ── Load .env (dev only — prod uses env vars set by hosting) ─
if (file_exists(SLATE_ROOT . '/.env')) {
    foreach (file(SLATE_ROOT . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) continue;
        [$k, $v] = explode('=', $line, 2);
        $_ENV[trim($k)] = trim($v, " \t\n\r\0\x0B\"'");
    }
}

if (!function_exists('env')) {
    function env(string $key, $default = '') {
        if (isset($_ENV[$key])) return $_ENV[$key];
        $v = getenv($key);
        return ($v !== false) ? $v : $default;
    }
}

// ── App URL + tenant ─────────────────────────────────────────
define('SLATE_URL', rtrim(env('APP_URL', 'https://greenlightinduction.rakibhasaan.com/slate'), '/'));
define('TENANT_ID', (int)env('TENANT_ID', 1));

// ── App secret (encryption + HMAC) ───────────────────────────
define('APP_SECRET', env('APP_SECRET', ''));

// ── Cron secret ──────────────────────────────────────────────
define('CRON_SECRET', env('CRON_SECRET', ''));

// ── Database ─────────────────────────────────────────────────
define('DB_HOST',    env('DB_HOST',    'localhost'));
define('DB_NAME',    env('DB_NAME',    'rakilluy_booking'));
define('DB_USER',    env('DB_USER',    'rakilluy_booking'));
define('DB_PASS',    env('DB_PASS',    'rakilluy_booking'));
define('DB_CHARSET', env('DB_CHARSET', 'utf8mb4'));

// ── Core includes ────────────────────────────────────────────

// -- PHPMailer loader
$_pm = __DIR__."/vendor/phpmailer/phpmailer/src";
if (is_dir($_pm)) { foreach (["Exception.php","PHPMailer.php","SMTP.php"] as $_pmf) { if (file_exists($_pm."/".$_pmf)) require_once $_pm."/".$_pmf; } }
unset($_pm, $_pmf);

require_once SLATE_ROOT . '/includes/helpers.php';
require_once SLATE_ROOT . '/includes/Database.php';
require_once SLATE_ROOT . '/includes/Hook.php';
require_once SLATE_ROOT . '/includes/Auth.php';
require_once SLATE_ROOT . '/includes/I18n.php';
require_once SLATE_ROOT . '/includes/AuditLog.php';
require_once SLATE_ROOT . '/includes/Notifications.php';
require_once SLATE_ROOT . '/includes/Uploads.php';
require_once SLATE_ROOT . '/includes/Mailer.php';
require_once SLATE_ROOT . '/includes/Plugin.php';
require_once SLATE_ROOT . '/includes/PluginLoader.php';
require_once SLATE_ROOT . '/includes/PublicRouter.php';
require_once SLATE_ROOT . '/includes/ui_components.php';

// ── Force HTTPS (Security setting) ───────────────────────────
// Enforce the `force_https` toggle from admin Settings → Security.
// Skipped on CLI (cron) and pre-install (settings table absent).
if (PHP_SAPI !== 'cli') {
    try {
        if (Database::setting('force_https') === '1') {
            $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
                    || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https')
                    || ((int)($_SERVER['SERVER_PORT'] ?? 0) === 443);
            if (!$isHttps && !empty($_SERVER['HTTP_HOST'])) {
                $host = preg_replace('/[^A-Za-z0-9.\-:]/', '', (string)$_SERVER['HTTP_HOST']);
                header('Location: https://' . $host . ($_SERVER['REQUEST_URI'] ?? '/'), true, 301);
                exit;
            }
            if ($isHttps) {
                header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
            }
        }
    } catch (\Throwable $e) {
        // Not installed yet, or DB unavailable — don't block the request.
    }
}

// ── Session ──────────────────────────────────────────────────
Auth::startSession();

// ── Boot plugins ─────────────────────────────────────────────
// Reads the `plugins` table once, requires each active plugin's
// bootstrap, calls boot(). Inactive plugins are never touched.
PluginLoader::boot();

// ── Dynamic notifications ────────────────────────────────────
// Surface key events in the topbar bell. Listeners are registered after
// plugins boot so the actions they fire are caught. Kept defensive so a
// notification failure never breaks the underlying event.
Hook::addAction('stripe_webhook_event', function (array $event): void {
    try {
        $type = (string)($event['type'] ?? '');
        if ($type !== 'checkout.session.completed'
            && $type !== 'payment_intent.succeeded') return;
        $obj    = $event['data']['object'] ?? [];
        $amount = (int)($obj['amount_total'] ?? $obj['amount_received'] ?? $obj['amount'] ?? 0);
        $cur    = strtoupper((string)($obj['currency'] ?? 'USD'));
        $src    = (string)(($obj['metadata']['source_plugin'] ?? '') ?: 'payment');
        Notifications::add('Payment received', [
            'body' => trim($cur . ' ' . number_format($amount / 100, 2) . ' · ' . $src),
            'icon' => 'card',
            'url'  => defined('SLATE_URL') ? SLATE_URL . '/admin/' : null,
        ]);
    } catch (\Throwable $e) { /* never break the webhook */ }
});
