<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Librairie Notification_mail
 * Envoi des rapports PDF par email
 * 
 * Fichier: application/libraries/Notification_mail.php
 */
class Notification_mail {
    
    protected $CI;
    
    // Configuration expéditeur
    protected $from_email = 'agbessijoel@gmail.com';
    protected $from_name = 'YAMEELA - Service Maritime';
    
    // =============================================
    // LISTE DES DESTINATAIRES - MODIFIER ICI UNIQUEMENT
    // =============================================
    protected $destinataires = array(
        'liste_passagers' => array(
            'agbessijoel@gmail.com',
            'wassimserviceswassim@gmail.com',
            'omarsoidik@yahoo.fr',
            'adel.ofaissah@gmail.com',
            'MV.Yameela@safeen.ae',
            'abdoulmouhsin05@gmail.com'
        ),
        'manifest' => array(
            'agbessijoel@gmail.com',
            'wassimserviceswassim@gmail.com',
            'adel.ofaissah@gmail.com',
            'omarsoidik@yahoo.fr',
            'MV.Yameela@safeen.ae',
            'abdoulmouhsin05@gmail.com'
        ),
        'recette' => array(
            'agbessijoel@gmail.com',
            'wassimserviceswassim@gmail.com',
            'soilhoud@gmail.com',
            'omarsoidik@yahoo.fr',
            'hichamsoilihi@live.fr',
            'thani.moina@gmail.com'

        ),
        'rapport_caisse' => array(
            'agbessijoel@gmail.com',
            'wassimserviceswassim@gmail.com',
            'soilhoud@gmail.com',
            'omarsoidik@yahoo.fr',
            'hichamsoilihi@live.fr',
            'thani.moina@gmail.com'
        )
    );
    
    public function __construct() {
        $this->CI =& get_instance();
        $this->CI->load->library('email');
        
      
        // Configuration email
        $config = array(
            'protocol'    => 'smtp',
            'smtp_host'   => 'smtp.gmail.com',  // À configurer
            'smtp_port'   => 465,
            'smtp_user'   => 'agbessijoel@gmail.com',                 // À configurer
            'smtp_pass'   => 'cikq iole iswb yxey',                 // À configurer
            'smtp_crypto' => 'ssl',
            'mailtype'    => 'html',
            'charset'     => 'utf-8',
            'newline'     => "\r\n",
            'crlf'        => "\r\n"
        );
        
        $this->CI->email->initialize($config);
    }
    
    /**
     * Obtenir les destinataires par type
     */
    public function get_destinataires($type = null) {
        if ($type) {
            return isset($this->destinataires[$type]) ? $this->destinataires[$type] : array();
        }
        return $this->destinataires;
    }
    
    /**
     * Envoyer le PDF de la liste des passagers
     */
    public function envoyer_liste_passagers_pdf($voyage, $pdf_path) {
        $subject = "Liste Passagers Voyage {$voyage->numero_voyage} - " . date('d/m/Y', strtotime($voyage->date_voyage));
        $message = $this->get_template('liste_passagers', $voyage);
        return $this->envoyer_multiple('liste_passagers', $subject, $message, $pdf_path);
    }
    
    /**
     * Envoyer le PDF du manifeste
     */
    public function envoyer_manifest_pdf($voyage, $pdf_path) {
        $subject = "Manifeste Voyage {$voyage->numero_voyage} - " . date('d/m/Y', strtotime($voyage->date_voyage));
        $message = $this->get_template('manifest', $voyage);
        return $this->envoyer_multiple('manifest', $subject, $message, $pdf_path);
    }
    
    /**
     * Envoyer le PDF des recettes
     */
    public function envoyer_recette_pdf($voyage, $pdf_path) {
        $subject = "Recettes Voyage {$voyage->numero_voyage} - " . date('d/m/Y', strtotime($voyage->date_voyage));
        $message = $this->get_template('recette', $voyage);
        return $this->envoyer_multiple('recette', $subject, $message, $pdf_path);
    }
    /**
     * Envoyer le PDF du rapport de caisse
     */
    public function envoyer_rapport_caisse_pdf($session, $pdf_path) {
        $subject = "Rapport Caisse - Session {$session->numero_session} - " . date('d/m/Y', strtotime($session->date_fermeture));
        $message = $this->get_template_caisse($session);
        return $this->envoyer_multiple('rapport_caisse', $subject, $message, $pdf_path);
    }
    
