<?php
// Include database connection
include 'config/connexion.php';

// Vérifier si un filtre par police est demandé
$policy_filter = isset($_GET['policy']) ? trim($_GET['policy']) : '';
$policy_id = null;

// Si on filtre par police, récupérer l'ID de la police pour le lien de retour
if (!empty($policy_filter)) {
    $policy_id_query = "SELECT id FROM policy_table WHERE n_policy = ?";
    $stmt_id = $conn->prepare($policy_id_query);
    $stmt_id->bind_param("s", $policy_filter);
    $stmt_id->execute();
    $stmt_id->bind_result($policy_id);
    $stmt_id->fetch();
    $stmt_id->close();
}

// Récupérer les données dans un tableau
$receipts = array();

// Construire la requête avec ou sans filtre
if (!empty($policy_filter)) {
    // Filtrer par police ET par statut en cours (paiement_statut = 0)
    $query = "SELECT id, receipt_number, policy_number, client_id, immatriculation, montant_total, montant_paye, reste_a_payer, agent, date_creation, paiement_mode, paiement_ref, echeance_date, paiement_statut FROM receipts_table WHERE UPPER(paiement_mode) IN ('CHEQUE', 'EFFET', 'VIREMENT BANCAIRE') AND policy_number = ? AND paiement_statut = 0 ORDER BY id DESC";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $policy_filter);
    $stmt->execute();
    $stmt->bind_result($id, $receipt_number, $policy_number, $client_id, $immatriculation, $montant_total, $montant_paye, $reste_a_payer, $agent, $date_creation, $paiement_mode, $paiement_ref, $echeance_date, $paiement_statut);
    while ($stmt->fetch()) {
        $receipts[] = array(
            'id' => $id,
            'receipt_number' => $receipt_number,
            'policy_number' => $policy_number,
            'client_id' => $client_id,
            'immatriculation' => $immatriculation,
            'montant_total' => $montant_total,
            'montant_paye' => $montant_paye,
            'reste_a_payer' => $reste_a_payer,
            'agent' => $agent,
            'date_creation' => $date_creation,
            'paiement_mode' => $paiement_mode,
            'paiement_ref' => $paiement_ref,
            'echeance_date' => $echeance_date,
            'paiement_statut' => $paiement_statut
        );
    }
    $stmt->close();
} else {
    // Sans filtre, afficher tous les chèques/effets (tous statuts)
    $query = "SELECT id, receipt_number, policy_number, client_id, immatriculation, montant_total, montant_paye, reste_a_payer, agent, date_creation, paiement_mode, paiement_ref, echeance_date, paiement_statut FROM receipts_table WHERE UPPER(paiement_mode) IN ('CHEQUE', 'EFFET', 'VIREMENT BANCAIRE') ORDER BY id DESC";
    $result = $conn->query($query);
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $receipts[] = $row;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<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 (optionnel) -->
        <?php  include 'includes/topbar.php'; ?>
        <!-- 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">
              <?php if (!empty($policy_filter)): ?>
                Paiements en cours - Police: <?php echo htmlspecialchars($policy_filter); ?>
              <?php else: ?>
                Tableau des Chèques et Effets
              <?php endif; ?>
            </h1>            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <?php if (!empty($policy_filter)): ?>
                <li class="breadcrumb-item"><a href="policys_table.php">Polices</a></li>
                <li class="breadcrumb-item"><a href="info_policy.php?id=<?php echo urlencode($policy_id); ?>">Police <?php echo htmlspecialchars($policy_filter); ?></a></li>
                <li class="breadcrumb-item active" aria-current="page">Paiements en cours</li>
              <?php else: ?>
                <li class="breadcrumb-item"><a href="./liste_recus.php">Reçus</a></li>
                <li class="breadcrumb-item active" aria-current="page">Chèques & Effets</li>
              <?php endif; ?>
            </ol>
          </div>
          <div class="row">
            <div class="col-lg-12">
              <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">
                    <?php if (!empty($policy_filter)): ?>
                      Paiements en cours (Statut: En attente de validation)
                    <?php else: ?>
                      Liste des Chèques & Effets
                    <?php endif; ?>
                  </h6><div>
                    <?php if (!empty($policy_filter)): ?>
                      <a href="liste_cheques_effets.php" class="btn btn-secondary btn-sm">
                        <i class="fas fa-list"></i> Voir tout
                      </a>
                      <?php if ($policy_id): ?>
                        <a href="info_policy.php?id=<?php echo urlencode($policy_id); ?>" class="btn btn-primary btn-sm">
                          <i class="fas fa-arrow-left"></i> Retour à la police
                        </a>
                      <?php endif; ?>
                    <?php endif; ?>
                  </div>
                </div>
                <div class="card-body">
                  <div class="table-responsive p-3">
                    <table class="table align-items-center table-flush" id="dataTable">
                      <thead class="thead-light">
                        <tr>
                          <th>Numéro de reçu</th>
                          <th>Numéro de police</th>
                          <th>Montant payé</th>
                          <th>Mode</th>
                          <th>Numéro chèque/effet</th>
                          <th>Date d'échéance</th>
                          <th>Statut</th>
                          <th>Actions</th>
                        </tr>
                      </thead>
                      <tbody>
                        <?php if (!empty($receipts)): ?>
                          <?php foreach ($receipts as $row): ?>
                            <tr>
                              <td><?php echo htmlspecialchars($row['receipt_number']); ?></td>
                              <td><?php echo htmlspecialchars($row['policy_number']); ?></td>
                              <td><?php echo htmlspecialchars($row['montant_paye']); ?></td>
                              <td><?php echo htmlspecialchars($row['paiement_mode']); ?></td>
                              <td><?php echo htmlspecialchars($row['paiement_ref']); ?></td>
                              <td>
                                <?php
                                  if (!empty($row['echeance_date'])) {
                                    echo htmlspecialchars(date('d/m/Y', strtotime($row['echeance_date'])));
                                  } else {
                                    echo '-';
                                  }
                                ?>
                              </td>
                              <td>
                                <?php
                                  if ($row['paiement_statut'] == 1) {
                                    echo '<span class="badge badge-success">Validé</span>';
                                  } elseif ($row['paiement_statut'] == 3) {
                                    echo '<span class="badge badge-danger">Reffusé</span>';
                                  } else {
                                    // En cours : lien vers page de validation
                                    echo '<a href="valider_paiement.php?id=' . $row['id'] . '" class="badge badge-warning" style="cursor:pointer;text-decoration:none;">En cours</a>';
                                  }
                                ?>
                              </td>
                              <td>
                                <a href="print_receipt_copy.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-info" target="_blank">
                                  <i class="fas fa-print"></i>
                                </a>
                              </td>
                            </tr>
                          <?php endforeach; ?>
                        <?php endif; ?>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!--Row-->
        </div>
        <!---Container Fluid-->
      </div>
      <!-- Footer -->
      <?php include ('includes/footer.php'); ?>
      <!-- Footer -->
    </div>
  </div>
  <!-- Include required scripts -->
  <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="vendor/datatables/jquery.dataTables.min.js"></script>
  <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
  <script src="js/ruang-admin.min.js"></script>
  <script>
    $(document).ready(function () {
      $('#dataTable').DataTable();
    });
  </script>
</body>
</html>
