<?php
// =============================================
// HELPERS SYSTÈME MARITIME - maritime_helper.php
// Fonctions utilitaires pour le système maritime
// =============================================

if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Obtenir la couleur Bootstrap selon le rôle utilisateur
 */
if (!function_exists('get_role_color')) {
    function get_role_color($role) {
        $colors = array(
            'admin' => 'danger',
            'planificateur' => 'primary',
            'agent_reservation' => 'success', 
            'caissier' => 'warning',
            'agent_embarquement' => 'info'
        );
        return isset($colors[$role]) ? $colors[$role] : 'secondary';
    }
}

/**
 * Obtenir l'icône Bootstrap Icons selon le rôle
 */
if (!function_exists('get_role_icon')) {
    function get_role_icon($role) {
        $icons = array(
            'admin' => 'shield-check',
            'planificateur' => 'calendar-event',
            'agent_reservation' => 'person-check',
            'caissier' => 'cash-stack',
            'agent_embarquement' => 'airplane-engines'
        );
        return isset($icons[$role]) ? $icons[$role] : 'person';
    }
}

/**
 * Formater numéro téléphone comorien
 */
if (!function_exists('format_phone_km')) {
    function format_phone_km($phone) {
        if (empty($phone)) return '';
        
        // Nettoyer le numéro
        $phone = preg_replace('/[^0-9+]/', '', $phone);
        
        // Format comorien standard
        if (strlen($phone) === 7 && !strpos($phone, '+')) {
            return '+269 ' . substr($phone, 0, 2) . ' ' . substr($phone, 2, 2) . ' ' . substr($phone, 4);
        }
        
        return $phone;
    }
}

/**
 * Formater montant en Francs Comoriens
 */
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        if (is_null($amount) || $amount === '') return '0 FC';
        return number_format($amount, 0, ',', ' ') . ' FC';
    }
}

/**
 * Calculer l'âge à partir de la date de naissance
 */
if (!function_exists('calculate_age')) {
    function calculate_age($birth_date) {
        if (empty($birth_date)) return 0;
        
        $birth = new DateTime($birth_date);
        $today = new DateTime();
        return $birth->diff($today)->y;
    }
}

/**
 * Formater la durée entre deux heures
 */
if (!function_exists('format_duration')) {
    function format_duration($start_time, $end_time) {
        if (empty($start_time) || empty($end_time)) return '-';
        
        $start = new DateTime($start_time);
        $end = new DateTime($end_time);
        $diff = $start->diff($end);
        
        $hours = $diff->h;
        $minutes = $diff->i;
        
        if ($hours > 0) {
            return $hours . 'h' . ($minutes > 0 ? ' ' . $minutes . 'min' : '');
        }
        
        return $minutes . 'min';
    }
}

/**
 * Calculer durée session de caisse
 */
if (!function_exists('calculate_session_duration')) {
    function calculate_session_duration($start_datetime) {
        if (empty($start_datetime)) return '0h 0min';
        
        $start = new DateTime($start_datetime);
        $now = new DateTime();
        $diff = $start->diff($now);
        
        $hours = $diff->h + ($diff->days * 24);
        $minutes = $diff->i;
        
        return $hours . 'h ' . $minutes . 'min';
    }
}

/**
 * Obtenir badge de statut avec couleur
 */
