<?php
// Include database connection
include 'config/connexion.php';
// Initialize variables
$policy = null;

// Fetch policy details if ID is provided
if (isset($_GET['id'])) {
    $id = intval($_GET['id']);    $query = "
        SELECT 
            p.id, p.n_policy, p.immatriculation, p.start_date, p.end_date, p.montant_to_paie, p.total_reste, p.policy_type, p.policy_category, p.marque, c.id as client_id, c.client_cin, c.client_name
        FROM 
            policy_table p 
        LEFT JOIN clients_table c ON p.client_id = c.id
        WHERE 
            p.id = ?
    ";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($policy_id, $policy_n_policy, $policy_immatriculation, $policy_start_date, $policy_end_date, $policy_montant_to_paie, $policy_total_reste, $policy_policy_type, $policy_policy_category, $policy_marque, $policy_client_id, $policy_client_cin, $policy_client_name);
    $policy = null;
    if ($stmt->fetch()) {
        $policy = array(
            'id' => $policy_id,
            'n_policy' => $policy_n_policy,
            'immatriculation' => $policy_immatriculation,
            'start_date' => $policy_start_date,
            'end_date' => $policy_end_date,
            'montant_to_paie' => $policy_montant_to_paie,
            'total_reste' => $policy_total_reste,
            'reste' => $policy_total_reste,
            'policy_type' => $policy_policy_type,
            'policy_category' => $policy_policy_category,
            'marque' => $policy_marque,
            'client_id' => $policy_client_id,
            'client_cin' => $policy_client_cin,
            'client_name' => $policy_client_name
        );
    }
    $stmt->close();
}

// Récupérer les informations de la police, y compris le type de police
if (isset($n_policy)) {
    $sql_policy = "SELECT n_policy, immatriculation, start_date, end_date, montant_to_paie, policy_type FROM policy_table WHERE n_policy = ?";
    $stmt_policy = $conn->prepare($sql_policy);
    $stmt_policy->bind_param("s", $n_policy);
    $stmt_policy->execute();
    $stmt_policy->bind_result($policy_n_policy, $policy_immatriculation, $policy_start_date, $policy_end_date, $policy_montant_to_paie, $policy_policy_type);
    $policy_data = [];
    if ($stmt_policy->fetch()) {
        $policy_data = array(
            'n_policy' => $policy_n_policy,
            'immatriculation' => $policy_immatriculation,
            'start_date' => $policy_start_date,
            'end_date' => $policy_end_date,
            'montant_to_paie' => $policy_montant_to_paie,
            'policy_type' => $policy_policy_type
        );
    }
    $stmt_policy->close();
}

// Récupérer l'ID du client depuis les données de la police
$client_id = $policy ? $policy['client_id'] : null;

// Ne pas fermer la connexion ici !
// $conn->close();

// Vérifier si la facture existe déjà
$existingFacture = null;
if ($policy && isset($policy['n_policy'])) {
    $sqlCheckFacture = "SELECT facture_num FROM facture_table WHERE libelle = ?";
    $stmtCheckFacture = $conn->prepare($sqlCheckFacture);
    $stmtCheckFacture->bind_param("s", $policy['n_policy']);
    $stmtCheckFacture->execute();
    $stmtCheckFacture->bind_result($facture_num_result);
    if ($stmtCheckFacture->fetch()) {
        $existingFacture = array('facture_num' => $facture_num_result);
    }
    $stmtCheckFacture->close();
}

// Vérifier s'il y a des paiements en cours (non validés) pour cette police
$hasPendingPayments = false;
if ($policy) {
    $sqlPendingPayments = "SELECT COUNT(*) as count FROM receipts_table WHERE policy_number = ? AND UPPER(paiement_mode) IN ('CHEQUE', 'EFFET', 'VIREMENT BANCAIRE') AND paiement_statut = 0";
    $stmtPendingPayments = $conn->prepare($sqlPendingPayments);
    $stmtPendingPayments->bind_param("s", $policy['n_policy']);
    $stmtPendingPayments->execute();
    $stmtPendingPayments->bind_result($count_result);
    if ($stmtPendingPayments->fetch()) {
        $hasPendingPayments = (int)$count_result > 0;
    }
    $stmtPendingPayments->close();
}
?>

