<?php
// Include database connection
include 'config/connexion.php';
include 'includes/simple_log.php';
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Initialize variables
$policy = null;
$error_message = "";
$success_message = "";

// Check if policy ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: policys_table.php");
    exit;
}

$policy_id = intval($_GET['id']);

// Fetch policy details
$query = "
    SELECT 
        p.id,
        p.n_policy, 
        p.immatriculation,
        p.start_date,
        p.end_date,
        p.montant_to_paie,
        p.montant_paye,
        p.total_reste,
        c.client_name,
        c.client_cin
    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", $policy_id);
$stmt->execute();
$stmt->bind_result($id, $n_policy, $immatriculation, $start_date, $end_date, $montant_to_paie, $montant_paye, $total_reste, $client_name, $client_cin);

$policy = null;
if ($stmt->fetch()) {
    $policy = array(
        'id' => $id,
        'n_policy' => $n_policy,
        'immatriculation' => $immatriculation,
        'start_date' => $start_date,
        'end_date' => $end_date,
        'montant_to_paie' => $montant_to_paie,
        'montant_paye' => $montant_paye,
        'total_reste' => $total_reste,
        'reste' => $total_reste,
        'client_name' => $client_name,
        'client_cin' => $client_cin
    );
}
$stmt->close();

if (!$policy) {
    header("Location: policys_table.php");
    exit;
}

// Fonction pour générer un numéro de facture unique
function generateFactureNum() {
    global $conn;
    
    // Récupérer les informations de la compagnie pour la numérotation
    $sqlCompany = "SELECT facture_ref, facture_prefixe, facture_suffixe, use_year_prefix, use_monthyear_prefix, use_year_suffix, use_monthyear_suffix, reset_number_yearly FROM compagnie_table LIMIT 1";
    $resultCompany = $conn->query($sqlCompany);
    $companyInfo = $resultCompany->fetch_assoc();
    
    // Valeurs par défaut si pas de données dans la table
    $facture_ref = !empty($companyInfo['facture_ref']) ? $companyInfo['facture_ref'] : 1;
    $facture_prefixe = !empty($companyInfo['facture_prefixe']) ? $companyInfo['facture_prefixe'] : '';
    $facture_suffixe = !empty($companyInfo['facture_suffixe']) ? $companyInfo['facture_suffixe'] : '';
    
    // Options automatiques
    $use_year_prefix = !empty($companyInfo['use_year_prefix']);
    $use_monthyear_prefix = !empty($companyInfo['use_monthyear_prefix']);
    $use_year_suffix = !empty($companyInfo['use_year_suffix']);
    $use_monthyear_suffix = !empty($companyInfo['use_monthyear_suffix']);
    $reset_number_yearly = !empty($companyInfo['reset_number_yearly']);
    
    // Calculer le préfixe automatique si activé
    if ($use_year_prefix) {
        $facture_prefixe = date('Y') . '-';
    } elseif ($use_monthyear_prefix) {
        $facture_prefixe = date('my') . '-'; // mois + année (2 chiffres)
    }
    
    // Calculer le suffixe automatique si activé
    if ($use_year_suffix) {
        $facture_suffixe = '/' . date('Y');
    } elseif ($use_monthyear_suffix) {
        $facture_suffixe = '/' . date('my'); // mois + année (2 chiffres)
    }
    
    // Déterminer la condition de recherche pour la dernière facture
    $sqlLastFacture = "SELECT facture_num FROM facture_table ORDER BY id DESC LIMIT 1";
    $whereCondition = "";
    
    // Si remise à zéro annuelle est activée, chercher seulement les factures de l'année courante
    if ($reset_number_yearly) {
        $currentYear = date('Y');
        if ($use_year_prefix) {
            $whereCondition = " WHERE facture_num LIKE '$currentYear-%'";
        } elseif ($use_year_suffix) {
            $whereCondition = " WHERE facture_num LIKE '%/$currentYear'";
        } else {
            // Si pas de préfixe/suffixe avec année, utiliser la date de création
            $whereCondition = " WHERE YEAR(facture_date) = $currentYear";
        }
        $sqlLastFacture = "SELECT facture_num FROM facture_table" . $whereCondition . " ORDER BY id DESC LIMIT 1";
    }
    
    $resultLastFacture = $conn->query($sqlLastFacture);
    
    if ($resultLastFacture && $resultLastFacture->num_rows > 0) {
        $rowLastFacture = $resultLastFacture->fetch_assoc();
        $lastFactureNum = $rowLastFacture['facture_num'];
        
        // Extraire le numéro de la dernière facture (sans préfixe ni suffixe)
        $lastFactureNum = str_replace($facture_prefixe, '', $lastFactureNum);
        $lastFactureNum = str_replace($facture_suffixe, '', $lastFactureNum);
        
        // Incrémenter le numéro
        $newNum = intval($lastFactureNum) + 1;
    } else {
        // Aucune facture n'existe (ou aucune pour l'année courante), utiliser facture_ref comme point de départ
        $newNum = intval($facture_ref);
    }
    
    // Construire le numéro final : préfixe + numéro + suffixe
    $finalFactureNum = $facture_prefixe . $newNum . $facture_suffixe;
    
    return $finalFactureNum;
}

// 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();
$stmtCheckFacture->bind_result($existing_facture_num);