if (!function_exists('get_status_badge')) {
    function get_status_badge($status, $type = 'general') {
        $status = strtoupper($status);
        
        $badges = array(
            'general' => array(
                'ACTIF' => '<span class="badge bg-success"><i class="bi bi-check-circle"></i> Actif</span>',
                'INACTIF' => '<span class="badge bg-danger"><i class="bi bi-x-circle"></i> Inactif</span>',
                'ACTIVE' => '<span class="badge bg-success"><i class="bi bi-check-circle"></i> Active</span>',
                'ANNULEE' => '<span class="badge bg-danger"><i class="bi bi-x-circle"></i> Annulée</span>'
            ),
            'voyage' => array(
                'PROGRAMME' => '<span class="badge bg-primary"><i class="bi bi-calendar-plus"></i> Programmé</span>',
                'EN_COURS' => '<span class="badge bg-warning"><i class="bi bi-play-circle"></i> En cours</span>',
                'TERMINE' => '<span class="badge bg-success"><i class="bi bi-check-all"></i> Terminé</span>',
                'ANNULE' => '<span class="badge bg-danger"><i class="bi bi-x-circle"></i> Annulé</span>',
                'REPORTE' => '<span class="badge bg-secondary"><i class="bi bi-clock"></i> Reporté</span>'
            ),
            'ferry' => array(
                'ACTIF' => '<span class="badge bg-success"><i class="bi bi-check-circle"></i> Actif</span>',
                'MAINTENANCE' => '<span class="badge bg-warning"><i class="bi bi-tools"></i> Maintenance</span>',
                'HORS_SERVICE' => '<span class="badge bg-danger"><i class="bi bi-x-circle"></i> Hors Service</span>',
                'INSPECTION' => '<span class="badge bg-info"><i class="bi bi-search"></i> Inspection</span>'
            ),
            'reservation' => array(
                'ACTIVE' => '<span class="badge bg-success"><i class="bi bi-check-circle"></i> Active</span>',
                'ANNULEE' => '<span class="badge bg-danger"><i class="bi bi-x-circle"></i> Annulée</span>',
                'MODIFIEE' => '<span class="badge bg-warning"><i class="bi bi-pencil"></i> Modifiée</span>',
                'EXPIREE' => '<span class="badge bg-secondary"><i class="bi bi-clock"></i> Expirée</span>'
            ),
            'billet' => array(
                'EMIS' => '<span class="badge bg-secondary"><i class="bi bi-ticket"></i> Émis</span>',
                'PAYE' => '<span class="badge bg-success"><i class="bi bi-cash"></i> Payé</span>',
                'ENREGISTRE' => '<span class="badge bg-info"><i class="bi bi-check-square"></i> Enregistré</span>',
                'EMBARQUE' => '<span class="badge bg-primary"><i class="bi bi-airplane-engines"></i> Embarqué</span>',
                'ANNULE' => '<span class="badge bg-danger"><i class="bi bi-x-circle"></i> Annulé</span>',
                'REMBOURSE' => '<span class="badge bg-warning"><i class="bi bi-arrow-counterclockwise"></i> Remboursé</span>'
            )
        );
        
        if (isset($badges[$type][$status])) {
            return $badges[$type][$status];
        }
        
        // Statut générique par défaut
        return '<span class="badge bg-secondary">' . ucfirst(strtolower($status)) . '</span>';
    }
}

/**
 * Obtenir icône selon type de véhicule
 */
if (!function_exists('get_vehicle_icon')) {
    function get_vehicle_icon($type) {
        $icons = array(
            'moto' => 'bicycle',
            'leger' => 'car-front',
            'cargo' => 'truck',
            'bus' => 'bus-front',
            'camion' => 'truck-front-fill'
        );
        
        return isset($icons[$type]) ? $icons[$type] : 'car-front';
    }
}

/**
 * Générer code de réservation unique
 */
if (!function_exists('generate_reservation_code')) {
    function generate_reservation_code($port_depart = '') {
        $prefix = '';
        
        switch($port_depart) {
            case 'MORONI':
                $prefix = 'MOR';
                break;
            case 'MUTSAMUDU':
                $prefix = 'MUT';
                break;
            case 'FOMBONI':
                $prefix = 'FOM';
                break;
            default:
                $prefix = 'MAR'; // Maritime générique
        }
        
        // Format: PREFIX + YYMMDD + nombre aléatoire 3 chiffres
        return $prefix . date('ymd') . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
    }
}

/**
 * Générer numéro de billet unique
 */
/*if (!function_exists('generate_ticket_number')) {
    function generate_ticket_number($voyage_id = null) {
        // Format: BIL + YYYYMMDD + ID voyage (2 chiffres) + nombre aléatoire
        $voyage_part = $voyage_id ? str_pad($voyage_id, 2, '0', STR_PAD_LEFT) : '00';
        return 'BIL' . date('Ymd') . $voyage_part . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
    }
}*/

// Dans application/helpers/maritime_helper.php
// Remplacer la fonction generate_ticket_number par :

if (!function_exists('generate_ticket_number')) {
    function generate_ticket_number($voyage_id = null) {
        $CI =& get_instance();
        
        // Vérifier que la table existe et obtenir le prochain numéro
        $CI->db->select('COUNT(*) as count');
        $CI->db->where('DATE(date_emission)', date('Y-m-d'));
        if ($voyage_id) {
            $CI->db->where('voyage_id', $voyage_id);
        }
        $count = $CI->db->get('billets')->row()->count;
        
        $date_part = date('Ymd');
        $voyage_part = $voyage_id ? str_pad($voyage_id, 2, '0', STR_PAD_LEFT) : '00';
        $sequence = str_pad($count + 1, 4, '0', STR_PAD_LEFT);
        $random = str_pad(rand(10, 99), 2, '0', STR_PAD_LEFT);
        
        return 'BIL' . $date_part . $voyage_part . $sequence . $random;
    }
}

