<?php
/**
 * Site Settings Helper + Database Connection
 * Auto-prepended to all PHP pages via .htaccess / .user.ini
 * Provides getSetting(), CSRF, rate-limiting, and DB connection globally.
 */

// ── Environment configuration ──────────────────────────────────────
define('APP_ENV', 'development');
define('RATE_LIMIT_MAX', 5);
define('RATE_LIMIT_SECONDS', (APP_ENV === 'development') ? 10 : 900);

// ── Secure session defaults ────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE && php_sapi_name() !== 'cli') {
    ini_set('session.cookie_httponly', '1');
    ini_set('session.cookie_samesite', 'Lax');
    ini_set('session.use_strict_mode', '1');
}

// ── CSRF Protection ────────────────────────────────────────────────
function csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}
function csrf_field() {
    return '<input type="hidden" name="csrf_token" value="' . csrf_token() . '">';
}
function csrf_verify() {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!isset($_POST['csrf_token']) || !isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
            die('Invalid request. Please go back and try again.');
        }
    }
    return true;
}

// ── Rate limiting ──────────────────────────────────────────────────
function rate_limit_check($key, $maxAttempts = null, $windowSeconds = null) {
    $maxAttempts = $maxAttempts ?? RATE_LIMIT_MAX;
    $windowSeconds = $windowSeconds ?? RATE_LIMIT_SECONDS;
    $file = sys_get_temp_dir() . '/ratelimit_' . md5($key);
    $attempts = [];
    if (file_exists($file)) {
        $attempts = json_decode(file_get_contents($file), true) ?: [];
    }
    $now = time();
    $attempts = array_filter($attempts, function($t) use ($now, $windowSeconds) { return $t > ($now - $windowSeconds); });
    if (count($attempts) >= $maxAttempts) return false;
    $attempts[] = $now;
    file_put_contents($file, json_encode($attempts));
    return true;
}

// ── Database connection ────────────────────────────────────────────
$servername = "localhost";
// --- LOCALHOST ---
// $username   = "root";
// $password   = "";
// $dbname     = "dbhacu";
// --- PRODUCTION (comment out above, uncomment below) ---
$username   = "whitestonetrustcu_db";
$password   = "ntbtUsuB7vGpyDJ2kBY3";
$dbname     = "whitestonetrustcu_db";

$mysqli = @mysqli_connect($servername, $username, $password, $dbname);

if ($mysqli) {
    mysqli_set_charset($mysqli, 'utf8mb4');
    // Store all timestamps in UTC — conversion happens on display per user timezone
    mysqli_query($mysqli, "SET time_zone = '+00:00'");
}

// Backward-compatible alias
$con = $mysqli;

// ── Admin session guard (man / chairman directories) ───────────────
$currentScript = basename($_SERVER['SCRIPT_NAME']);
$currentDir    = basename(dirname($_SERVER['SCRIPT_NAME']));

if ($currentDir === 'man' || $currentDir === 'chairman') {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    if (
        $currentScript !== 'login.php' &&
        $currentScript !== 'index.php' &&
        $currentScript !== 'register.php' &&
        !isset($_SESSION['man'])
    ) {
        die('Access Denied: You must be logged in as admin.');
    }
    $timeout = 1800;
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $timeout)) {
        session_unset();
        session_destroy();
        echo "<script>alert('Session expired. Please log in again.');window.location.href='../index.php';</script>";
        exit();
    }
    $_SESSION['LAST_ACTIVITY'] = time();
}

// ── Site settings helper ───────────────────────────────────────────
function getSiteSettings() {
    static $settings = null;
    if ($settings !== null) return $settings;

    global $mysqli, $con;
    $db = $mysqli ?? $con ?? null;

    // Auto-connect if no existing connection
    if (!$db) {
        $db = @mysqli_connect('localhost', 'root', '', 'whitestonetrustcu_db');
        if (!$db) { $settings = []; return $settings; }
        mysqli_set_charset($db, 'utf8mb4');
    }

    $result = @mysqli_query($db, "SELECT setting_key, setting_value FROM site_settings");
    $settings = [];
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }
    }
    return $settings;
}

function getSetting($key, $default = '') {
    $settings = getSiteSettings();
    return isset($settings[$key]) && $settings[$key] !== '' ? $settings[$key] : $default;
}