    /**
     * Template HTML pour rapport de caisse
     */
    private function get_template_caisse($session) {
        $ecart_class = $session->ecart_fermeture == 0 ? 'green' : ($session->ecart_fermeture > 0 ? 'blue' : 'red');
        
        return "
        <div style='font-family: Arial, sans-serif;'>
            <h2>Rapport de Caisse</h2>
            <p><strong>Session:</strong> {$session->numero_session}</p>
            <p><strong>Caissier:</strong> {$session->caissier_nom} {$session->caissier_prenom}</p>
            <p><strong>Date fermeture:</strong> " . date('d/m/Y H:i', strtotime($session->date_fermeture)) . "</p>
            <hr>
            <table style='width:100%; border-collapse: collapse;'>
                <tr><td style='padding:5px;'>Fonds ouverture:</td><td style='text-align:right;'>" . number_format($session->montant_ouverture_declare, 0, ',', ' ') . " KMF</td></tr>
                <tr><td style='padding:5px;'>Encaissements:</td><td style='text-align:right;'>" . number_format($session->total_encaissements, 0, ',', ' ') . " KMF</td></tr>
                <tr><td style='padding:5px;'>Remboursements:</td><td style='text-align:right;'>" . number_format($session->total_remboursements, 0, ',', ' ') . " KMF</td></tr>
                <tr style='font-weight:bold;'><td style='padding:5px;'>Theorique:</td><td style='text-align:right;'>" . number_format($session->montant_fermeture_theorique, 0, ',', ' ') . " KMF</td></tr>
                <tr style='font-weight:bold;'><td style='padding:5px;'>Declare:</td><td style='text-align:right;'>" . number_format($session->montant_fermeture_declare, 0, ',', ' ') . " KMF</td></tr>
                <tr style='font-weight:bold; color:{$ecart_class};'><td style='padding:5px;'>Ecart:</td><td style='text-align:right;'>" . number_format($session->ecart_fermeture, 0, ',', ' ') . " KMF</td></tr>
            </table>
            <hr>
            <p>Veuillez trouver le rapport detaille en piece jointe.</p>
            <small>YAMEELA - Service Maritime des Comores</small>
        </div>";
    }
    
    
    /**
     * Template HTML du message
     */
    private function get_template($type, $voyage) {
        $titres = array(
            'liste_passagers' => 'Liste des Passagers',
            'manifest' => 'Manifeste Officiel',
            'recette' => 'Rapport des Recettes'
        );
        
        return "
        <div style='font-family: Arial, sans-serif;'>
            <h2>{$titres[$type]}</h2>
            <p><strong>Voyage:</strong> {$voyage->numero_voyage}</p>
            <p><strong>Date:</strong> " . date('d/m/Y', strtotime($voyage->date_voyage)) . "</p>
            <p><strong>Trajet:</strong> {$voyage->port_depart} → {$voyage->port_arrivee}</p>
            <p>Veuillez trouver le document en pièce jointe.</p>
            <hr>
            <small>YAMEELA - Service Maritime des Comores</small>
        </div>";
    }
    
    /**
     * Envoyer à tous les destinataires d'un type
     */
    private function envoyer_multiple($type, $subject, $message, $attachment) {
        $emails = $this->get_destinataires($type);
        
        $result = array(
            'success' => 0,
            'failed' => 0,
            'total' => count($emails)
        );
        
        foreach ($emails as $email) {
            if ($this->envoyer($email, $subject, $message, $attachment)) {
                $result['success']++;
            } else {
                $result['failed']++;
            }
        }
        
        return $result;
    }
    
    /**
     * Envoi d'un email
     */
    private function envoyer($to, $subject, $message, $attachment = null) {
        $this->CI->email->clear(true);
        $this->CI->email->from($this->from_email, $this->from_name);
        $this->CI->email->to($to);
        $this->CI->email->subject($subject);
        $this->CI->email->message($message);
        
        if ($attachment && file_exists($attachment)) {
            $this->CI->email->attach($attachment);
        }
        
        return $this->CI->email->send();
    }
}