
<?php
session_start();
include 'config/connexion.php';
$today = date('Y-m-d');
$message = '';

// Traitement validation/refus direct
if (isset($_POST['action']) && isset($_POST['id'])) {
    $id = intval($_POST['id']);
    if ($_POST['action'] === 'valider') {
        // Récupérer infos du paiement avant validation
        $info_stmt = $conn->prepare("SELECT policy_number, montant_paye, paiement_mode, paiement_ref, receipt_number FROM receipts_table WHERE id = ?");
        $info_stmt->bind_param("i", $id);
        $info_stmt->execute();
        $info_stmt->bind_result($policy_number, $montant_paye, $paiement_mode, $paiement_ref, $receipt_number);
        $info_stmt->fetch();
        $info_stmt->close();
        
        // Validation : paiement_statut = 1
        $update = $conn->prepare("UPDATE receipts_table SET paiement_statut = 1 WHERE id = ?");
        $update->bind_param("i", $id);
        $update->execute();
        $update->close();
        
        // Mettre à jour policy_table : ajouter au montant_paye et soustraire de total_reste
        $sql_update_policy = "UPDATE policy_table 
            SET montant_paye = IFNULL(montant_paye,0) + ?, 
                total_reste = IFNULL(total_reste,0) - ?
            WHERE n_policy = ?";
        $stmt_update = $conn->prepare($sql_update_policy);
        $stmt_update->bind_param("dds", $montant_paye, $montant_paye, $policy_number);
        $stmt_update->execute();
        $stmt_update->close();
        
        $message = "Le paiement a été validé.";
        // Journalisation
        $user = isset($_SESSION['user_name']) ? $_SESSION['user_name'] : 'inconnu';
        $details = " pour la police (" . $policy_number . ") - montant : " . number_format($montant_paye, 2, ',', ' ') . " DH, mode : " . $paiement_mode . ($paiement_ref ? ", référence : " . $paiement_ref : "") . ($receipt_number ? ", reçu : " . $receipt_number : "");
        $log_msg = date('Y-m-d H:i:s') . ", $user à validé un paiement" . $details . "\n";
        file_put_contents(__DIR__ . '/data/123456/journal.log', $log_msg, FILE_APPEND);
    } elseif ($_POST['action'] === 'refuser') {
        // Récupérer infos du paiement avant refus
        $info_stmt = $conn->prepare("SELECT policy_number, montant_paye, paiement_mode, paiement_ref, receipt_number FROM receipts_table WHERE id = ?");
        $info_stmt->bind_param("i", $id);
        $info_stmt->execute();
        $info_stmt->bind_result($policy_number, $montant_paye, $paiement_mode, $paiement_ref, $receipt_number);
        $info_stmt->fetch();
        $info_stmt->close();
        
        // Refus : paiement_statut = 3
        $update = $conn->prepare("UPDATE receipts_table SET paiement_statut = 3 WHERE id = ?");
        $update->bind_param("i", $id);
        $update->execute();
        $update->close();
        
        // Ne pas mettre à jour la table policy en cas de refus
        // Le montant reste non validé, donc ne doit pas être soustrait de montant_paye ni ajouté à total_reste
        
        $message = "Le paiement a été refusé.";
        // Journalisation
        $user = isset($_SESSION['user_name']) ? $_SESSION['user_name'] : 'inconnu';
        $details = " pour la police (" . $policy_number . ") - montant : " . number_format($montant_paye, 2, ',', ' ') . " DH, mode : " . $paiement_mode . ($paiement_ref ? ", référence : " . $paiement_ref : "") . ($receipt_number ? ", reçu : " . $receipt_number : "");
        $log_msg = date('Y-m-d H:i:s') . ", $user à refusé un paiement" . $details . "\n";
        file_put_contents(__DIR__ . '/data/123456/journal.log', $log_msg, FILE_APPEND);
    }
}

