<?php
include 'config/connexion.php';

// Récupérer le numéro de facture depuis l'URL
if (!isset($_GET['num']) || empty($_GET['num'])) {
    die("Numéro de facture non fourni.");
}

$facture_num = $_GET['num'];

// Récupérer les détails de la facture depuis facture_table avec le numéro de dossier client
$sql = "SELECT f.facture_num, f.facture_date, f.libelle, f.objet_assure, f.start_date, f.end_date, f.total, c.n_dossier, c.client_company, c.client_genre, c.client_adresse, c.client_ice, p.policy_type, p.policy_category, p.marque 
        FROM facture_table f
        LEFT JOIN policy_table p ON f.libelle = p.n_policy
        LEFT JOIN clients_table c ON p.client_cin = c.client_cin
        WHERE f.facture_num = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $facture_num);
$stmt->execute();
$result = $stmt->get_result();

$facture = $result->fetch_assoc();
$stmt->close();

if (!$facture) {
    die("Aucune donnée trouvée pour cette facture.");
}
// Récupérer les informations de la compagnie depuis la table compagnie_table
$sql_company = "SELECT compagnie_name, adresse, tel1, tel2, fax, whatsapp, mail_1, mail_2, mail_3, footer, logo, logo_format, facture_ref, facture_prefixe, facture_suffixe FROM compagnie_table LIMIT 1";
$result_company = $conn->query($sql_company);
$company_info = [];

if ($result_company && $row_company = $result_company->fetch_assoc()) {
    $company_info = [
        'name' => $row_company['compagnie_name'] ?? 'HIBA ASSURANCE',
        'address' => $row_company['adresse'] ?? 'N°8, AV. Allal El Fassi, IMM A, Opération Elboustane 2, Marrakech',
        'tel1' => $row_company['tel1'] ?? '',
        'tel2' => $row_company['tel2'] ?? '',
        'fax' => $row_company['fax'] ?? '',
        'whatsapp' => $row_company['whatsapp'] ?? '',
        'mail_1' => $row_company['mail_1'] ?? '',
        'mail_2' => $row_company['mail_2'] ?? '',
        'mail_3' => $row_company['mail_3'] ?? '',
        'footer' => $row_company['footer'] ?? '',
        'logo' => $row_company['logo'] ?? '',
        'logo_format' => $row_company['logo_format'] ?? 'wide',
        'facture_ref' => $row_company['facture_ref'] ?? '',
        'facture_prefixe' => $row_company['facture_prefixe'] ?? '',
        'facture_suffixe' => $row_company['facture_suffixe'] ?? ''
    ];
} else {
    // Valeurs par défaut si la table n'existe pas ou est vide
    $company_info = [
        'name' => '',
        'address' => '',
        'tel1' => '',
        'tel2' => '',
        'fax' => '',
        'whatsapp' => '',
        'mail_1' => '',
        'mail_2' => '',
        'mail_3' => '',
        'footer' => '',
        'logo' => '',
        'logo_format' => 'wide',
        'facture_ref' => '',
        'facture_prefixe' => '',
        'facture_suffixe' => ''
    ];
}

// Récupérer les informations du footer depuis la table compagnie_table
$footer_info = $company_info['footer'];

// Valeur par défaut si pas de footer dans la base
if (empty($footer_info)) {
    $footer_info = "Intermédiaire d'assurances régi par la loi 17-99.\nPortant code des assurances. Agrément N°C0000000 du 29 Décembre 2000.\nRC:0000-IF: 40708 ICE :0000000";
}

$total_ttc = floatval($facture['total']);

// Le numéro de facture est déjà formaté complet (préfixe + numéro + suffixe) lors de sa création
$facture_num_formatted = $facture['facture_num'];



// Fonction pour formater le nom de l'entreprise selon le genre
function formatClientName($client_company, $client_genre) {
    if (empty($client_company)) {
        return 'N/A';
    }
    
    switch (strtolower($client_genre)) {
        case 'mâle':
        case 'masculin':
        case 'm':
            return 'M. ' . $client_company;
        case 'femelle':
        case 'feminin':
        case 'f':
            return 'Mme ' . $client_company;
        case 'personne morale':
        case 'morale':
        case 'societe':
            return 'STE ' . $client_company;
        default:
            return $client_company;
    }
}

