<?php
// Helper functions

function redirect($url) {
    session_write_close();
    while (ob_get_level()) {
        ob_end_clean();
    }
    header("Location: " . APP_URL . $url);
    exit;
}

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

function flash($key, $message = null) {
    if ($message) {
        $_SESSION['flash'][$key] = $message;
    } else {
        $msg = $_SESSION['flash'][$key] ?? null;
        unset($_SESSION['flash'][$key]);
        return $msg;
    }
}

function formatMoney($amount) {
    return number_format($amount, 2, ',', ' ') . ' MAD';
}

function formatDate($date) {
    if (!$date) return '';
    return date('d/m/Y', strtotime($date));
}

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

function generateReference($prefix = 'REF') {
    return $prefix . '-' . date('Y') . '-' . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

function uploadFile($file, $directory, $allowedTypes = ['jpg','jpeg','png','pdf','doc','docx']) {
    if ($file['error'] !== UPLOAD_ERR_OK) return false;
    
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedTypes)) return false;
    
    $filename = uniqid() . '_' . time() . '.' . $ext;
    $destination = $directory . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $destination)) {
        return $filename;
    }
    return false;
}

function getStatusBadge($status) {
    $badges = [
        'actif' => 'bg-success',
        'inactif' => 'bg-secondary',
        'en_cours' => 'bg-primary',
        'termine' => 'bg-info',
        'annule' => 'bg-danger',
        'en_attente' => 'bg-warning text-dark',
        'confirme' => 'bg-success',
        'refuse' => 'bg-danger',
        'paye' => 'bg-success',
        'partiel' => 'bg-warning text-dark',
        'impaye' => 'bg-danger',
    ];
    $class = $badges[$status] ?? 'bg-secondary';
    $label = ucfirst(str_replace('_', ' ', $status));
    return "<span class='badge {$class}'>{$label}</span>";
}

function getDB() {
    return Database::getInstance()->getConnection();
}

function paginate($total, $perPage = 15, $currentPage = 1) {
    $totalPages = ceil($total / $perPage);
    $currentPage = max(1, min($currentPage, $totalPages));
    $offset = ($currentPage - 1) * $perPage;
    return [
        'total' => $total,
        'per_page' => $perPage,
        'current_page' => $currentPage,
        'total_pages' => $totalPages,
        'offset' => $offset,
    ];
}

function renderPagination($pagination, $baseUrl) {
    if ($pagination['total_pages'] <= 1) return '';
    $html = '<nav><ul class="pagination pagination-sm justify-content-center">';
    
    if ($pagination['current_page'] > 1) {
        $html .= '<li class="page-item"><a class="page-link" href="'.$baseUrl.'&page='.($pagination['current_page']-1).'">«</a></li>';
    }
    
    for ($i = max(1, $pagination['current_page']-2); $i <= min($pagination['total_pages'], $pagination['current_page']+2); $i++) {
        $active = $i == $pagination['current_page'] ? 'active' : '';
        $html .= '<li class="page-item '.$active.'"><a class="page-link" href="'.$baseUrl.'&page='.$i.'">'.$i.'</a></li>';
    }
    
    if ($pagination['current_page'] < $pagination['total_pages']) {
        $html .= '<li class="page-item"><a class="page-link" href="'.$baseUrl.'&page='.($pagination['current_page']+1).'">»</a></li>';
    }
    
    $html .= '</ul></nav>';
    return $html;
}

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

function getAgencyInfo() {
    $db = getDB();
    $rows = $db->query("SELECT setting_key, setting_value FROM settings")->fetchAll();
    $info = [];
    foreach ($rows as $r) {
        $info[$r['setting_key']] = $r['setting_value'];
    }
    return $info;
}

function logAction($userId, $action, $details = '') {
    $db = getDB();
    $stmt = $db->prepare("INSERT INTO logs (user_id, action, details, ip_address, created_at) VALUES (?, ?, ?, ?, datetime('now'))");
    $stmt->execute([$userId, $action, $details, $_SERVER['REMOTE_ADDR'] ?? '']);
}