// ── Currency formatting ────────────────────────────────────────────
function formatCurrency($amount, $currencyCode = null) {
    static $map = [
        'USD' => '$',  'EUR' => '€',  'GBP' => '£',  'JPY' => '¥',
        'CHF' => 'Fr', 'CAD' => 'C$', 'AUD' => 'A$', 'NZD' => 'NZ$',
        'SGD' => 'S$', 'HKD' => 'HK$','AED' => 'د.إ','SAR' => '﷼',
        'QAR' => 'QR', 'CNY' => '¥',  'INR' => '₹',  'ZAR' => 'R',
        'NGN' => '₦',  'KES' => 'KSh','SEK' => 'kr', 'NOK' => 'kr',
        'DKK' => 'kr', 'PLN' => 'zł', 'TRY' => '₺',  'RUB' => '₽',
        'BRL' => 'R$', 'MXN' => 'MX$','ARS' => 'AR$','CLP' => 'CLP$',
        'COP' => 'COL$','PEN' => 'S/','EGP' => 'E£', 'PKR' => 'Rs',
        'BDT' => '৳',  'PHP' => '₱',  'IDR' => 'Rp', 'MYR' => 'RM',
        'THB' => '฿',  'VND' => '₫',  'KRW' => '₩',  'ILS' => '₪',
        'MAD' => 'DH', 'TND' => 'DT', 'BHD' => 'BD', 'KWD' => 'KD',
        'OMR' => 'RO', 'JOD' => 'JD', 'RON' => 'lei','BGN' => 'лв',
        'CZK' => 'Kč', 'HUF' => 'Ft', 'ISK' => 'kr', 'HRK' => 'kn',
        'UAH' => '₴',  'DZD' => 'DA', 'LBP' => 'LL', 'IRR' => '﷼',
    ];
    $code = $currencyCode ?? getSetting('currency', 'USD');
    if ($code === null || $code === '') {
        $code = getSetting('currency', 'USD');
    }
    // Handle admin registration storing raw symbols or HTML entities
    $len = mb_strlen($code);
    if (($len === 1 || strpos($code, '&') === 0 || strpos($code, '€') !== false || strpos($code, '£') !== false || strpos($code, '¥') !== false) && $len <= 8) {
        $symbol = html_entity_decode($code, ENT_QUOTES, 'UTF-8');
    } else {
        $symbol = $map[$code] ?? $code;
    }
    return $symbol . number_format((float)$amount, 2);
}

// ── User Timezone Date Formatting ─────────────────────────────────
function getUserTimezone() {
    // Return user's timezone from session, or fall back to UTC
    if (isset($_SESSION['user_timezone']) && $_SESSION['user_timezone'] !== '') {
        return $_SESSION['user_timezone'];
    }
    // If logged in but no session timezone yet, try to load from DB
    if (isset($_SESSION['chap'])) {
        global $mysqli, $con;
        $db = $mysqli ?? $con ?? null;
        if ($db) {
            try {
                $email = mysqli_real_escape_string($db, $_SESSION['chap']);
                $result = mysqli_query($db, "SELECT timezone FROM users WHERE email = '$email' LIMIT 1");
                if ($result && $row = mysqli_fetch_assoc($result)) {
                    $tz = $row['timezone'] ?? 'UTC';
                    $_SESSION['user_timezone'] = $tz;
                    return $tz;
                }
            } catch (Exception $e) {
                // Column may not exist — use session timezone or UTC
            }
        }
    }
    return 'UTC';
}

function formatUserDate($dbDate, $format = 'd M Y, h:i A') {
    if (empty($dbDate) || $dbDate === '0000-00-00 00:00:00' || $dbDate === '0000-00-00') {
        return '—';
    }
    $tz = getUserTimezone();
    try {
        $dt = new DateTime($dbDate, new DateTimeZone('UTC'));
        $dt->setTimezone(new DateTimeZone($tz));
        return $dt->format($format);
    } catch (Exception $e) {
        return $dbDate; // fallback: raw value
    }
}

function currencySymbol($currencyCode = null) {
    static $map = null;
    if ($map === null) {
        // Extract just the symbol from formatCurrency by calling it with 0
        // We reuse the same logic inline for performance
        $map = [
            'USD' => '$',  'EUR' => '€',  'GBP' => '£',  'JPY' => '¥',
            'CHF' => 'Fr', 'CAD' => 'C$', 'AUD' => 'A$', 'NZD' => 'NZ$',
            'SGD' => 'S$', 'HKD' => 'HK$','AED' => 'د.إ','SAR' => '﷼',
            'QAR' => 'QR', 'CNY' => '¥',  'INR' => '₹',  'ZAR' => 'R',
            'NGN' => '₦',  'KES' => 'KSh','SEK' => 'kr', 'NOK' => 'kr',
            'DKK' => 'kr', 'PLN' => 'zł', 'TRY' => '₺',  'RUB' => '₽',
            'BRL' => 'R$', 'MXN' => 'MX$','ARS' => 'AR$','CLP' => 'CLP$',
            'COP' => 'COL$','PEN' => 'S/','EGP' => 'E£', 'PKR' => 'Rs',
            'BDT' => '৳',  'PHP' => '₱',  'IDR' => 'Rp', 'MYR' => 'RM',
            'THB' => '฿',  'VND' => '₫',  'KRW' => '₩',  'ILS' => '₪',
            'MAD' => 'DH', 'TND' => 'DT', 'BHD' => 'BD', 'KWD' => 'KD',
            'OMR' => 'RO', 'JOD' => 'JD', 'RON' => 'lei','BGN' => 'лв',
            'CZK' => 'Kč', 'HUF' => 'Ft', 'ISK' => 'kr', 'HRK' => 'kn',
            'UAH' => '₴',  'DZD' => 'DA', 'LBP' => 'LL', 'IRR' => '﷼',
        ];
    }
    $code = $currencyCode ?? getSetting('currency', 'USD');
    if ($code === null || $code === '') {
        $code = getSetting('currency', 'USD');
    }
    $len = mb_strlen($code);
    if (($len === 1 || strpos($code, '&') === 0 || strpos($code, '€') !== false || strpos($code, '£') !== false || strpos($code, '¥') !== false) && $len <= 8) {
        return html_entity_decode($code, ENT_QUOTES, 'UTF-8');
    }
    return $map[$code] ?? $code;
}