$existingFacture = null;
if ($stmtCheckFacture->fetch()) {
    $existingFacture = array('facture_num' => $existing_facture_num);
}
$stmtCheckFacture->close();

// Si la facture existe déjà, rediriger vers la facture
if ($existingFacture) {
    header("Location: facture.php?num=" . urlencode($existingFacture['facture_num']));
    exit;
}

// Créer automatiquement la facture dès l'ouverture de la page
$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()) {
    // Enregistrer la création de la facture dans le log global
    logFactureCreation($facture_num, $policy['client_name'], $policy['client_cin'], $total);
    
    $success_message = "Facture créée avec succès ! Redirection vers la facture...";
    // Redirection automatique vers la facture créée
    header("refresh:2;url=facture.php?num=" . urlencode($facture_num));
} else {
    $error_message = "Erreur lors de la création de la facture : " . $conn->error;
}
$stmtInsertFacture->close();
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <?php include ('includes/head.php'); ?>
  <style>
    .loading-spinner {
      border: 4px solid #f3f3f3;
      border-top: 4px solid #3498db;
      border-radius: 50%;
      width: 50px;
      height: 50px;
      animation: spin 1s linear infinite;
      margin: 0 auto;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .creation-container {
      text-align: center;
      padding: 50px 20px;
    }
  </style>
</head>

<body id="page-top">
  <div id="wrapper">
    <!-- Sidebar -->
    <!-- Sidebar -->

    <div id="content-wrapper" class="d-flex flex-column">
      <div id="content">
        <!-- TopBar -->
        <!-- 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">Création de Facture</h1>
            <ol class="breadcrumb">
            </ol>
          </div>

          <div class="row justify-content-center">
            <div class="col-lg-8">
              <div class="card">
                <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">Création de Facture en Cours</h6>
                </div>
                <div class="card-body">
                  <div class="creation-container">
                    <?php if ($success_message): ?>
                      <div class="alert alert-success">
                        <i class="fas fa-check-circle fa-2x mb-3 text-success"></i>
                        <h4>Facture Créée avec Succès!</h4>
                        <p><?php echo $success_message; ?></p>
                        <div class="loading-spinner mt-3"></div>
                        <p class="mt-3">Redirection automatique en cours...</p>
                      </div>
                      
                      <!-- Informations de la facture créée -->
                      <div class="mt-4">
                        <h5>Détails de la Facture Créée</h5>
                        <div class="row">
                          <div class="col-md-6">
                            <ul class="list-group text-left">
                              <li class="list-group-item"><strong>Numéro de Facture:</strong> <?php echo $facture_num; ?></li>
                              <li class="list-group-item"><strong>Date de Création:</strong> <?php echo date('d/m/Y H:i', strtotime($facture_date)); ?></li>
                              <li class="list-group-item"><strong>Police:</strong> <?php echo $libelle; ?></li>
                              <li class="list-group-item"><strong>Client:</strong> <?php echo $policy['client_name']; ?></li>
                            </ul>
                          </div>
                          <div class="col-md-6">
                            <ul class="list-group text-left">
                              <li class="list-group-item"><strong>Objet Assuré:</strong> <?php echo $objet_assure; ?></li>
                              <li class="list-group-item"><strong>Période:</strong> <?php echo date('d/m/Y', strtotime($start_date)) . ' - ' . date('d/m/Y', strtotime($end_date)); ?></li>
                              <li class="list-group-item"><strong>Montant:</strong> <?php echo number_format($total, 2, ',', ' ') . ' DH'; ?></li>
                              <li class="list-group-item"><strong>Statut:</strong> <span class="badge badge-success">Créée</span></li>
                            </ul>
                          </div>
                        </div>
                      </div>
                      
                      <div class="mt-4">
                        <a href="facture.php?num=<?php echo urlencode($facture_num); ?>" class="btn btn-primary btn-lg">
                          <i class="fas fa-file-invoice"></i> Voir la Facture
                        </a>
                        <a href="info_policy.php?id=<?php echo $policy_id; ?>" class="btn btn-secondary btn-lg ml-2">
                          <i class="fas fa-arrow-left"></i> Retour à la Police
                        </a>
                      </div>
                      
                    <?php elseif ($error_message): ?>
                      <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle fa-2x mb-3 text-danger"></i>
                        <h4>Erreur lors de la Création</h4>
                        <p><?php echo $error_message; ?></p>
                        <div class="mt-3">
                          <a href="info_policy.php?id=<?php echo $policy_id; ?>" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> Retour à la Police
                          </a>
                          <button onclick="location.reload()" class="btn btn-primary ml-2">
                            <i class="fas fa-redo"></i> Réessayer
                          </button>
                        </div>
                      </div>
                    <?php else: ?>
                      <div class="loading-spinner"></div>
                      <h4 class="mt-3">Création de la facture en cours...</h4>
                      <p>Veuillez patienter pendant que nous créons votre facture.</p>
                    <?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>
  
  <?php if ($success_message): ?>
  <script>
    // Redirection automatique après 3 secondes si pas déjà redirigé
    setTimeout(function() {
      if (!document.hidden) {
        window.location.href = 'facture.php?num=<?php echo urlencode($facture_num); ?>';
      }
    }, 3000);
  </script>
  <?php endif; ?>
</body>

</html>
