<?php
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth.php';

function e($str) { return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8'); }

function formatRupiah($n) { return 'Rp ' . number_format($n ?? 0, 0, ',', '.'); }

function formatDate($d, $fmt = 'd M Y') { return $d ? date($fmt, strtotime($d)) : '-'; }

function formatDateTime($d) { return $d ? date('d/m/Y H:i', strtotime($d)) : '-'; }

function generateBillNumber() {
    return 'BILL/' . date('Ymd') . '/' . strtoupper(substr(uniqid(), -6));
}

function generateCustomerNumber($branchId) {
    $db = db();
    $stmt = $db->prepare("SELECT COUNT(*) as c FROM customers WHERE branch_id = ?");
    $stmt->execute([$branchId]);
    $count = $stmt->fetch()['c'] + 1;
    $branch = $db->prepare("SELECT code FROM branches WHERE id = ?")->execute([$branchId]);
    return 'LFN-' . str_pad($count, 5, '0', STR_PAD_LEFT);
}

function getSetting($key, $default = null) {
    static $cache = [];
    if (!isset($cache[$key])) {
        $stmt = db()->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        $row = $stmt->fetch();
        $cache[$key] = $row ? $row['setting_value'] : $default;
    }
    return $cache[$key];
}

function logActivity($userId, $action, $desc, $targetType = null, $targetId = null) {
    $stmt = db()->prepare("INSERT INTO activity_logs (user_id, action, description, target_type, target_id, ip_address, user_agent) 
                           VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $userId, $action, $desc, $targetType, $targetId,
        $_SERVER['REMOTE_ADDR'] ?? null,
        $_SERVER['HTTP_USER_AGENT'] ?? null
    ]);
}

function redirect($url, $message = null, $type = 'success') {
    if ($message) {
        $_SESSION['flash_message'] = $message;
        $_SESSION['flash_type']    = $type;
    }
    header("Location: $url");
    exit;
}

function flashMessage() {
    if (isset($_SESSION['flash_message'])) {
        $msg  = $_SESSION['flash_message'];
        $type = $_SESSION['flash_type'] ?? 'info';
        unset($_SESSION['flash_message'], $_SESSION['flash_type']);
        return "<div class='alert alert-{$type} alert-dismissible fade show'>
                    {$msg}
                    <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                </div>";
    }
    return '';
}

function csrfToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function csrfField() {
    return '<input type="hidden" name="csrf_token" value="' . csrfToken() . '">';
}

function verifyCsrf($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}