/**
 * Générer numéro de voyage
 */
if (!function_exists('generate_voyage_number')) {
    function generate_voyage_number($ferry_id, $date) {
        // Format: Ferry ID + Date MMDD + Séquence
        $date_part = date('md', strtotime($date));
        $ferry_part = str_pad($ferry_id, 2, '0', STR_PAD_LEFT);
        $sequence = rand(1, 99);
        
        return 'V' . $ferry_part . $date_part . str_pad($sequence, 2, '0', STR_PAD_LEFT);
    }
}

/**
 * Valider numéro de téléphone comorien
 */
if (!function_exists('is_valid_phone_km')) {
    function is_valid_phone_km($phone) {
        if (empty($phone)) return true; // Optionnel
        
        // Nettoyer
        $clean = preg_replace('/[^0-9+]/', '', $phone);
        
        // Formats acceptés:
        // +269XXXXXXX (10 chiffres après +269)
        // 77XXXXX, 32XXXXX, etc. (7 chiffres commençant par préfixe mobile/fixe)
        if (preg_match('/^\+269[0-9]{7}$/', $clean) || preg_match('/^[0-9]{7}$/', $clean)) {
            return true;
        }
        
        return false;
    }
}

/**
 * Obtenir les ports comoriens
 */
if (!function_exists('get_ports')) {
    function get_ports() {
        return array(
            'MORONI' => 'Moroni (Grande Comore)',
            'MUTSAMUDU' => 'Mutsamudu (Anjouan)',
            'FOMBONI' => 'Fomboni (Mohéli)',
            'DOMONI' => 'Domoni (Anjouan)',
            'OUANI' => 'Ouani (Anjouan)'
        );
    }
}

/**
 * Formater nom propre (capitalisation)
 */
if (!function_exists('format_proper_name')) {
    function format_proper_name($name) {
        if (empty($name)) return '';
        
        // Convertir en majuscules pour les noms comoriens
        return strtoupper(trim($name));
    }
}

/**
 * Générer QR Code pour billet
 */
if (!function_exists('generate_qr_code')) {
    function generate_qr_code($data) {
        // Encoder les données du billet pour QR code
        return base64_encode($data . '|' . time());
    }
}

/**
 * Vérifier permissions utilisateur
 */
if (!function_exists('user_can')) {
    function user_can($required_role, $user_role = null) {
        $CI =& get_instance();
        
        if (!$user_role) {
            $user_role = $CI->session->userdata('role');
        }
        
        // Hiérarchie des rôles
        $hierarchy = array(
            'admin' => 5,
            'planificateur' => 4,
            'agent_reservation' => 3,
            'caissier' => 3,
            'agent_embarquement' => 2
        );
        
        $user_level = isset($hierarchy[$user_role]) ? $hierarchy[$user_role] : 0;
        $required_level = isset($hierarchy[$required_role]) ? $hierarchy[$required_role] : 1;
        
        return $user_level >= $required_level;
    }
}

/**
 * Logger les actions utilisateur
 */
if (!function_exists('log_user_action')) {
    function log_user_action($action, $details = '') {
        $CI =& get_instance();
        
        $log_data = array(
            'user_id' => $CI->session->userdata('user_id'),
            'username' => $CI->session->userdata('username'),
            'action' => $action,
            'details' => $details,
            'ip_address' => $CI->input->ip_address(),
            'user_agent' => $CI->input->user_agent(),
            'timestamp' => date('Y-m-d H:i:s')
        );
        
        // Sauvegarder en base si table existe
        if ($CI->db->table_exists('user_logs')) {
            $CI->db->insert('user_logs', $log_data);
        }
        
        // Log fichier
        log_message('info', 'User Action: ' . $action . ' by ' . $log_data['username']);
    }
}

/**
 * Nettoyer string pour URL
 */
if (!function_exists('clean_string')) {
    function clean_string($string) {
        $string = strtolower($string);
        $string = preg_replace('/[^a-z0-9]/', '_', $string);
        $string = preg_replace('/_+/', '_', $string);
        return trim($string, '_');
    }
}

/**
 * Vérifier si c'est un jour ouvrable
 */
if (!function_exists('is_working_day')) {
    function is_working_day($date = null) {
        $date = $date ?: date('Y-m-d');
        $day_of_week = date('N', strtotime($date));
        
        // Lundi = 1, Dimanche = 7
        // Aux Comores, généralement travail du Dimanche au Jeudi
        return in_array($day_of_week, array(7, 1, 2, 3, 4)); // Dim-Jeu
    }
}
?>