<!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 la Police</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item"><a href="policys_table.php">Polices</a></li>
              <li class="breadcrumb-item active" aria-current="page">Détails de la Police</li>
            </ol>
          </div>

          <div class="row">
            <div class="col-lg-6">
              <!-- Policy Details -->
              <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 de la Police</h6>
                </div>
                <div class="card-body">
                  <?php if ($policy): ?>
                    <ul class="list-group">
                      <!-- Affichage catégorie de police avec icône -->
                      <li class="list-group-item">
                        <strong>Catégorie de Police :</strong> 
                        <?php if (isset($policy['policy_category']) && $policy['policy_category'] === 'RD'): ?>
                          <span class="badge badge-warning px-3 py-2"><i class="fas fa-shield-alt mr-2"></i><strong>Risque Divers (RD)</strong></span>
                        <?php else: ?>
                          <span class="badge badge-info px-3 py-2"><i class="fas fa-car mr-2"></i><strong>Véhicule (V)</strong></span>
                        <?php endif; ?>
                      </li>
                      <li class="list-group-item"><strong>CIN Client:</strong> <?php echo $policy['client_cin']; ?></li>
                      <li class="list-group-item"><strong>Nom Client:</strong> <?php echo $policy['client_name']; ?></li>
                      <?php if (!isset($policy['policy_category']) || $policy['policy_category'] !== 'RD'): ?>
                      <li class="list-group-item"><strong>Immatriculation:</strong> <span style="direction: ltr; unicode-bidi: bidi-override; display: inline-block;"><?php echo htmlspecialchars($policy['immatriculation']); ?></span></li>
                      <?php endif; ?>
                      <li class="list-group-item"><strong>Numéro de Police:</strong> <?php echo $policy['n_policy']; ?></li>
                      <li class="list-group-item"><strong>Type de Police:</strong> <?php echo $policy['policy_type']; ?></li>
                      <?php if (!isset($policy['policy_category']) || $policy['policy_category'] !== 'RD'): ?>
                      <li class="list-group-item"><strong>Marque du Véhicule:</strong> <?php echo !empty($policy['marque']) ? htmlspecialchars($policy['marque']) : 'Non spécifiée'; ?></li>
                      <?php endif; ?>
                      <li class="list-group-item"><strong>Date de Début:</strong> <?php echo $policy['start_date']; ?></li>
                      <li class="list-group-item"><strong>Date de Fin:</strong> <?php echo $policy['end_date']; ?></li>
                      <li class="list-group-item"><strong>Montant à Payer:</strong> <?php echo $policy['montant_to_paie'] . ' DH'; ?></li>
                      <li class="list-group-item"><strong>Reste:</strong> <?php echo $policy['reste'] . ' DH'; ?></li>
                      <li class="list-group-item"><strong>Jours Restants:</strong> <?php
                        // Calcul des jours restants entre la date de début et la date de fin
                        $jours_restants = null;
                        if ($policy && $policy['start_date'] && $policy['end_date']) {
                            $date_debut = new DateTime($policy['start_date']);
                            $date_fin = new DateTime($policy['end_date']);
                            $interval = $date_debut->diff($date_fin);
                            $jours_restants = $interval->format('%r%a');
                        }
                        echo $jours_restants !== null ? $jours_restants . ' jours' : 'N/A';
                      ?></li>
                    </ul>
                  <?php else: ?>
                    <div class="alert alert-danger">Aucune information trouvée pour cette police.</div>
                  <?php endif; ?>
                  <div class="mt-3">
                    <a href="policys_table.php" class="btn btn-secondary">Retour</a>
                    <a href="view_logs.php?policy_num=<?php echo urlencode($policy['n_policy']); ?>" class="btn btn-success" title="Historique de cette police"><i class='fas fa-history'></i> Historique</a>
                    <a href="info_client.php?id=<?php echo urlencode($client_id); ?>" class="btn btn-info" title="Client Info"><i class='fas fa-user'></i> Client</a>                    <?php if ($existingFacture): ?>
                        <a href="facture.php?num=<?php echo urlencode($existingFacture['facture_num']); ?>" class="btn btn-primary" title="Consulter la facture" target='_blank'>
                            <i class="fas fa-file-invoice"></i> Consulter Facture
                        </a>
                    <?php else: ?>
                        <button type="button" class="btn btn-success" title="Créer une facture" data-toggle="modal" data-target="#confirmFactureModal">
                            <i class="fas fa-file-invoice"></i> Créer Facture
                        </button>
                    <?php endif; ?>
                    <a href='liste_paiements_policy.php?policy=<?= urlencode($policy['n_policy']) ?>' class='btn btn btn-info' title='Imprimer paiements de cette police' target='_blank'>
                        <i class='fas fa-money-check-alt'></i>
                    </a>                    <a href='edit_policy.php?id=<?= $policy['id'] ?>' class='btn btn btn-primary' title='Modifier'>
                        <i class='fas fa-edit'></i>
                    </a>
                    <?php if ($hasPendingPayments): ?>
                    <hr>
                      <a href='liste_cheques_effets.php?policy=<?= urlencode($policy['n_policy']) ?>' class='btn btn btn-warning' title='Voir les paiements en cours de cette police'>
                        <i class='fas fa-hourglass-half'></i> Paiements en cours
                    </a>
                    <?php endif; ?>
                  </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="js/ruang-admin.min.js"></script>

  <!-- Modal de confirmation pour créer facture -->
  <div class="modal fade" id="confirmFactureModal" tabindex="-1" role="dialog" aria-labelledby="confirmFactureModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header bg-warning">
          <h5 class="modal-title" id="confirmFactureModalLabel">
            <i class="fas fa-exclamation-triangle"></i> Confirmation requise
          </h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <p class="mb-3">Pour confirmer la création de la facture, veuillez saisir la phrase suivante :</p>
          <div class="alert alert-info text-center mb-3" style="font-weight: bold; user-select: none;">
            <span id="phraseToType">CRÉER FACTURE</span>
          </div>
          <div class="form-group">
            <label for="confirmationPhrase">Saisissez la phrase :</label>
            <input type="text" class="form-control" id="confirmationPhrase" 
                   placeholder="Tapez la phrase ci-dessus" 
                   autocomplete="off" 
                   onpaste="return false;" 
                   ondrop="return false;">
            <small id="phraseError" class="text-danger" style="display: none;">La phrase saisie ne correspond pas.</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
          <button type="button" class="btn btn-success" id="btnConfirmFacture" disabled>
            <i class="fas fa-check"></i> Confirmer
          </button>
        </div>
      </div>
    </div>
  </div>

  <script>
    $(document).ready(function() {
      const phraseToMatch = 'CRÉER FACTURE';
      
      // Vérifier la saisie en temps réel
      $('#confirmationPhrase').on('input', function() {
        const userInput = $(this).val().toUpperCase();
        const btnConfirm = $('#btnConfirmFacture');
        const errorMsg = $('#phraseError');
        
        if (userInput === phraseToMatch) {
          btnConfirm.prop('disabled', false);
          errorMsg.hide();
        } else {
          btnConfirm.prop('disabled', true);
          if (userInput.length >= phraseToMatch.length) {
            errorMsg.show();
          } else {
            errorMsg.hide();
          }
        }
      });

      // Empêcher le copier-coller et le glisser-déposer
      $('#confirmationPhrase').on('paste drop', function(e) {
        e.preventDefault();
        return false;
      });

      // Action de confirmation
      $('#btnConfirmFacture').on('click', function() {
        window.open('create_facture.php?id=<?php echo $policy['id']; ?>', '_blank');
        $('#confirmFactureModal').modal('hide');
        $('#confirmationPhrase').val('');
      });

      // Réinitialiser le champ quand le modal se ferme
      $('#confirmFactureModal').on('hidden.bs.modal', function() {
        $('#confirmationPhrase').val('');
        $('#btnConfirmFacture').prop('disabled', true);
        $('#phraseError').hide();
      });
    });
  </script>
</body>

</html>