$nom_client_formate = formatClientName($facture['client_company'], $facture['client_genre']);

// Fonction pour convertir un montant en lettres
function convertirEnLettres($montant) {
    $formatter = new NumberFormatter("fr", NumberFormatter::SPELLOUT);
    $dirhams = floor($montant);
    $centimes = round(($montant - $dirhams) * 100);

    $montantEnLettres = ucfirst($formatter->format($dirhams)) . " dirhams";
    if ($centimes > 0) {
        $montantEnLettres .= " et " . $formatter->format($centimes) . " centimes";
    }

    return $montantEnLettres;
}

$montant_en_lettres = convertirEnLettres($total_ttc);
?>
<!DOCTYPE html>
<html lang="en">

<head>
 <?php include('includes/head_facture.php'); ?>
 <link rel="stylesheet" href="css/style_facture.css" type="text/css" media="all" /> <style>
  @media print {
    .no-print {
    display: none !important;
  }
  
  /* Garder le footer original mais ajuster pour l'impression */
  footer {
    position: fixed !important;
    left: 0 !important;
    right: 0 !important;
    width: 100% !important;
    height: 200px;
    background-color: #f1f5f9 !important;
    text-align: center !important;
    font-size: 10px !important;
    color: #4b5563 !important;
    padding: 8px 0 !important;
    z-index: 1000 !important;
  }
  
  /* Réserver l'espace pour le footer */
  @page {
    margin-bottom: 1px !important;
  }
  
  /* Ajuster le contenu principal */
  body {
    padding-bottom: 50px !important;
  }
}
</style>
</head>