$sql = "SELECT id, receipt_number, date_creation, policy_number, client_id, immatriculation, montant_total, montant_paye, reste_a_payer, agent, paiement_mode, paiement_ref, echeance_date, paiement_statut FROM receipts_table WHERE paiement_statut = 0 AND (
    UPPER(paiement_mode) = 'CHEQUE' OR UPPER(paiement_mode) = 'EFFET' OR UPPER(paiement_mode) = 'VIREMENT BANCAIRE'
) AND echeance_date <= ? ORDER BY echeance_date ASC, id DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$stmt->bind_result($rec_id, $receipt_number, $date_creation, $policy_number, $client_id, $immatriculation, $montant_total, $montant_paye, $reste_a_payer, $agent, $paiement_mode, $paiement_ref, $echeance_date, $paiement_statut);
$result = [];
while ($stmt->fetch()) {
    $result[] = [
        'id' => $rec_id,
        'receipt_number' => $receipt_number,
        'date_creation' => $date_creation,
        '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,
        'paiement_mode' => $paiement_mode,
        'paiement_ref' => $paiement_ref,
        'echeance_date' => $echeance_date,
        'paiement_statut' => $paiement_statut
    ];
}
$stmt->close();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <?php include('includes/head.php'); ?>
    <title>Échéances du <?php echo date('d/m/Y'); ?></title>
</head>
<body id="page-top">
<div id="wrapper">
    <?php include('includes/sidebar.php'); ?>
    <div id="content-wrapper" class="d-flex flex-column">
        <div id="content">
            <?php include('includes/topbar.php'); ?>
            <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">Échéances du <?php echo date('d/m/Y'); ?></h1>
                    <a href="dashboard.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Retour Dashboard</a>
                </div>
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Liste des Échéances à valider</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover">
                                <thead class="thead-light">
                                    <tr>
                                        <th>#</th>
                                        <th>Client</th>
                                        <th>Numéro de police</th>
                                        <th>Montant</th>
                                        <th>Mode</th>
                                        <th>Référence</th>
                                        <th>Échéance</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php if (!empty($result)): $i=1; foreach($result as $row): 
                                    // Récupérer les infos du client
                                    $client_name = '';
                                    $client_cin = '';
                                    if (isset($row['client_id']) && !empty($row['client_id'])) {
                                        $stmt_client = $conn->prepare("SELECT client_name, client_cin FROM clients_table WHERE id = ?");
                                        $stmt_client->bind_param("i", $row['client_id']);
                                        $stmt_client->execute();
                                        $stmt_client->bind_result($name_result, $cin_result);
                                        if ($stmt_client->fetch()) {
                                            $client_name = $name_result ?? '';
                                            $client_cin = $cin_result ?? '';
                                        }
                                        $stmt_client->close();
                                    }
                                ?>
                                    <tr>
                                        <td><?php echo $i++; ?></td>
                                        <td><?php echo htmlspecialchars($client_name); ?> <br><small><?php echo htmlspecialchars($client_cin); ?></small></td>
                                        <td><?php echo htmlspecialchars($row['policy_number']); ?></td>
                                        <td><?php echo number_format($row['montant_paye'], 2, ',', ' '); ?> DH</td>
                                        <td><?php echo htmlspecialchars($row['paiement_mode']); ?></td>
                                        <td><?php echo htmlspecialchars($row['paiement_ref']); ?></td>
                                        <td><?php echo htmlspecialchars($row['echeance_date']); ?></td>
                                        <td>
                                            <form method="post" style="display:inline;">
                                                <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                                <input type="hidden" name="action" value="valider">
                                                <button type="submit" class="btn btn-success btn-sm"><i class="fas fa-check"></i> Valider</button>
                                            </form>
                                            <form method="post" style="display:inline;">
                                                <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                                <input type="hidden" name="action" value="refuser">
                                                <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-times"></i> Refuser</button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; else: ?>
                                    <tr><td colspan="8" class="text-center text-muted">Aucune échéance à valider aujourd'hui.</td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php include('includes/footer.php'); ?>
    </div>
</div>
<!-- Modal de confirmation -->
<div class="modal fade" id="confirmationModal" tabindex="-1" role="dialog" aria-labelledby="confirmationModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="confirmationModalLabel">Information</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <?php if (!empty($message)) echo htmlspecialchars($message); ?>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
      </div>
    </div>
  </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>
<script>
$(document).ready(function() {
  <?php if (!empty($message)): ?>
    $('#confirmationModal').modal('show');
  <?php endif; ?>
});
</script>
</body>
</html>
