<?php
/**
 * Funciones de utilidad del sistema
 * Turpial Airlines, C.A.
 */

// Iniciar sesión si no está iniciada
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

/**
 * Verificar si el usuario está logueado
 */
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

/**
 * Verificar permisos de usuario
 */
function hasPermission($required_role_id) {
    if (!isLoggedIn()) {
        return false;
    }
    return $_SESSION['role_id'] <= $required_role_id;
}

/**
 * Redireccionar si no está logueado
 */
function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: login.php');
        exit;
    }
}

/**
 * Redireccionar si no tiene permisos
 */
function requirePermission($required_role_id) {
    requireLogin();
    if (!hasPermission($required_role_id)) {
        header('Location: dashboard.php?error=no_permission');
        exit;
    }
}

/**
 * Escapar HTML
 */
function escape($string) {
    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}

/**
 * Formatear fecha
 */
function formatDate($date, $format = 'd/m/Y') {
    if (empty($date)) return '-';
    return date($format, strtotime($date));
}

/**
 * Formatear fecha y hora
 */
function formatDateTime($datetime, $format = 'd/m/Y H:i') {
    if (empty($datetime)) return '-';
    return date($format, strtotime($datetime));
}

/**
 * Generar token CSRF
 */
function generateCSRFToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

/**
 * Verificar token CSRF
 */
function verifyCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * Subir archivo
 */
function uploadFile($file, $allowed_types = ['pdf', 'doc', 'docx'], $max_size = 5242880) {
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return ['success' => false, 'message' => 'Error al subir el archivo'];
    }
    
    if ($file['size'] > $max_size) {
        return ['success' => false, 'message' => 'El archivo es demasiado grande'];
    }
    
    $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    
    if (!in_array($file_extension, $allowed_types)) {
        return ['success' => false, 'message' => 'Tipo de archivo no permitido'];
    }
    
    $upload_dir = '../uploads/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }
    
    $filename = uniqid() . '_' . time() . '.' . $file_extension;
    $filepath = $upload_dir . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return [
            'success' => true,
            'filename' => $filename,
            'original_name' => $file['name'],
            'path' => $filepath
        ];
    }
    
    return ['success' => false, 'message' => 'Error al guardar el archivo'];
}

/**
 * Validar email
 */
function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

/**
 * Limpiar string
 */
function cleanString($string) {
    return trim(strip_tags($string));
}

/**
 * Generar slug
 */
function generateSlug($string) {
    $string = strtolower($string);
    $string = preg_replace('/[^a-z0-9\s]/', '', $string);
    $string = preg_replace('/\s+/', '-', $string);
    return trim($string, '-');
}

/**
 * Mostrar alertas
 */
function showAlert($message, $type = 'info') {
    $class = '';
    switch ($type) {
        case 'success':
            $class = 'alert-success';
            break;
        case 'error':
        case 'danger':
            $class = 'alert-danger';
            break;
        case 'warning':
            $class = 'alert-warning';
            break;
        default:
            $class = 'alert-info';
    }
    
    return "<div class='alert $class alert-dismissible fade show' role='alert'>
                $message
                <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
            </div>";
}

/**
 * Paginación
 */
function paginate($total_records, $records_per_page, $current_page, $base_url) {
    $total_pages = ceil($total_records / $records_per_page);
    
    if ($total_pages <= 1) {
        return '';
    }
    
    $pagination = '<nav aria-label="Paginación"><ul class="pagination justify-content-center">';
    
    // Botón anterior
    if ($current_page > 1) {
        $prev_page = $current_page - 1;
        $pagination .= "<li class='page-item'><a class='page-link' href='$base_url?page=$prev_page'>Anterior</a></li>";
    }
    
    // Números de página
    for ($i = 1; $i <= $total_pages; $i++) {
        $active = ($i == $current_page) ? 'active' : '';
        $pagination .= "<li class='page-item $active'><a class='page-link' href='$base_url?page=$i'>$i</a></li>";
    }
    
    // Botón siguiente
    if ($current_page < $total_pages) {
        $next_page = $current_page + 1;
        $pagination .= "<li class='page-item'><a class='page-link' href='$base_url?page=$next_page'>Siguiente</a></li>";
    }
    
    $pagination .= '</ul></nav>';
    
    return $pagination;
}

/**
 * Truncar texto
 */
function truncateText($text, $length = 100, $suffix = '...') {
    if (strlen($text) <= $length) {
        return $text;
    }
    
    return substr($text, 0, $length) . $suffix;
}

/**
 * Convertir array a opciones de select
 */
function arrayToOptions($array, $value_key, $text_key, $selected_value = null) {
    $options = '';
    foreach ($array as $item) {
        $selected = ($item[$value_key] == $selected_value) ? 'selected' : '';
        $options .= "<option value='{$item[$value_key]}' $selected>{$item[$text_key]}</option>";
    }
    return $options;
}

/**
 * Obtener configuración
 */
function getSetting($key, $default = null) {
    static $settings = null;
    
    if ($settings === null) {
        try {
            $db = new Database();
            $result = $db->fetchAll("SELECT setting_key, setting_value FROM settings");
            $settings = [];
            foreach ($result as $row) {
                $settings[$row['setting_key']] = $row['setting_value'];
            }
        } catch (Exception $e) {
            $settings = [];
        }
    }
    
    return isset($settings[$key]) ? $settings[$key] : $default;
}

?>