-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckout.php
More file actions
370 lines (304 loc) · 14.2 KB
/
checkout.php
File metadata and controls
370 lines (304 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<?php
session_start();
require "include/template2.inc.php";
require "include/auth.inc.php";
require "include/dbms.inc.php";
include "include/utils/priceFormatter.php";
if (isset($_SESSION['user']['groups'])) {
$main = new Template("skins/motor-html-package/motor/frame-customer.html");
} else {
header("Location: /MotorShop/login.php");
exit();
}
$body = new Template("skins/motor-html-package/motor/checkout.html");
// titolo del prodotto
function getProductTitle($subproductId) {
global $mysqli;
$query = "SELECT title FROM products WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("i", $subproductId);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
return $row['title'];
} else {
return 'Titolo non disponibile';
}
}
$userEmail = $mysqli->real_escape_string($_SESSION['user']['email']);
// indirizzi di spedizione
$addressesQuery = "SELECT * FROM shipping_address WHERE users_email = ?";
$stmtAddresses = $mysqli->prepare($addressesQuery);
$stmtAddresses->bind_param("s", $userEmail);
$stmtAddresses->execute();
$resultAddresses = $stmtAddresses->get_result();
$addresses = [];
while ($row = $resultAddresses->fetch_assoc()) {
$addresses[] = $row;
}
$stmtAddresses->close();
foreach ($addresses as $address) {
$body->setContent("id", $address['id']);
$body->setContent("ADname", $address['name']);
$body->setContent("ADsurname", $address['surname']);
$body->setContent("ADphone", $address['phone']);
$body->setContent("ADprovince", $address['province']);
$body->setContent("ADcity", $address['city']);
$body->setContent("ADstreetAddress", $address['streetAddress']);
$body->setContent("ADcap", $address['cap']);
}
if (isset($_POST['add-address-button'])) {
// Aggiunta nuovo indirizzo di spedizione
$name = $_POST["name"];
$surname = $_POST["surname"];
$phone = $_POST["phone"];
$province = $_POST["province"];
$city = $_POST["city"];
$address = $_POST["streetAddress"];
$cap = $_POST["cap"];
if ($name != "" && $surname != "" && $phone != "" && $province != "" && $city != "" && $address != "" && $cap != "") {
$mysqli->query("INSERT INTO shipping_address (users_email, name, surname, phone, province, city, streetAddress, cap)
VALUE ('{$_SESSION['user']['email']}', '$name', '$surname', '$phone', '$province', '$city', '$address', '$cap')");
}
}
// totale ordine
$totalPrice = 0;
$products = [];
$sub_quantity = 0;
// prodotti dal carrello
$userEmail = $_SESSION['user']['email'];
$query = "SELECT c.subproduct_id, c.quantity, sp.products_id, sp.price, sp.quantity AS prod_quantity, sp.availability, sp.color, sp.size, i.imgsrc, i.id
FROM cart c
JOIN sub_products sp ON c.subproduct_id = sp.id
INNER JOIN images i ON sp.products_id = i.product_id
WHERE c.user_email = ?
GROUP BY sp.products_id";
$stmt = $mysqli->prepare($query);
if ($stmt) {
$stmt->bind_param("s", $userEmail);
$stmt->execute();
$result = $stmt->get_result();
while ($cartItem = $result->fetch_assoc()) {
$subproductId = $cartItem['subproduct_id'];
$sub_quantity = $cartItem['prod_quantity'];
$productQuery = "SELECT title FROM products WHERE id = ?";
$stmt_product = $mysqli->prepare($productQuery);
if ($stmt_product) {
$stmt_product->bind_param("i", $cartItem['products_id']);
$stmt_product->execute();
$productResult = $stmt_product->get_result();
if ($productData = $productResult->fetch_assoc()) {
$title = $productData['title'];
$size = $cartItem['size'];
$color = $cartItem['color'];
$price = floatval($cartItem['price']);
$quantity = intval($cartItem['quantity']);
$availability = intval($cartItem['availability']);
$stockQuantity = intval($cartItem['prod_quantity']);
// verifica se il sottoprodotto è disponibile
if ($availability == 1 && $quantity <= $stockQuantity) {
$subtotal = $price * $quantity;
$totalPrice += $subtotal;
// dettagli del prodotto nell'array
$products[] = [
'subproduct_id' => $subproductId,
'title' => $title,
'quantity' => $quantity,
'subtotal' => $subtotal,
'quantityCheck' => $stockQuantity - $quantity
];
$body->setContent("title", $title);
$body->setContent("quantity", $quantity);
$body->setContent("size", $size);
$body->setContent("color", $color);
$body->setContent("price", priceFormatter($subtotal));
} else {
echo "Prodotto con ID $subproductId non disponibile o quantità insufficiente. Sarà escluso dall'ordine.<br>";
}
}
$stmt_product->close();
}
}
$stmt->close();
$body->setContent("total_price", priceFormatter($totalPrice));
} else {
echo "Errore nella query del carrello: " . $mysqli->error;
}
// verifica se ci sono prodotti da acquistare
if (empty($products)) {
echo "Nessun prodotto disponibile nel carrello per l'ordine.";
exit;
}
// vrifica se l' indirizzo di spedizione e il metodo di pagamento sono stati selezionati
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['address_list']) && isset($_POST['payment_method'])) {
$shippingAddressId = $mysqli->real_escape_string($_POST['address_list']);
// Prodotti nel carrello dell'utente
$queryCart = "SELECT c.subproduct_id, c.quantity, sp.products_id, sp.price,sp.quantity as prod_quantity, sp.availability, sp.color, sp.size, i.imgsrc,i.id FROM cart c JOIN sub_products sp ON c.subproduct_id = sp.id INNER JOIN images i ON sp.products_id = i.product_id WHERE c.user_email ='$userEmail' GROUP BY sp.products_id";
$resultCart = $mysqli->query($queryCart);
if ($resultCart) {
$products = []; // salva i dettagli dei prodotti
// calcola importo totale e salva i dati dei prodotti nell'array
while ($row = $resultCart->fetch_assoc()) {
// Dati carrello
$subproductId = $row['subproduct_id'];
$quantity = $row['quantity'];
// Dati sottoprodotto
$price = $row['price'];
$availability = $row['availability'];
$stockQuantity = $row['stock'];
if ($availability == 1 && $cartQuantity <= $stockQuantity) {
// totale parziale per ciascun sottoprodotto nel carrello
$subtotal = $price * $quantity;
$totalPrice += $subtotal;
$productTitle = getProductTitle($subproductId);
$products[] = [
'subproduct_id' => $subproductId,
'title' => $productTitle,
'quantity' => $quantity,
'subtotal' => $subtotal,
'quantityCheck' => $stockQuantity - $quantity
];
} else {
echo "Prodotto con ID $subproductId non disponibile o quantità insufficiente. Sarà escluso dall'ordine.<br>";
}
}
// numero random per il codice ordine
$uniqueOrderNumber = generateUniqueOrderNumber($mysqli);
$orderDetails = $mysqli->real_escape_string($_POST['details']);
$paymentMethod = $mysqli->real_escape_string($_POST['payment_method']);
// Data corrente
$currentDate = date('Y-m-d H:i:s');
// Stato dell'ordine, di default
$orderState = "pending";
// inserisci ordine
$insertOrderQuery = "INSERT INTO orders (shipping_address_id, totalPrice, details, paymentMethod, date, state, number, users_email)
VALUES ('$shippingAddressId', $totalPrice, '$orderDetails', '$paymentMethod', '$currentDate', '$orderState', '$uniqueOrderNumber', '$userEmail')";
if ($mysqli->query($insertOrderQuery)) {
// ID dell'ordine inserito
$orderId = $mysqli->insert_id;
// Aggiungi i prodotti associati all'ordine nella tabella orders_has_products
foreach ($products as $product) {
$subproductId = $product['subproduct_id'];
$quantity = $product['quantity']; // Quantità nel carrello
// Query per inserire i dati nella tabella orders_has_products
$insertOrderHasProductsQuery = "INSERT INTO orders_has_products (order_id, sub_products_id, quantity)
VALUES (?, ?, ?)";
$stmtOrderHasProducts = $mysqli->prepare($insertOrderHasProductsQuery);
$stmtOrderHasProducts->bind_param("iii", $orderId, $subproductId, $quantity);
if ($stmtOrderHasProducts->execute()) {
echo "Prodotto con ID $subproductId inserito correttamente nell'ordine.<br>";
} else {
echo "Errore durante l'inserimento del prodotto con ID $subproductId nell'ordine: " . $stmtOrderHasProducts->error . "<br>";
}
$stmtOrderHasProducts->close();
}
echo "Ordine inserito con successo! Numero ordine: " . $uniqueOrderNumber;
// Recupera i dettagli dell'indirizzo di spedizione selezionato
$addressQuery = "SELECT * FROM shipping_address WHERE id = ?";
$stmtAddress = $mysqli->prepare($addressQuery);
$stmtAddress->bind_param("i", $shippingAddressId);
$stmtAddress->execute();
$resultAddress = $stmtAddress->get_result();
$address = $resultAddress->fetch_assoc();
$stmtAddress->close();
// email
$to = $userEmail;
$subject = 'Conferma Ordine #' . $uniqueOrderNumber;
$message = '<html><body>';
$message .= '<h2>Gentile cliente,</h2>';
$message .= '<p>Grazie per il tuo ordine! Ecco i dettagli:</p>';
$message .= '<h3>Indirizzo di Spedizione</h3>';
$message .= '<p>';
$message .= 'Nome: ' . $address['name'] . '<br>';
$message .= 'Cognome: ' . $address['surname'] . '<br>';
$message .= 'Telefono: ' . $address['phone'] . '<br>';
$message .= 'Provincia: ' . $address['province'] . '<br>';
$message .= 'Città: ' . $address['city'] . '<br>';
$message .= 'Indirizzo: ' . $address['streetAddress'] . '<br>';
$message .= 'CAP: ' . $address['cap'] . '<br>';
$message .= '</p>';
$message .= '<h3>Riepilogo Ordine</h3>';
$message .= '<table border="1">';
$message .= '<tr><th>Prodotto</th><th>Quantità</th><th>Subtotale</th></tr>';
foreach ($products as $product) {
$message .= '<tr>';
$message .= '<td>' . htmlspecialchars($product['title']) . '</td>';
$message .= '<td>' . $product['quantity'] . '</td>';
$message .= '<td>' . priceFormatter($product['subtotal']) . '</td>';
$message .= '</tr>';
}
$message .= '</table>';
$message .= '<p><strong>Totale Ordine:</strong> ' . priceFormatter($totalPrice) . '</p>';
$message .= '<p>Dettagli aggiuntivi: ' . $orderDetails . '</p>';
$message .= '<p>Metodo di Pagamento: ' . $paymentMethod . '</p>';
$message .= '<p>Grazie per aver scelto il nostro negozio!</p>';
$message .= '</body></html>';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <noreply@motorshop.com>' . "\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "Email di conferma inviata con successo.";
} else {
echo "Errore durante l'invio dell'email di conferma.";
}
// svuota il carrello
$deleteCartQuery = "DELETE FROM cart WHERE user_email = '$userEmail'";
if ($mysqli->query($deleteCartQuery)) {
echo "Carrello svuotato con successo.";
foreach ($products as $prod) {
// Verifica se la quantità richiesta è maggiore di 0
if ($prod['quantityCheck'] > 0) {
// quantità disponibile del sottoprodotto
$result = $mysqli->query("SELECT quantity FROM sub_products WHERE id = " . intval($prod['subproduct_id']));
$subProduct = $result->fetch_assoc();
$availableQuantity = $subProduct['quantity'];
// Se la quantità da acquistare è maggiore della quantità disponibile, inserisci solo la quantità disponibile
$quantityToBuy = min(intval($prod['quantity']), $availableQuantity);
// aggiorna la quantità del sottoprodotto
$mysqli->query("UPDATE sub_products SET quantity = quantity - $quantityToBuy WHERE id = " . intval($prod['subproduct_id']));
// Se la quantità disponibile diventa zero, aggiorna la disponibilità a 0
if ($availableQuantity - $quantityToBuy <= 0) {
$mysqli->query("UPDATE sub_products SET availability = 0 WHERE id = " . intval($prod['subproduct_id']));
}
echo "Quantità inserita nell'ordine: $quantityToBuy per il sottoprodotto ID " . $prod['subproduct_id'];
} else {
// Se la quantità da acquistare è zero o negativa, aggiorna direttamente la disponibilità a 0
$mysqli->query("UPDATE sub_products SET quantity = quantity - " . intval($prod['quantity']) . ", availability = 0 WHERE id = " . intval($prod['subproduct_id']));
echo "Quantità zero inserita nell'ordine per il sottoprodotto ID " . $prod['subproduct_id'];
}
echo "Errore durante l'eliminazione dei prodotti dal carrello: " . $mysqli->error;
}
echo json_encode(['success' => 'success']);
} else {
echo "Errore nello svuotamento del carrello.";
}
} else {
echo "Errore durante l'inserimento dell'ordine: 1" . $mysqli->error;
}
} else {
echo "Errore durante la query del carrello: " . $mysqli->error;
}
} else{
echo "Errore: nessun indirizzo di spedizione selezionato.";
}
// generare un numero casuale univoco, di 5 cifre, per l'ordine
function generateUniqueOrderNumber($mysqli) {
$uniqueNumber = mt_rand(10000, 99999);
$query = "SELECT number FROM orders WHERE number = '$uniqueNumber'";
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
// Se il numero è già presente, richiama la funzione per generare un altro numero
return generateUniqueOrderNumber($mysqli);
} else {
return $uniqueNumber;
}
}
// formattazione prezzo
function priceFormatter($price) {
// 2 decimali
return '€ ' . number_format($price, 2);
}
$main->setContent("dynamic", $body->get());
$main->close();
?>