<?php
// ============================================================
// includes/functions.php — دوال مساعدة عامة
// ============================================================

function sanitize(string $val): string {
    return htmlspecialchars(trim($val), ENT_QUOTES, 'UTF-8');
}

function generateCaseNumber(): string {
    $year = date('Y');
    $pdo  = db();
    $cnt  = $pdo->query("SELECT COUNT(*) FROM cases WHERE YEAR(created_at) = $year")->fetchColumn();
    return sprintf('QD-%s-%04d', $year, (int)$cnt + 1);
}

function uploadFile(array $file, string $subfolder = 'docs'): array {
    $dir = UPLOAD_PATH . $subfolder . '/';
    if (!is_dir($dir)) mkdir($dir, 0755, true);

    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ALLOWED_EXT, true)) {
        return ['success' => false, 'message' => 'امتداد الملف غير مسموح'];
    }
    if ($file['size'] > MAX_FILE_SIZE) {
        return ['success' => false, 'message' => 'حجم الملف يتجاوز 5 ميغا'];
    }

    $name = uniqid('file_', true) . '.' . $ext;
    if (move_uploaded_file($file['tmp_name'], $dir . $name)) {
        return ['success' => true, 'path' => $subfolder . '/' . $name];
    }
    return ['success' => false, 'message' => 'فشل رفع الملف'];
}

function createNotification(int $userId, string $type, string $title, string $message, ?string $link = null): void {
    try {
        db()->prepare('INSERT INTO notifications (user_id, type, title, message, link) VALUES (?,?,?,?,?)')
            ->execute([$userId, $type, $title, $message, $link]);
    } catch (\Exception $e) {
        error_log('Notification error: ' . $e->getMessage());
    }
}

function getUnreadNotifCount(int $userId): int {
    return (int) db()->prepare('SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0')
        ->execute([$userId]) && false ?: (function() use ($userId) {
            $s = db()->prepare('SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0');
            $s->execute([$userId]);
            return (int)$s->fetchColumn();
        })();
}

function getNotifications(int $userId, int $limit = 10): array {
    $s = db()->prepare('SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT ?');
    $s->execute([$userId, $limit]);
    return $s->fetchAll();
}

function formatDate(?string $date, bool $time = false): string {
    if (!$date) return '—';
    $ts  = strtotime($date);
    $fmt = $time ? 'd/m/Y H:i' : 'd/m/Y';
    return date($fmt, $ts);
}

function badgeHtml(string $text, string $class): string {
    return "<span class='badge bg-{$class}'>{$text}</span>";
}

function caseStatusBadge(string $status): string {
    $map = CASE_STATUS;
    $info = $map[$status] ?? ['label' => $status, 'class' => 'secondary'];
    return badgeHtml($info['label'], $info['class']);
}

function paginate(int $total, int $perPage, int $current): array {
    $pages     = (int) ceil($total / $perPage);
    $offset    = ($current - 1) * $perPage;
    return ['total' => $total, 'pages' => $pages, 'current' => $current, 'offset' => $offset, 'per_page' => $perPage];
}
