<!DOCTYPE html>
<html lang="en">
<head>
  <?php include('includes/head.php'); ?>
</head>
<body id="page-top">
  <div id="wrapper">
    <!-- Sidebar -->
    <?php include('includes/sidebar.php'); ?>
    <!-- Sidebar -->
    <div id="content-wrapper" class="d-flex flex-column">
      <div id="content">
        <!-- TopBar -->
        <?php include('includes/topbar.php'); ?>
        <!-- Topbar -->

        <!-- Container Fluid-->
        <div class="container-fluid" id="container-wrapper">
          <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">Table des Polices</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item">Tableaux</li>
              <li class="breadcrumb-item active" aria-current="page">Table des Polices</li>
            </ol>
          </div>

          <!-- Policies Table -->
          <div class="card mb-4">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
              <h6 class="m-0 font-weight-bold text-primary">Polices</h6>
            </div>
            <div class="table-responsive p-3">
              <table class="table align-items-center table-flush" id="dataTable">
                <thead class="thead-light">
                  <tr>
                    <th>CIN</th>
                    <th>Immatriculation</th>
                    <th>Numéro de Police</th>
                    <th>Jours Restants</th>
                    <th>Reste</th>
                    <th>Statut paiement</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tfoot>
                  <tr>
                    <th>CIN</th>
                    <th>Immatriculation</th>
                    <th>Numéro de Police</th>
                    <th>Jours Restants</th>
                    <th>Reste</th>
                    <th>Statut paiement</th>
                    <th>Actions</th>
                  </tr>
                </tfoot>
                <tbody>
                  <?php
                  $query = "
                      SELECT 
                          p.*, 
                          p.total_reste AS reste,
                          DATEDIFF(p.end_date, CURDATE()) AS jours_restants,
                          c.client_cin,
                          c.client_name
                      FROM 
                          policy_table p
                      LEFT JOIN clients_table c ON p.client_id = c.id
                  ";
                  $result = $conn->query($query);

                  if ($result && $result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {
                      ?>
                      <tr>
                        <td><?= htmlspecialchars($row['client_cin'] ?? '') ?></td>
                        <td>
                          <?php
                          $immat = trim($row['immatriculation'] ?? '');
                          // Afficher avec direction LTR pour éviter le désordre
                          echo '<span style="direction: ltr; unicode-bidi: bidi-override; display: inline-block;">' . htmlspecialchars($immat) . '</span>';
                          ?>
                        </td>
                        <td><?= $row['n_policy'] ?></td>
                        <td>
                          <?php
                          if ($row['jours_restants'] < 0) {
                            echo "<span class='text-danger'>Expiré</span>";
                          } else {
                            echo $row['jours_restants'] . " jours";
                          }
                          ?>
                        </td>
                        <td><?= $row['reste'] ?></td>                        <td>
                          <?php
                          $reste = floatval($row['reste']);
                          $total = floatval($row['montant_to_paie']);
                          
                          if ($reste <= 0) {
                            // Vérifier les paiements validés
                            $sqlPaiementsValides = "SELECT SUM(montant_paye) as total_valide FROM receipts_table WHERE policy_number = ? AND paiement_statut = 1";
                            $stmtPaiementsValides = $conn->prepare($sqlPaiementsValides);
                            $stmtPaiementsValides->bind_param("s", $row['n_policy']);
                            $stmtPaiementsValides->execute();
                            $stmtPaiementsValides->bind_result($total_valide_result);
                            $total_valide = 0;
                            if ($stmtPaiementsValides->fetch()) {
                              $total_valide = floatval($total_valide_result);
                            }
                            $stmtPaiementsValides->close();
                            
                            // Vérifier s'il y a des paiements non validés (chèques/effets)
                            $sqlEffets = "SELECT COUNT(*) as nb_non_valide FROM receipts_table WHERE policy_number = ? AND UPPER(paiement_mode) IN ('CHEQUE','EFFET') AND paiement_statut != 1";
                            $stmtEffets = $conn->prepare($sqlEffets);
                            $stmtEffets->bind_param("s", $row['n_policy']);
                            $stmtEffets->execute();
                            $stmtEffets->bind_result($nb_non_valide_result);
                            $nb_non_valide = 0;
                            if ($stmtEffets->fetch()) {
                              $nb_non_valide = (int)$nb_non_valide_result;
                            }
                            $stmtEffets->close();
                            
                            // Déterminer le statut
                            if ($reste == 0 && $total_valide >= $total) {
                              echo '<span class="badge badge-success">Payé</span>';
                            } elseif ($nb_non_valide > 0) {
                              echo '<span class="badge badge-dark">En attente de validation</span>';
                            } else {
                              echo '<span class="badge badge-success">Payé</span>';
                            }
                          } elseif ($reste < $total) {
                            echo '<a href="paiement.php?id=' . $row['id'] . '" class="btn btn-warning btn-sm text-white" style="font-weight:bold;">Partiellement payé</a>';
                          } else {
                            // Vérifier s'il y a des paiements en cours (statut = 0)
                            $sqlPaiementsEnCours = "SELECT COUNT(*) as nb_en_cours FROM receipts_table WHERE policy_number = ? AND paiement_statut = 0";
                            $stmtEnCours = $conn->prepare($sqlPaiementsEnCours);
                            $stmtEnCours->bind_param("s", $row['n_policy']);
                            $stmtEnCours->execute();
                            $stmtEnCours->bind_result($nb_en_cours_result);
                            $nb_en_cours = 0;
                            if ($stmtEnCours->fetch()) {
                              $nb_en_cours = (int)$nb_en_cours_result;
                            }
                            $stmtEnCours->close();
                            
                            if ($nb_en_cours > 0) {
                              echo '<a href="liste_cheques_effets.php?policy=' . urlencode($row['n_policy']) . '" class="btn btn-warning btn-sm text-white" style="font-weight:bold;">En cours</a>';
                            } else {
                              echo '<a href="paiement.php?id=' . $row['id'] . '" class="btn btn-danger btn-sm" style="font-weight:bold;">Non payé</a>';
                            }
                          }
                          ?>
                        </td>
                        <td>
                          <a href='info_policy.php?id=<?= $row['id'] ?>' class='btn btn-sm btn-info' title='Détails'>
                            <i class='fas fa-info-circle'></i>
                          </a>
                          <?php
                          // Calculer si le bouton de renouvellement doit être actif
                          $jours_restants = (int)$row['jours_restants'];
                          $show_renew = ($jours_restants <= 30); // Actif si <= 1 mois ou expiré
                          
                          if ($show_renew): ?>
                            <a href='renew_policy.php?id=<?= $row['id'] ?>' class='btn btn-sm btn-success' title='Renouveler la police'>
                              <i class='fas fa-redo'></i>
                            </a>
                          <?php endif; ?>
                          
                          <?php
                          $sqlCheckFacture = "SELECT facture_num FROM facture_table WHERE libelle = ?";
                          $stmtCheckFacture = $conn->prepare($sqlCheckFacture);
                          $stmtCheckFacture->bind_param("s", $row['n_policy']);
                          $stmtCheckFacture->execute();
                          $stmtCheckFacture->bind_result($facture_num_result);
                          $facture = null;
                          if ($stmtCheckFacture->fetch()) {
                            $facture = array('facture_num' => $facture_num_result);
                          }
                          $stmtCheckFacture->close();
                          if ($facture): ?>
                            <a href='facture.php?num=<?= urlencode($facture['facture_num']) ?>' class='btn btn-sm btn-danger' title='Consulter la facture' target='_blank'>
                              <i class='fas fa-file-invoice'></i>
                            </a>
                          <?php endif; ?>
                        </td>
                      </tr>
                      <?php
                    }
                  } else {
                    echo "<tr><td colspan='7' class='text-center'>Aucune police trouvée</td></tr>";
                  }
                  // Connection is managed globally; do not close it here.
                  ?>
                </tbody>
              </table>
            </div>
          </div>
          <!-- End Policies Table -->

        </div>
        <!---Container Fluid-->
      </div>
      <!-- Footer -->
      <?php include('includes/footer.php'); ?>
      <!-- Footer -->
    </div>
  </div>
  <!-- Scroll to top -->
  <a class="scroll-to-top rounded" href="#page-top">
    <i class="fas fa-angle-up"></i>
  </a>
  <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>
  <script src="vendor/datatables/jquery.dataTables.min.js"></script>
  <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
  <script>
    $(document).ready(function () {
      $('#dataTable').DataTable();
    });
  </script>
</body>
</html>
