<?php
// Include database connection
include 'config/connexion.php';
// Récupérer les infos du client si id fourni
$client = null;
if (isset($_GET['id'])) {
    $id = intval($_GET['id']);
    // Utiliser une requête directe plus compatible
    $query = "SELECT id, client_cin, client_name, client_phone, client_email, client_adresse, 
                     client_company, client_genre, n_dossier, client_ice 
              FROM clients_table WHERE id = " . intval($id);
    $result = $conn->query($query);
    
    if ($result && $result->num_rows > 0) {
        $client = $result->fetch_assoc();
    }
}

// Calcul du solde du client (débiteur ou créditeur)
$solde = 0;
if (!empty($client['id'])) {
    // Somme des montants à payer (total des polices)
    $client_id = intval($client['id']);
    $sqlTotal = "SELECT SUM(montant_to_paie) as total_a_payer FROM policy_table WHERE client_id = $client_id";
    $resultTotal = $conn->query($sqlTotal);
    $total_a_payer = 0;
    if ($resultTotal && $rowTotal = $resultTotal->fetch_assoc()) {
        $total_a_payer = floatval($rowTotal['total_a_payer']);
    }

    // Somme des montants payés (tous paiements validés)
    $sqlPaye = "SELECT SUM(montant_paye) as total_paye FROM receipts_table WHERE client_id = $client_id AND paiement_statut = 1";
    $resultPaye = $conn->query($sqlPaye);
    $total_paye = 0;
    if ($resultPaye && $rowPaye = $resultPaye->fetch_assoc()) {
        $total_paye = floatval($rowPaye['total_paye']);
    }

    // Solde = payé - à payer (positif = créditeur, négatif = débiteur)
    $solde = $total_paye - $total_a_payer;
}
?>
<!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">Informations sur le client</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item"><a href="clients_table.php">Clients</a></li>
              <li class="breadcrumb-item active" aria-current="page">Détails du client</li>
            </ol>
          </div>
          <div class="row">
            <div class="col-lg-6">
              <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">Détails du client</h6>
                </div>
                <div class="card-body">
                  <?php if ($client): ?>                    <ul class="list-group">
                      <li class="list-group-item"><strong>CIN:</strong> <?php echo htmlspecialchars($client['client_cin']); ?></li>
                      <li class="list-group-item"><strong>Nom:</strong> <?php echo htmlspecialchars($client['client_name']); ?></li>
                      <li class="list-group-item"><strong>Téléphone:</strong> <?php echo htmlspecialchars($client['client_phone']); ?></li>
                      <li class="list-group-item"><strong>Email:</strong> <?php echo htmlspecialchars($client['client_email']); ?></li>
                      <li class="list-group-item"><strong>Entreprise:</strong> <?php echo htmlspecialchars($client['client_company']); ?></li>
                      <li class="list-group-item"><strong>Genre:</strong> <?php echo htmlspecialchars($client['client_genre']); ?></li>
                      <li class="list-group-item"><strong>Adresse:</strong> <?php echo htmlspecialchars($client['client_adresse']); ?></li>
                      <li class="list-group-item"><strong>Numéro de dossier:</strong> <?php echo htmlspecialchars($client['n_dossier']); ?></li>
                      <li class="list-group-item"><strong>ICE:</strong> <?php echo !empty($client['client_ice']) ? htmlspecialchars($client['client_ice']) : 'Non renseigné'; ?></li>
                    </ul>
                  <?php else: ?>
                    <div class="alert alert-danger">Aucune information trouvée pour ce client.</div>
                  <?php endif; ?>
                  <div class="mt-3">
                    <a href="clients_table.php" class="btn btn-secondary">Tableau de Client</a>
                    <a href="edit_client.php?id=<?php echo $client['id']; ?>" class="btn btn-primary">Modifier le Client</a>
                    <a href="view_logs.php?client_cin=<?php echo urlencode($client['client_cin']); ?>" class="btn btn btn-secondary" title="Historique du client">
                      <i class="fas fa-history"></i>
                    </a>
                    <hr>
                    <a href="releve_compte.php?cin=<?php echo urlencode($client['client_cin']); ?>" class="btn btn-info" title="Relevé de compte">
                      <i class="fas fa-file-invoice-dollar"></i> Relevé de compte
                    </a>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-lg-6">
              <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">Compte du client</h6>
                </div>
                <div class="card-body">
                  <h5>Informations sur le Compte</h5>
                  <?php if ($solde < 0): ?>
                      <div class="alert alert-danger">
                          Débiteur : <?php echo number_format(abs($solde), 2, ',', ' '); ?> DH
                      </div>
                  <?php elseif ($solde > 0): ?>
                      <div class="alert alert-success">
                          Créditeur : <?php echo number_format($solde, 2, ',', ' '); ?> DH
                      </div>
                  <?php else: ?>
                      <div class="alert alert-secondary">
                          Solde nul
                      </div>
                  <?php endif; ?>
                </div>
              </div>
            </div>
          </div>
          <!-- Modal Delete -->
          <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="deleteModalLabel">Confirmation de suppression</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                  </button>
                </div>
                <div class="modal-body">
                  Êtes-vous sûr de vouloir supprimer ce client ?
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
                  <button type="button" class="btn btn-danger" id="confirmDelete">Supprimer</button>
                </div>
              </div>
            </div>
          </div>

          <!-- Modal Error -->
          <div class="modal fade" id="errorModal" tabindex="-1" role="dialog" aria-labelledby="errorModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="errorModalLabel">Erreur</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                  </button>
                </div>
                <div class="modal-body">
                  <!-- Error message will be injected here -->
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
                </div>
              </div>
            </div>
          </div>
        </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>
    $(document).ready(function () {
      // Handle confirm delete button click
      $('#confirmDelete').on('click', function () {
        const clientId = <?php echo $client['id']; ?>; // Get client ID
        $.ajax({
          url: 'delete_client.php',
          type: 'POST',
          data: { id: clientId },
          success: function (response) {
            const result = JSON.parse(response); // Parse JSON response
            if (result.status === 'success') {
              // Redirect to clients table after successful deletion
              window.location.href = 'clients_table.php';
            } else if (result.status === 'cannot_delete') {
              // Close the delete confirmation modal
              $('#deleteModal').modal('hide');
              // Show error modal with specific message
              $('#errorModal').find('.modal-body').text(result.message);
              $('#errorModal').modal('show');
            } else {
              // Close the delete confirmation modal
              $('#deleteModal').modal('hide');
              // Show generic error modal
              $('#errorModal').find('.modal-body').text('Erreur lors de la suppression du client.');
              $('#errorModal').modal('show');
            }
          },
          error: function () {
            // Close the delete confirmation modal
            $('#deleteModal').modal('hide');
            // Show error modal for server connection issues
            $('#errorModal').find('.modal-body').text('Erreur de connexion au serveur.');
            $('#errorModal').modal('show');
          }
        });
      });
    });
  </script>
</body>
</html>
