<?php
/**
 * SIPIUTANG - Bootstrap aplikasi
 * Memuat autoloader, konfigurasi, sesi, pengaturan, dan pembantu global.
 */

define('SIPIUTANG_ROOT', dirname(__DIR__));
define('SIPIUTANG_VERSION', '1.0.0');

// --------------------------------------------------------------- Autoloader
spl_autoload_register(function (string $class): void {
    $prefix = 'App\\';
    if (!str_starts_with($class, $prefix)) return;
    $rel  = substr($class, strlen($prefix));
    $file = SIPIUTANG_ROOT . '/app/' . str_replace('\\', '/', $rel) . '.php';
    if (is_file($file)) require $file;
});

// Composer opsional (PhpSpreadsheet / Dompdf bila dipasang)
if (is_file(SIPIUTANG_ROOT . '/vendor/autoload.php')) {
    require SIPIUTANG_ROOT . '/vendor/autoload.php';
}

use App\Core\Config;
use App\Core\Database;
use App\Core\Session;
use App\Core\Settings;
use App\Core\Logger;
use App\Core\Response;

// --------------------------------------------------------------- Konfigurasi
$configFile = SIPIUTANG_ROOT . '/config/config.php';
$configLoaded = Config::load($configFile);

date_default_timezone_set(Config::get('app.timezone', 'Asia/Jakarta'));
mb_internal_encoding('UTF-8');

// Penanganan error
$debug = (bool)Config::get('app.debug', false);
error_reporting(E_ALL);
ini_set('display_errors', $debug ? '1' : '0');
ini_set('log_errors', '1');

set_exception_handler(function (\Throwable $e) use ($debug) {
    Logger::error($e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine() . "\n" . $e->getTraceAsString());
    if (PHP_SAPI === 'cli') { fwrite(STDERR, $e->getMessage() . "\n" . $e->getTraceAsString() . "\n"); exit(1); }
    if ($debug) {
        http_response_code(500);
        echo '<pre style="padding:16px;font:13px/1.5 monospace;background:#fff3f3;color:#900;white-space:pre-wrap">';
        echo htmlspecialchars(get_class($e) . ': ' . $e->getMessage() . "\n" . $e->getFile() . ':' . $e->getLine() . "\n\n" . $e->getTraceAsString());
        echo '</pre>';
        exit;
    }
    Response::abort(500, 'Terjadi kesalahan pada sistem. Silakan hubungi administrator. (Rujukan log: ' . date('Y-m-d H:i:s') . ')');
});

set_error_handler(function (int $no, string $str, string $file = '', int $line = 0) {
    if (!(error_reporting() & $no)) return false;
    throw new \ErrorException($str, 0, $no, $file, $line);
});

// --------------------------------------------------------------- Pembantu global
require_once SIPIUTANG_ROOT . '/app/Helpers/functions.php';

if (!$configLoaded) {
    // Belum terpasang -> arahkan ke wizard instalasi
    if (PHP_SAPI !== 'cli') {
        $base = rtrim(str_replace('\\', '/', dirname((string)($_SERVER['SCRIPT_NAME'] ?? ''))), '/');
        $uri  = (string)($_SERVER['REQUEST_URI'] ?? '');
        if (!str_contains($uri, '/install')) {
            header('Location: ' . $base . '/install/');
            exit;
        }
        return;
    }
    return;
}

// --------------------------------------------------------------- Basis data & sesi
Database::init(Config::get('db'));
Settings::load();
date_default_timezone_set(Settings::str('umum.zona_waktu', Config::get('app.timezone', 'Asia/Jakarta')));

if (PHP_SAPI !== 'cli') {
    Session::start();
    Response::securityHeaders();
}
