<?php
require_once __DIR__ . '/translations.php';

function gp_lang(PDO $pdo): string
{
    static $lang = null;
    if ($lang !== null) return $lang;

    // 1. URL override (highest priority — also saves to session + user)
    $forced = trim((string)($_GET['lang'] ?? ''));
    if (in_array($forced, ['el', 'en'], true)) {
        if (session_status() !== PHP_SESSION_ACTIVE) session_start();
        $_SESSION['gp_lang'] = $forced;
        // Save to user's account if logged in
        if (function_exists('auth_user')) {
            $u = auth_user();
            if ($u && ($u['id'] ?? 0) > 0) {
                try {
                    $pdo->prepare("UPDATE users SET lang_preference = ? WHERE id = ?")
                        ->execute([$forced, (int)$u['id']]);
                } catch (Throwable $e) {}
            }
        }
        $lang = $forced;
        return $lang;
    }

    // 2. Session
    if (session_status() !== PHP_SESSION_ACTIVE) session_start();
    $sessionLang = trim((string)($_SESSION['gp_lang'] ?? ''));
    if (in_array($sessionLang, ['el', 'en'], true)) {
        $lang = $sessionLang;
        return $lang;
    }

    // 3. User's personal preference (DB)
    if (function_exists('auth_user')) {
        $u = auth_user();
        if ($u && ($u['id'] ?? 0) > 0) {
            try {
                $stmt = $pdo->prepare("SELECT lang_preference FROM users WHERE id = ? LIMIT 1");
                $stmt->execute([(int)$u['id']]);
                $userLang = (string)($stmt->fetchColumn() ?: '');
                if (in_array($userLang, ['el', 'en'], true)) {
                    $_SESSION['gp_lang'] = $userLang;
                    $lang = $userLang;
                    return $lang;
                }
            } catch (Throwable $e) {}
        }
    }

    // 4. App-wide default from settings
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'app_language' LIMIT 1");
        $stmt->execute();
        $v = (string)($stmt->fetchColumn() ?: 'el');
        $lang = in_array($v, ['el', 'en'], true) ? $v : 'el';
    } catch (Throwable $e) {
        $lang = 'el';
    }
    return $lang;
}

function gp_tr(PDO $pdo, string $key): string
{
    static $dict = null;
    if ($dict === null) $dict = gp_translations();
    $l = gp_lang($pdo);
    return $dict[$key][$l] ?? $dict[$key]['en'] ?? $key;
}

function gp_project_statuses(PDO $pdo, bool $activeOnly = true): array
{
    try {
        $sql = "SELECT status_key, label_el, label_en, is_active FROM project_statuses";
        if ($activeOnly) $sql .= " WHERE is_active = 1";
        $sql .= " ORDER BY sort_order ASC, id ASC";
        $rows = $pdo->query($sql)->fetchAll();

        if ($rows) {
            $lang = gp_lang($pdo);
            $out = [];
            foreach ($rows as $r) {
                $out[(string)$r['status_key']] = $lang === 'en' ? (string)$r['label_en'] : (string)$r['label_el'];
            }
            return $out;
        }
    } catch (Throwable $e) {}

    return [
        'new'         => gp_lang($pdo) === 'en' ? 'New'          : 'Νέο',
        'in_progress' => gp_lang($pdo) === 'en' ? 'In progress'  : 'Σε εξέλιξη',
        'completed'   => gp_lang($pdo) === 'en' ? 'Completed'    : 'Ολοκληρωμένο',
        'cancelled'   => gp_lang($pdo) === 'en' ? 'Cancelled'    : 'Ακυρωμένο',
    ];
}

function gp_project_status_label(PDO $pdo, string $status): string
{
    $all = gp_project_statuses($pdo, false);
    return $all[$status] ?? $status;
}
