<?php
// config/app.php

define('APP_NAME',    'Vehicle Verify');
define('APP_VERSION', '1.0.0');
define('BASE_URL',    '/vehicle-verify/public');       // adjust to your server path
define('UPLOAD_DIR',  __DIR__.'/../public/uploads/');
define('UPLOAD_URL',  BASE_URL.'/uploads/');
define('ALLOWED_MIME', ['image/jpeg','image/png','application/pdf']);
define('MAX_UPLOAD',  5 * 1024 * 1024);       // 5 MB

// ── Session ──────────────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE) {
    session_start([
        'cookie_httponly' => true,
        'cookie_samesite' => 'Lax',
    ]);
}

// ── Autoload (simple PSR-4 style) ────────────────────────────
spl_autoload_register(function (string $class): void {
    $file = __DIR__.'/../app/'.str_replace('\\','/',$class).'.php';
    if (file_exists($file)) require_once $file;
});

require_once __DIR__.'/database.php';

// ── Helpers ───────────────────────────────────────────────────

/** Redirect to a URL */
function redirect(string $url): void {
    header('Location: '.$url);
    exit;
}

/** Return current logged-in user array or null */
function currentUser(): ?array {
    return $_SESSION['user'] ?? null;
}

/** Require auth; optionally restrict to roles */
function requireAuth(array $roles = []): array {
    $user = currentUser();
    if (!$user) redirect(BASE_URL.'/index.php');
    if ($roles && !in_array($user['role'], $roles, true)) {
        redirect(BASE_URL.'/index.php');
    }
    return $user;
}

/** Sanitize output */
function e($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8');
}

/** Number of days before expiry to start warning (from settings, cached, default 30) */
function expiryWarnDays(): int {
    static $d = null;
    if ($d === null) {
        $d = 30;
        try {
            $s = db()->prepare("SELECT setting_value FROM settings WHERE setting_key='expiry_warn_days'");
            $s->execute();
            $v = $s->fetchColumn();
            if ($v !== false && (int)$v > 0) $d = (int)$v;
        } catch (Throwable $e) { /* settings table may not exist yet */ }
    }
    return $d;
}

/** Doc status from expiry date */
function docStatus(?string $expiry): string {
    if (!$expiry) return 'unknown';
    $today = new DateTime('today');
    $exp   = new DateTime($expiry);
    if ($exp < $today) return 'expired';
    $diff = (int)$today->diff($exp)->days;
    if ($diff <= expiryWarnDays()) return 'expiring';
    return 'valid';
}

/** Badge HTML */
function statusBadge(string $status, string $lang = 'ar'): string {
    $labels = [
        'ar' => ['valid'=>'ساري','expired'=>'منتهي','expiring'=>'ينتهي قريباً','unknown'=>'—'],
        'en' => ['valid'=>'Valid','expired'=>'Expired','expiring'=>'Expiring Soon','unknown'=>'—'],
        'fr' => ['valid'=>'Valide','expired'=>'Expiré','expiring'=>'Expire bientôt','unknown'=>'—'],
    ];
    $icons  = ['valid'=>'✓','expired'=>'✗','expiring'=>'⚠','unknown'=>'—'];
    $classes= ['valid'=>'badge-success','expired'=>'badge-danger','expiring'=>'badge-warning','unknown'=>'badge-info'];
    $l = $labels[$lang][$status] ?? '—';
    $i = $icons[$status] ?? '—';
    $c = $classes[$status] ?? 'badge-info';
    return "<span class=\"badge $c\">$i $l</span>";
}

/** Avatar initials */
function avatarInitials(string $name): string {
    $parts = explode(' ', trim($name));
    return strtoupper(
        count($parts) >= 2 ? $parts[0][0].$parts[1][0] : ($parts[0][0] ?? '?')
    );
}

/** CSRF token */
function csrf(): string {
    if (empty($_SESSION['csrf'])) {
        $_SESSION['csrf'] = bin2hex(random_bytes(24));
    }
    return $_SESSION['csrf'];
}

function csrfField(): string {
    return '<input type="hidden" name="csrf" value="'.e(csrf()).'">';
}

function verifyCsrf(): void {
    if (($_POST['csrf'] ?? '') !== csrf()) {
        http_response_code(403);
        die('Invalid CSRF token');
    }
}

/** Flash messages */
function flash(string $key, string $msg = '', string $type = 'success'): array|null {
    if ($msg) {
        $_SESSION['flash'][$key] = ['msg' => $msg, 'type' => $type];
        return null;
    }
    $f = $_SESSION['flash'][$key] ?? null;
    unset($_SESSION['flash'][$key]);
    return $f;
}

/** Current language */
function lang(): string {
    return $_SESSION['lang'] ?? 'ar';
}

/** Translate a key */
function t(string $key): string {
    static $translations = null;
    if ($translations === null) {
        $translations = require __DIR__.'/translations.php';
    }
    $l = lang();
    return $translations[$l][$key] ?? $translations['en'][$key] ?? $key;
}

/** Set language */
function setLang(string $l): void {
    if (in_array($l, ['ar','en','fr'], true)) {
        $_SESSION['lang'] = $l;
    }
}

/** Get/set theme */
function theme(): string {
    return $_SESSION['theme'] ?? 'light';
}
function setTheme(string $t): void {
    if (in_array($t, ['light','dark'], true)) $_SESSION['theme'] = $t;
}
