<?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.*, 
            p.total_reste AS reste 
        FROM 
            policy_table p 
        WHERE 
            p.id = ?
    ";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $policy = $result->fetch_assoc();
    $stmt->close();
}

// Récupérer les informations de la police, y compris le type de police
$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();
$res_policy = $stmt_policy->get_result();
$policy_data = [];
if ($res_policy && $row_policy = $res_policy->fetch_assoc()) {
    $policy_data = $row_policy;
}
$stmt_policy->close();

// Récupérer l'ID du client depuis la table clients_table
$client_id = null;
if ($policy && isset($policy['client_cin'])) {
    $sql_client = "SELECT id FROM clients_table WHERE client_cin = ?";
    $stmt_client = $conn->prepare($sql_client);
    $stmt_client->bind_param("s", $policy['client_cin']);
    $stmt_client->execute();
    $res_client = $stmt_client->get_result();
    if ($res_client && $row_client = $res_client->fetch_assoc()) {
        $client_id = $row_client['id'];
    }
    $stmt_client->close();
}

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

// Générer un numéro de facture unique en suivi
function generateFactureNum() {
    global $conn;
    $year = date('Y');
    $sqlLastFacture = "SELECT facture_num FROM facture_table ORDER BY id DESC LIMIT 1";
    $resultLastFacture = $conn->query($sqlLastFacture);
    $lastFactureNum = "255/$year"; // Default starting number

    if ($resultLastFacture && $rowLastFacture = $resultLastFacture->fetch_assoc()) {
        $lastFactureParts = explode('/', $rowLastFacture['facture_num']);
        if (count($lastFactureParts) === 2 && intval($lastFactureParts[1]) === intval($year)) {
            $lastFactureNum = intval($lastFactureParts[0]) + 1 . "/$year";
        }
    }

    return $lastFactureNum;
}

// Insérer une nouvelle facture dans la base de données
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_facture'])) {
    // Vérifier si le libelle existe déjà dans facture_table
    $sqlCheckFacture = "SELECT COUNT(*) AS count FROM facture_table WHERE libelle = ?";
    $stmtCheckFacture = $conn->prepare($sqlCheckFacture);
    $stmtCheckFacture->bind_param("s", $policy['n_policy']);
    $stmtCheckFacture->execute();
    $resultCheckFacture = $stmtCheckFacture->get_result();
    $rowCheckFacture = $resultCheckFacture->fetch_assoc();
    $stmtCheckFacture->close();

    if ($rowCheckFacture['count'] > 0) {
        $error_message = "La facture pour cette police existe déjà.";
    } else {
        $facture_num = generateFactureNum();
        $facture_date = date('Y-m-d H:i:s');
        $libelle = $policy['n_policy'];
        $objet_assure = $policy['immatriculation'];
        $start_date = $policy['start_date'];
        $end_date = $policy['end_date'];
        $total = $policy['montant_to_paie'];

        $sqlInsertFacture = "INSERT INTO facture_table (facture_num, facture_date, libelle, objet_assure, start_date, end_date, total) 
                             VALUES (?, ?, ?, ?, ?, ?, ?)";
        $stmtInsertFacture = $conn->prepare($sqlInsertFacture);
        $stmtInsertFacture->bind_param("ssssssd", $facture_num, $facture_date, $libelle, $objet_assure, $start_date, $end_date, $total);

        if ($stmtInsertFacture->execute()) {
            header("Location: facture.php?num=" . urlencode($facture_num));
            exit;
        } else {
            $error_message = "Erreur lors de la création de la facture.";
        }
        $stmtInsertFacture->close();
    }
}

// Vérifier si la facture existe déjà
$sqlCheckFacture = "SELECT facture_num FROM facture_table WHERE libelle = ?";
$stmtCheckFacture = $conn->prepare($sqlCheckFacture);
$stmtCheckFacture->bind_param("s", $policy['n_policy']);
$stmtCheckFacture->execute();
$resultCheckFacture = $stmtCheckFacture->get_result();
$existingFacture = $resultCheckFacture->fetch_assoc();
$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();
    $resultPendingPayments = $stmtPendingPayments->get_result();
    if ($resultPendingPayments && $rowPending = $resultPendingPayments->fetch_assoc()) {
        $hasPendingPayments = (int)$rowPending['count'] > 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">
                      <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>
                      <li class="list-group-item"><strong>Immatriculation:</strong> <?php
                        $immat = trim($policy['immatriculation']);
                        $immat_parts = preg_split('/\s*-\s*/u', $immat);
                        if(count($immat_parts) === 3) {
                            $part1 = trim($immat_parts[2]);
                            $part2 = trim($immat_parts[1]);
                            $part3 = trim($immat_parts[0]);
                            echo $part1 . ' - ' . '<span dir="rtl" style="display:inline-block;">' . $part2 . '</span>' . ' - ' . $part3;
                        } else {
                            echo htmlspecialchars($immat);
                        }
                      ?></li>                      <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>
                      <li class="list-group-item"><strong>Marque du Véhicule:</strong> <?php echo !empty($policy['marque']) ? htmlspecialchars($policy['marque']) : 'Non spécifiée'; ?></li>
                      <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="history.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: ?>
                        <form method="POST" action="" class="d-inline">
                            <button type="submit" name="create_facture" class="btn btn-success" title="Créer une facture">
                                <i class="fas fa-file-invoice"></i> Créer Facture
                            </button>
                        </form>
                    <?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>
</body>

</html>