2025-04-14 11:25:26 +02:00

374 lines
15 KiB
PHP

<?php
// Inizia la sessione e includi i file necessari
session_start();
require_once('include/headscript.php');
// Debug: verifica il contenuto della sessione
\Log::info('Contenuto della sessione:', $_SESSION);
// Ottieni l'istanza del DBHandlerSelect
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->getConnection();
// Recupera lo school_id e user_id dalla sessione
$school_id = session('school_id');
$user_id = $iduserlogin;
// Debug: verifica il valore di iduserlogin
\Log::info('Valore di iduserlogin: ' . $user_id);
// Controlla se l'utente è loggato
if (empty($user_id)) {
// Reindirizza alla pagina di login se l'utente non è loggato
header('Location: login.php?error=not_logged_in');
exit;
}
$school = null;
$school_name = 'Nessuna scuola selezionata';
$school_logo_path = url('userarea/photoschool/yogibook_logo.png'); // Default logo
if ($school_id) {
$school = \Vanguard\Models\School::find($school_id);
if ($school) {
$school_name = $school->name;
$school_logo_path = $school->logo ? url('userarea/photoschool/' . $school->logo) : $school_logo_path;
}
}
// Inizializza il carrello se non esiste
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Recupera i prodotti nel carrello
$cart_items = [];
$total_price = 0;
if (!empty($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $cart_key => $item) {
$product_id = $item['product_id'];
$variation_id = $item['variation_id'];
$class_type_id = $item['class_type_id'];
$quantity = $item['quantity'];
// Query per ottenere i dettagli del prodotto, variazione e classe
$stmt = $pdo->prepare("
SELECT p.id AS product_id, p.name AS product_name,
pv.id AS variation_id, pv.name AS variation_name, pv.price, pv.duration_days, pv.max_entries, pv.max_recoveries,
c.id AS class_id, c.name AS class_name, c.photo AS class_photo,
ct.id AS class_type_id, ct.level, ct.day_of_week
FROM products p
JOIN product_variations pv ON pv.id = ?
LEFT JOIN product_class_types pct ON p.id = pct.product_id AND pct.variation_id IS NULL
LEFT JOIN class_types ct ON ct.id = ?
LEFT JOIN classes c ON ct.class_id = c.id
WHERE p.id = ?
");
$stmt->execute([$variation_id, $class_type_id, $product_id]);
$cart_item = $stmt->fetch(PDO::FETCH_ASSOC);
if ($cart_item) {
$cart_items[$cart_key] = [
'product_id' => $cart_item['product_id'],
'product_name' => $cart_item['product_name'],
'variation_id' => $cart_item['variation_id'],
'variation_name' => $cart_item['variation_name'],
'class_id' => $cart_item['class_id'],
'class_name' => $cart_item['class_name'],
'class_type_id' => $cart_item['class_type_id'],
'level' => $cart_item['level'],
'day_of_week' => $cart_item['day_of_week'],
'photo' => $cart_item['class_photo'] ?: 'default_class_image.jpg',
'price' => $cart_item['price'],
'quantity' => $quantity,
'subtotal' => $cart_item['price'] * $quantity,
'duration_days' => $cart_item['duration_days'],
'max_entries' => $cart_item['max_entries'],
'max_recoveries' => $cart_item['max_recoveries']
];
$total_price += $cart_item['price'] * $quantity;
}
}
}
// Calcola il numero totale di elementi nel carrello
$cart_count = array_sum(array_column($_SESSION['cart'], 'quantity'));
// Gestione della conferma dell'acquisto
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_purchase'])) {
// Assicurati che non ci siano output prima di questo punto
ob_start(); // Avvia il buffer per catturare eventuali output indesiderati
if (empty($cart_items)) {
$response = ['success' => false, 'message' => 'Il carrello è vuoto.'];
} else {
try {
// Verifica che user_id non sia NULL
if (empty($user_id)) {
throw new Exception("L'ID utente non è definito nella sessione.");
}
// Genera un order_number unico
$stmt = $pdo->query("SELECT MAX(order_number) AS max_order FROM orders");
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$order_number = ($result['max_order'] ?? 0) + 1;
// Inserisci ogni elemento del carrello come un ordine
foreach ($cart_items as $item) {
// Usa max_entries direttamente dalla tabella
$total_entries = $item['max_entries'] ?? 0; // 0 se non definito
$available_entries = $total_entries;
// Usa max_recoveries direttamente dalla tabella
$available_recoveries = $item['max_recoveries'] ?? 0; // 0 se non definito
// Calcola expiration_date
$activation_date = date('Y-m-d'); // Oggi
$expiration_date = null;
if (!empty($item['duration_days']) && is_numeric($item['duration_days'])) {
$expiration_date = date('Y-m-d', strtotime($activation_date . ' + ' . $item['duration_days'] . ' days'));
}
// Debug: log dei valori
\Log::info('Calcolo expiration_date:', [
'variation_id' => $item['variation_id'],
'duration_days' => $item['duration_days'],
'activation_date' => $activation_date,
'expiration_date' => $expiration_date
]);
$stmt = $pdo->prepare("
INSERT INTO orders (
order_number, school_id, user_id, product_id, variation_id, class_id, class_type_id,
created_at, payment_method, price, status, total_entries, available_entries,
available_recoveries, expiration_date, activation_date
) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), 'direct', ?, 'completed', ?, ?, ?, ?, ?)
");
$stmt->execute([
$order_number,
$school_id,
$user_id,
$item['product_id'],
$item['variation_id'],
$item['class_id'],
$item['class_type_id'],
$item['subtotal'],
$total_entries,
$available_entries,
$available_recoveries,
$expiration_date,
$activation_date
]);
}
// Svuota il carrello
$_SESSION['cart'] = [];
// Reindirizza alla pagina di ringraziamento con l'order_number
$response = ['success' => true, 'redirect' => 'thank_you.php?order_number=' . $order_number];
} catch (Exception $e) {
$response = ['success' => false, 'message' => 'Errore durante l\'acquisto: ' . $e->getMessage()];
}
}
// Pulisci il buffer e invia la risposta JSON
ob_end_clean();
header('Content-Type: application/json');
echo json_encode($response);
exit;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
<?php include('cssinclude.php'); ?>
<?php include('siteinfo.php'); ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
.page-content {
background-color: #f0f4f5;
}
.card-pastel {
background-color: rgb(149, 217, 248);
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
border: none;
}
.cart-item-card {
background-color: #fff;
border: 1px solid #c8e6c9;
border-radius: 8px;
margin-bottom: 15px;
padding: 15px;
}
.cart-item-image {
width: 60px;
height: 60px;
object-fit: cover;
border-radius: 50%;
}
.btn-pastel {
background-color: rgb(148, 186, 204);
border: none;
transition: background-color 0.3s ease;
}
.btn-pastel:hover {
background-color: rgb(155, 189, 221);
}
h5,
h6 {
font-family: 'Poppins', sans-serif;
color: #333;
}
.cart-item-details p {
margin: 0;
font-size: 0.9rem;
color: #555;
}
.cart-item-details .price {
font-weight: bold;
color: #28a745;
}
.total-section {
background-color: rgb(148, 186, 204);
color: #fff;
padding: 10px;
border-radius: 8px;
}
.swal2-pastel {
background-color: #f0f4f5;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}
.swal2-title {
font-family: 'Poppins', sans-serif;
color: #333;
}
.swal2-content {
font-family: 'Poppins', sans-serif;
color: #333;
}
</style>
</head>
<body>
<div class="wrapper">
<?php include('include/navbar.php'); ?>
<?php include('include/topbar.php'); ?>
<div class="page-wrapper">
<div class="page-content">
<div class="card card-pastel radius-10 mb-4">
<div class="card-body text-center">
<?php if ($school): ?>
<h5 class="mb-3">Checkout - Scuola: <?php echo htmlspecialchars($school_name); ?></h5>
<img src="<?php echo $school_logo_path; ?>" alt="School Logo" style="max-height: 100px;">
<?php else: ?>
<h5 class="mb-3">Nessuna scuola selezionata</h5>
<img src="<?php echo $school_logo_path; ?>" alt="Default Logo" style="max-height: 100px;">
<?php endif; ?>
</div>
</div>
<div class="card card-pastel radius-10">
<div class="card-header">
<div class="d-flex align-items-center">
<div>
<h6 class="mb-0">Riepilogo Carrello</h6>
</div>
</div>
</div>
<div class="card-body">
<?php if (empty($cart_items)): ?>
<p class="text-center text-muted">Il carrello è vuoto.</p>
<?php else: ?>
<div class="cart-items-list">
<?php foreach ($cart_items as $item): ?>
<div class="cart-item-card d-flex align-items-center">
<img src="<?php echo htmlspecialchars($item['photo']); ?>" class="cart-item-image me-3" alt="product image">
<div class="cart-item-details flex-grow-1">
<h6 class="mb-1"><?php echo htmlspecialchars($item['product_name']); ?></h6>
<p><strong>Variazione:</strong> <?php echo htmlspecialchars($item['variation_name']); ?></p>
<p><strong>Classe:</strong> <?php echo htmlspecialchars($item['class_name'] . ' - ' . $item['level'] . ' (' . $item['day_of_week'] . ')'); ?></p>
<p><strong>Quantità:</strong> <?php echo $item['quantity']; ?></p>
<p><strong>Prezzo Unitario:</strong> €<?php echo number_format($item['price'], 2); ?></p>
<p class="price"><strong>Subtotale:</strong> €<?php echo number_format($item['subtotal'], 2); ?></p>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="total-section mt-3 d-flex justify-content-between align-items-center">
<h5 class="mb-0">Totale</h5>
<h5 class="mb-0">€<?php echo number_format($total_price, 2); ?></h5>
</div>
<div class="text-center mt-4">
<button id="confirm_purchase" class="btn btn-pastel">Conferma Acquisto</button>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<div class="overlay toggle-icon"></div>
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<?php include('include/footer.php'); ?>
</div>
<?php include('jsinclude.php'); ?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#confirm_purchase').on('click', function() {
$.ajax({
url: 'checkout.php',
method: 'POST',
data: {
confirm_purchase: true
},
dataType: 'json',
success: function(response) {
console.log('Risposta AJAX:', response);
if (response.success) {
window.location.href = response.redirect;
} else {
Swal.fire({
icon: 'error',
title: 'Errore',
text: response.message,
confirmButtonText: 'OK',
confirmButtonColor: '#94bacc',
customClass: {
popup: 'swal2-pastel',
title: 'swal2-title',
content: 'swal2-content'
}
});
}
},
error: function(xhr, status, error) {
console.log('Errore AJAX:', xhr.responseText);
Swal.fire({
icon: 'error',
title: 'Errore',
text: 'Errore di connessione: ' + xhr.responseText,
confirmButtonColor: '#94bacc'
});
}
});
});
});
</script>
</body>
</html>