<body>
  <div>
    <div class="py-4">
      <div class="px-14 py-6">
        <table class="w-full border-collapse border-spacing-0">
          <tbody>            <tr>
              <td class="w-full align-top">
                <div>
                  <?php if (!empty($company_info['logo']) && file_exists($company_info['logo'])): ?>
                    <?php 
                    // Définir les dimensions selon le format
                    $logo_style = '';
                    if ($company_info['logo_format'] === 'square') {
                        $logo_style = 'max-width: 150px; max-height: 150px; object-fit: contain;';
                    } else {
                        $logo_style = 'max-width:auto ; max-height: 150px; object-fit: contain;';
                    }
                    ?>
                    <img src="<?php echo htmlspecialchars($company_info['logo']); ?>" 
                         style="<?php echo $logo_style; ?>" 
                         alt="Logo <?php echo htmlspecialchars($company_info['name']); ?>" />
                  <?php else: ?>
                    <!-- Logo par défaut ou placeholder si aucun logo configuré -->
                    <div style="width: 150px; height: 75px; border: 1px dashed #ccc; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #666;">
                      Logo
                    </div>
                  <?php endif; ?>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
                <div class="text-right font-bold">
                  <h1># Facture</h1>
                </div>
      </div>

      <div class="bg-slate-100 px-14 py-6 text-sm">
        <table class="w-full border-collapse border-spacing-0">
          <tbody>            <tr>              <td class="border-rw-1/2 align-top">
                <div class="text-sm text-neutral-600" style="width: 300px;">
                  <strong><h5><?php echo htmlspecialchars($company_info['name']); ?></h5></strong>
                  <i class="fa-solid fa-location-dot text-info"></i> : <?php echo htmlspecialchars($company_info['address']); ?><br>
                  
                  <?php if (!empty($company_info['tel1'])): ?>
                    <i class="fa-solid fa-phone text-info"></i> : <?php echo htmlspecialchars($company_info['tel1']); ?><br>
                  <?php endif; ?>
                  
                  <?php if (!empty($company_info['tel2'])): ?>
                    <i class="fa-solid fa-phone text-info"></i> : <?php echo htmlspecialchars($company_info['tel2']); ?><br>
                  <?php endif; ?>
                  
                  <?php if (!empty($company_info['fax'])): ?>
                    <i class="fa-solid fa-fax text-info"></i> : <?php echo htmlspecialchars($company_info['fax']); ?><br>
                  <?php endif; ?>                  <?php if (!empty($company_info['whatsapp'])): ?>
                    <i class="fa-brands fa-whatsapp text-info"></i> : <?php echo htmlspecialchars($company_info['whatsapp']); ?><br>
                  <?php endif; ?>
                  
                  <?php if (!empty($company_info['mail_1'])): ?>
                    <i class="fa-solid fa-envelope text-info"></i> : <?php echo htmlspecialchars($company_info['mail_1']); ?><br>
                  <?php endif; ?>
                  
                  <?php if (!empty($company_info['mail_2'])): ?>
                    <i class="fa-solid fa-envelope text-info"></i> : <?php echo htmlspecialchars($company_info['mail_2']); ?><br>
                  <?php endif; ?>
                  
                  <?php if (!empty($company_info['mail_3'])): ?>
                    <i class="fa-solid fa-envelope text-info"></i> : <?php echo htmlspecialchars($company_info['mail_3']); ?>
                  <?php endif; ?>
                </div>
              </td>              <td class="w-1/2 align-top text-right">
                <div class="text-sm text-neutral-600 text-justify">
                  <h5 style="font-weight: bold;">CLIENT</h5>
                                    <p class="text-justify">
                                        <strong><?php echo htmlspecialchars($nom_client_formate); ?></strong><br>
                                        <strong>Adresse:</strong> <?php echo htmlspecialchars($facture['client_adresse'] ?? 'N/A'); ?><?php if (!empty($facture['client_ice'])): ?><br>
                                        <strong>ICE:</strong> <?php echo htmlspecialchars($facture['client_ice']); ?><?php endif; ?><br>
                                        <strong>Intitulé:</strong> <?php echo htmlspecialchars($facture['policy_type'] ?? 'N/A'); ?>
                                    </p>
                </div>
              </td>
                        <td class="border-r pr-4">
                          <div>
                            <p class="whitespace-nowrap text-slate-400 text-right">Facture N</p>
                            <p class="whitespace-nowrap font-bold text-main text-right"><?php echo htmlspecialchars($facture_num_formatted); ?></p>
                          </div>
                        </td>   
                        <td class="pl-4">
                          <div>
                            <p class="whitespace-nowrap text-slate-400 text-right">Date</p>
                            <p class="whitespace-nowrap font-bold text-main text-right">
                                <?php echo htmlspecialchars(date('d/m/Y', strtotime($facture['facture_date']))); ?>
                            </p>
                          </div>
                        </td>                      
                        <td class="pl-4">
                          <div>
                            <p class="whitespace-nowrap text-slate-400 text-right">N° client </p>
                            <p class="whitespace-nowrap font-bold text-main text-right"><?php echo htmlspecialchars($facture['n_dossier'] ?? 'N/A'); ?></p>
                          </div>                        </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="px-14 py-10 text-sm text-neutral-700">
        <table class="w-full border-collapse border-spacing-0">
          <thead>
            <tr>
              <td class="border-b-2 border-main pb-3 pl-3 font-bold text-main text-center">LIBELLE</td>
              <td class="border-b-2 border-main pb-3 pl-2 font-bold text-main text-center">OBJET ASSURE</td>
              <td class="border-b-2 border-main pb-3 pl-2 text-right font-bold text-main text-center">DATE D'EFFET</td>
              <td class="border-b-2 border-main pb-3 pl-2 text-center font-bold text-main text-center">DATE D'ECHEANCE</td>
              <td class="border-b-2 border-main pb-3 pl-2 text-center font-bold text-main text-center">PRIME TOTAL (DH)</td>
            </tr>
          </thead>
          <tbody>            <tr>
              <td class="border-b py-3 pl-3 text-center">Police : <br><?php echo htmlspecialchars($facture['libelle']); ?></td>              <td class="border-b py-3 pl-2 text-center">
                <?php
                // Formatage de l'objet assuré comme l'immatriculation
                $immat = trim($facture['objet_assure']);
                // Si la catégorie de police est RD, afficher le type de police
                if (isset($facture['policy_category']) && preg_match('/^rd$/i', trim($facture['policy_category']))) {
                  echo htmlspecialchars($facture['policy_type']);
                } else {
                  $immat_parts = preg_split('/\s*-\s*/u', $immat);
                  if (count($immat_parts) === 3) {
                    $part1 = trim($immat_parts[2]);
                    $part2 = trim($immat_parts[1]);
                    $part3 = trim($immat_parts[0]);
                    echo $part3 . ' - ' . '<span dir="rtl" style="display:inline-block;">' . $part2 . '</span>' . ' - ' . $part1;
                  } else {
                    echo htmlspecialchars($immat);
                  }
                  // Afficher la marque si elle est disponible
                  if (!empty($facture['marque'])) {
                    echo '<br><small style="color: #666; font-style: italic;">' . htmlspecialchars($facture['marque']) . '</small>';
                  }
                }
                ?>
              </td>
              <td class="border-b py-3 pl-2 text-center"><?php echo htmlspecialchars(date('d/m/Y', strtotime($facture['start_date']))); ?></td>
              <td class="border-b py-3 pl-2 text-center"><?php echo htmlspecialchars(date('d/m/Y', strtotime($facture['end_date']))); ?></td>
              <td class="border-b py-3 pl-2 text-center"><?php echo number_format($facture['total'], 2, ',', ' '); ?> DH</td>
            </tr>
            <tr>
              <td colspan="7">
                <table class="w-full border-collapse border-spacing-0">
                  <tbody>
                    <tr>
                      <td class="w-full"></td>
                      <td>
                        <table class="w-full border-collapse border-spacing-0">
                          <tbody><br>
                            <tr>
                              <td class="bg-main p-3">
                                <div class="whitespace-nowrap font-bold text-white">Total TTC :</div>
                              </td>
                              <td class="bg-main p-3 text-right">
                                <div class="whitespace-nowrap font-bold text-white"><?php echo number_format($total_ttc, 2, ',', ' '); ?> DH</div>
                              </td>
                            </tr>
                          </tbody>
                        </table>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="no-print text-center mt-4">
        <button onclick="window.print()" class="btn btn-primary">
          <i class="fas fa-print"></i> Imprimer la facture
        </button>
      </div>      <div class="px-14 text-sm text-neutral-700">
        <p class="text-main font-bold">Arrêtée la présente facture à la somme de : </p>
        <p><strong><?php echo htmlspecialchars($montant_en_lettres); ?></strong>.</p>
      </div>      
      <footer class="fixed bottom-0 left-0 bg-slate-100 w-full text-neutral-600 text-center text-xs py-3">
        <?php        // Affichage du footer dynamique
        if (!empty($footer_info)) {
            // Convertir tous les types de retours à la ligne possibles
            $footer_display = $footer_info;
            
            // Convertir tous les types de retours à la ligne possibles
            $footer_display = str_replace('\\n', "\n", $footer_display);  // \n littéraux
            $footer_display = str_replace('\n', "\n", $footer_display);   // \n échappés
            $footer_display = str_replace('&#10;', "\n", $footer_display); // HTML entities
            
            // Séparer les lignes
            $footer_lines = explode("\n", $footer_display);
            
            foreach ($footer_lines as $index => $line) {
                $line = trim($line);
                if (!empty($line)) {
                    echo '<p style="margin: 2px 0; text-align: center; line-height: 1.2;">' . htmlspecialchars($line) . '</p>';
                }
            }
        } else {
            // Fallback si pas de footer dans la DB
            echo '<p style="margin: 2px 0; text-align: center;">Intermédiaire d\'assurances régi par la loi 17-99.</p>';
            echo '<p style="margin: 2px 0; text-align: center;">Portant code des assurances. Agrément N°C265352011450 du 29 Décembre 2000.</p>';
            echo '<p style="margin: 2px 0; text-align: center;">RC: 443-IF: 40708 ICE :0002200001</p>';
        }
        ?>
      </footer>
    </div>
  </div>
  <script src="vendor/jquery/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
  <script src="js/ruang-admin.min.js"></script>
</body>
</html>
