Delete comment

This commit is contained in:
kirill.khorkov
2025-12-16 19:18:03 +03:00
parent 474fe41d41
commit 8a93cf8657
59 changed files with 9767 additions and 10403 deletions

View File

@@ -1,116 +1,112 @@
<?php
session_start();
require_once __DIR__ . '/../config/database.php';
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
echo json_encode(['success' => false, 'message' => 'Требуется авторизация']);
exit();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['product_id'])) {
$product_id = intval($_POST['product_id']);
$quantity = intval($_POST['quantity'] ?? 1);
$user_id = $_SESSION['user_id'] ?? 0;
if ($user_id == 0) {
echo json_encode(['success' => false, 'message' => 'Пользователь не найден']);
exit();
}
$db = Database::getInstance()->getConnection();
try {
// Проверяем наличие товара на складе
$checkStock = $db->prepare("
SELECT stock_quantity, name, price
FROM products
WHERE product_id = ? AND is_available = TRUE
");
$checkStock->execute([$product_id]);
$product = $checkStock->fetch();
if (!$product) {
echo json_encode(['success' => false, 'message' => 'Товар не найден']);
exit();
}
if ($product['stock_quantity'] < $quantity) {
echo json_encode(['success' => false, 'message' => 'Недостаточно товара на складе']);
exit();
}
// Проверяем, есть ли товар уже в корзине пользователя
$checkCart = $db->prepare("
SELECT cart_id, quantity
FROM cart
WHERE user_id = ? AND product_id = ?
");
$checkCart->execute([$user_id, $product_id]);
$cartItem = $checkCart->fetch();
if ($cartItem) {
// Обновляем количество
$newQuantity = $cartItem['quantity'] + $quantity;
// Проверяем общее количество
if ($newQuantity > $product['stock_quantity']) {
echo json_encode(['success' => false, 'message' => 'Превышено доступное количество']);
exit();
}
$updateStmt = $db->prepare("
UPDATE cart
SET quantity = ?, updated_at = CURRENT_TIMESTAMP
WHERE cart_id = ?
");
$updateStmt->execute([$newQuantity, $cartItem['cart_id']]);
} else {
// Добавляем новый товар
$insertStmt = $db->prepare("
INSERT INTO cart (user_id, product_id, quantity)
VALUES (?, ?, ?)
");
$insertStmt->execute([$user_id, $product_id, $quantity]);
}
// Обновляем сессию
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$product_id] = [
'quantity' => $quantity,
'name' => $product['name'],
'price' => $product['price'],
'added_at' => time()
];
}
// Получаем общее количество товаров в корзине
$cartCountStmt = $db->prepare("
SELECT SUM(quantity) as total
FROM cart
WHERE user_id = ?
");
$cartCountStmt->execute([$user_id]);
$cart_count = $cartCountStmt->fetchColumn() ?: 0;
echo json_encode([
'success' => true,
'cart_count' => $cart_count,
'message' => 'Товар добавлен в корзину'
]);
} catch (PDOException $e) {
echo json_encode([
'success' => false,
'message' => 'Ошибка базы данных: ' . $e->getMessage()
]);
}
} else {
echo json_encode(['success' => false, 'message' => 'Неверный запрос']);
}
<?php
session_start();
require_once __DIR__ . '/../config/database.php';
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
echo json_encode(['success' => false, 'message' => 'Требуется авторизация']);
exit();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['product_id'])) {
$product_id = intval($_POST['product_id']);
$quantity = intval($_POST['quantity'] ?? 1);
$user_id = $_SESSION['user_id'] ?? 0;
if ($user_id == 0) {
echo json_encode(['success' => false, 'message' => 'Пользователь не найден']);
exit();
}
$db = Database::getInstance()->getConnection();
try {
$checkStock = $db->prepare("
SELECT stock_quantity, name, price
FROM products
WHERE product_id = ? AND is_available = TRUE
");
$checkStock->execute([$product_id]);
$product = $checkStock->fetch();
if (!$product) {
echo json_encode(['success' => false, 'message' => 'Товар не найден']);
exit();
}
if ($product['stock_quantity'] < $quantity) {
echo json_encode(['success' => false, 'message' => 'Недостаточно товара на складе']);
exit();
}
$checkCart = $db->prepare("
SELECT cart_id, quantity
FROM cart
WHERE user_id = ? AND product_id = ?
");
$checkCart->execute([$user_id, $product_id]);
$cartItem = $checkCart->fetch();
if ($cartItem) {
$newQuantity = $cartItem['quantity'] + $quantity;
if ($newQuantity > $product['stock_quantity']) {
echo json_encode(['success' => false, 'message' => 'Превышено доступное количество']);
exit();
}
$updateStmt = $db->prepare("
UPDATE cart
SET quantity = ?, updated_at = CURRENT_TIMESTAMP
WHERE cart_id = ?
");
$updateStmt->execute([$newQuantity, $cartItem['cart_id']]);
} else {
$insertStmt = $db->prepare("
INSERT INTO cart (user_id, product_id, quantity)
VALUES (?, ?, ?)
");
$insertStmt->execute([$user_id, $product_id, $quantity]);
}
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$product_id] = [
'quantity' => $quantity,
'name' => $product['name'],
'price' => $product['price'],
'added_at' => time()
];
}
$cartCountStmt = $db->prepare("
SELECT SUM(quantity) as total
FROM cart
WHERE user_id = ?
");
$cartCountStmt->execute([$user_id]);
$cart_count = $cartCountStmt->fetchColumn() ?: 0;
echo json_encode([
'success' => true,
'cart_count' => $cart_count,
'message' => 'Товар добавлен в корзину'
]);
} catch (PDOException $e) {
echo json_encode([
'success' => false,
'message' => 'Ошибка базы данных: ' . $e->getMessage()
]);
}
} else {
echo json_encode(['success' => false, 'message' => 'Неверный запрос']);
}
?>

View File

@@ -1,71 +1,68 @@
<?php
// login_handler.php
session_start();
require_once __DIR__ . '/../config/database.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
if (empty($email) || empty($password)) {
echo json_encode(['success' => false, 'message' => 'Заполните все поля']);
exit();
}
$db = Database::getInstance()->getConnection();
try {
// Проверяем пользователя в базе данных
$stmt = $db->prepare("
SELECT user_id, email, password_hash, full_name, phone, city, is_admin, is_active
FROM users
WHERE email = ?
");
$stmt->execute([$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) {
echo json_encode(['success' => false, 'message' => 'Пользователь не найден']);
exit();
}
if (!$user['is_active']) {
echo json_encode(['success' => false, 'message' => 'Аккаунт заблокирован']);
exit();
}
// Проверяем пароль
if (empty($user['password_hash'])) {
echo json_encode(['success' => false, 'message' => 'Ошибка: пароль не найден в базе данных']);
exit();
}
if (!password_verify($password, $user['password_hash'])) {
echo json_encode(['success' => false, 'message' => 'Неверный пароль']);
exit();
}
// Сохраняем в сессию
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['user_email'] = $user['email'];
$_SESSION['full_name'] = $user['full_name'];
$_SESSION['user_phone'] = $user['phone'] ?? '';
$_SESSION['user_city'] = $user['city'] ?? '';
$_SESSION['isLoggedIn'] = true;
$_SESSION['isAdmin'] = (bool)$user['is_admin'];
$_SESSION['login_time'] = time();
// Обновляем время последнего входа
$updateStmt = $db->prepare("UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE user_id = ?");
$updateStmt->execute([$user['user_id']]);
echo json_encode(['success' => true, 'redirect' => 'catalog.php']);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => 'Ошибка базы данных']);
}
} else {
echo json_encode(['success' => false, 'message' => 'Неверный запрос']);
}
<?php
session_start();
require_once __DIR__ . '/../config/database.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
if (empty($email) || empty($password)) {
echo json_encode(['success' => false, 'message' => 'Заполните все поля']);
exit();
}
$db = Database::getInstance()->getConnection();
try {
$stmt = $db->prepare("
SELECT user_id, email, password_hash, full_name, phone, city, is_admin, is_active
FROM users
WHERE email = ?
");
$stmt->execute([$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) {
echo json_encode(['success' => false, 'message' => 'Пользователь не найден']);
exit();
}
if (!$user['is_active']) {
echo json_encode(['success' => false, 'message' => 'Аккаунт заблокирован']);
exit();
}
if (empty($user['password_hash'])) {
echo json_encode(['success' => false, 'message' => 'Ошибка: пароль не найден в базе данных']);
exit();
}
if (!password_verify($password, $user['password_hash'])) {
echo json_encode(['success' => false, 'message' => 'Неверный пароль']);
exit();
}
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['user_email'] = $user['email'];
$_SESSION['full_name'] = $user['full_name'];
$_SESSION['user_phone'] = $user['phone'] ?? '';
$_SESSION['user_city'] = $user['city'] ?? '';
$_SESSION['isLoggedIn'] = true;
$_SESSION['isAdmin'] = (bool)$user['is_admin'];
$_SESSION['login_time'] = time();
$updateStmt = $db->prepare("UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE user_id = ?");
$updateStmt->execute([$user['user_id']]);
echo json_encode(['success' => true, 'redirect' => 'catalog.php']);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => 'Ошибка базы данных']);
}
} else {
echo json_encode(['success' => false, 'message' => 'Неверный запрос']);
}
?>

View File

@@ -1,14 +1,10 @@
<?php
/**
* API для работы с корзиной
* Эндпоинты: add, update, remove, get, count
*/
session_start();
require_once __DIR__ . '/../config/database.php';
header('Content-Type: application/json; charset=utf-8');
// Проверка авторизации
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
echo json_encode(['success' => false, 'message' => 'Требуется авторизация']);
exit();
@@ -24,66 +20,64 @@ try {
case 'add':
$productId = (int)($_POST['product_id'] ?? 0);
$quantity = (int)($_POST['quantity'] ?? 1);
if ($productId <= 0) {
echo json_encode(['success' => false, 'message' => 'Неверный ID товара']);
exit();
}
// Проверяем существование товара
$checkProduct = $db->prepare("SELECT product_id, stock_quantity FROM products WHERE product_id = ? AND is_available = TRUE");
$checkProduct->execute([$productId]);
$product = $checkProduct->fetch();
if (!$product) {
echo json_encode(['success' => false, 'message' => 'Товар не найден']);
exit();
}
// Проверяем, есть ли товар уже в корзине
$checkCart = $db->prepare("SELECT cart_id, quantity FROM cart WHERE user_id = ? AND product_id = ?");
$checkCart->execute([$userId, $productId]);
$cartItem = $checkCart->fetch();
if ($cartItem) {
// Обновляем количество
$newQuantity = $cartItem['quantity'] + $quantity;
$stmt = $db->prepare("UPDATE cart SET quantity = ?, updated_at = CURRENT_TIMESTAMP WHERE cart_id = ?");
$stmt->execute([$newQuantity, $cartItem['cart_id']]);
} else {
// Добавляем новый товар
$stmt = $db->prepare("INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, ?)");
$stmt->execute([$userId, $productId, $quantity]);
}
echo json_encode(['success' => true, 'message' => 'Товар добавлен в корзину']);
break;
case 'update':
$productId = (int)($_POST['product_id'] ?? 0);
$quantity = (int)($_POST['quantity'] ?? 1);
if ($quantity <= 0) {
// Удаляем товар если количество 0
$stmt = $db->prepare("DELETE FROM cart WHERE user_id = ? AND product_id = ?");
$stmt->execute([$userId, $productId]);
} else {
$stmt = $db->prepare("UPDATE cart SET quantity = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND product_id = ?");
$stmt->execute([$quantity, $userId, $productId]);
}
echo json_encode(['success' => true, 'message' => 'Корзина обновлена']);
break;
case 'remove':
$productId = (int)($_POST['product_id'] ?? 0);
$stmt = $db->prepare("DELETE FROM cart WHERE user_id = ? AND product_id = ?");
$stmt->execute([$userId, $productId]);
echo json_encode(['success' => true, 'message' => 'Товар удален из корзины']);
break;
case 'get':
$stmt = $db->prepare("
SELECT c.cart_id, c.product_id, c.quantity, p.name, p.price, p.image_url, p.stock_quantity
@@ -94,13 +88,13 @@ try {
");
$stmt->execute([$userId]);
$items = $stmt->fetchAll();
$total = 0;
foreach ($items as &$item) {
$item['subtotal'] = $item['price'] * $item['quantity'];
$total += $item['subtotal'];
}
echo json_encode([
'success' => true,
'items' => $items,
@@ -108,27 +102,26 @@ try {
'count' => array_sum(array_column($items, 'quantity'))
]);
break;
case 'count':
$stmt = $db->prepare("SELECT COALESCE(SUM(quantity), 0) FROM cart WHERE user_id = ?");
$stmt->execute([$userId]);
$count = $stmt->fetchColumn();
echo json_encode(['success' => true, 'count' => (int)$count]);
break;
case 'clear':
$stmt = $db->prepare("DELETE FROM cart WHERE user_id = ?");
$stmt->execute([$userId]);
echo json_encode(['success' => true, 'message' => 'Корзина очищена']);
break;
default:
echo json_encode(['success' => false, 'message' => 'Неизвестное действие']);
}
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => 'Ошибка базы данных: ' . $e->getMessage()]);
}

View File

@@ -1,62 +1,61 @@
<?php
// get_cart.php
session_start();
require_once __DIR__ . '/../config/database.php';
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
echo json_encode(['success' => false, 'message' => 'Требуется авторизация']);
exit();
}
$user_id = $_SESSION['user_id'] ?? 0;
if ($user_id == 0) {
echo json_encode(['success' => false, 'message' => 'Пользователь не найден']);
exit();
}
$db = Database::getInstance()->getConnection();
try {
// Получаем корзину из БД
$stmt = $db->prepare("
SELECT
c.cart_id,
c.product_id,
c.quantity,
p.name,
p.price,
p.image_url,
p.stock_quantity
FROM cart c
JOIN products p ON c.product_id = p.product_id
WHERE c.user_id = ? AND p.is_available = TRUE
ORDER BY c.created_at DESC
");
$stmt->execute([$user_id]);
$cart_items = $stmt->fetchAll();
// Обновляем сессию
$_SESSION['cart'] = [];
foreach ($cart_items as $item) {
$_SESSION['cart'][$item['product_id']] = [
'quantity' => $item['quantity'],
'name' => $item['name'],
'price' => $item['price'],
'added_at' => time()
];
}
echo json_encode([
'success' => true,
'cart_items' => $cart_items,
'total_items' => count($cart_items)
]);
} catch (PDOException $e) {
echo json_encode([
'success' => false,
'message' => 'Ошибка базы данных: ' . $e->getMessage()
]);
}
<?php
session_start();
require_once __DIR__ . '/../config/database.php';
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
echo json_encode(['success' => false, 'message' => 'Требуется авторизация']);
exit();
}
$user_id = $_SESSION['user_id'] ?? 0;
if ($user_id == 0) {
echo json_encode(['success' => false, 'message' => 'Пользователь не найден']);
exit();
}
$db = Database::getInstance()->getConnection();
try {
$stmt = $db->prepare("
SELECT
c.cart_id,
c.product_id,
c.quantity,
p.name,
p.price,
p.image_url,
p.stock_quantity
FROM cart c
JOIN products p ON c.product_id = p.product_id
WHERE c.user_id = ? AND p.is_available = TRUE
ORDER BY c.created_at DESC
");
$stmt->execute([$user_id]);
$cart_items = $stmt->fetchAll();
$_SESSION['cart'] = [];
foreach ($cart_items as $item) {
$_SESSION['cart'][$item['product_id']] = [
'quantity' => $item['quantity'],
'name' => $item['name'],
'price' => $item['price'],
'added_at' => time()
];
}
echo json_encode([
'success' => true,
'cart_items' => $cart_items,
'total_items' => count($cart_items)
]);
} catch (PDOException $e) {
echo json_encode([
'success' => false,
'message' => 'Ошибка базы данных: ' . $e->getMessage()
]);
}
?>

View File

@@ -1,22 +1,22 @@
<?php
// get_cart_count.php
session_start();
require_once __DIR__ . '/../config/database.php';
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
echo json_encode(['success' => false, 'cart_count' => 0]);
exit();
}
$user_id = $_SESSION['user_id'] ?? 0;
$db = Database::getInstance()->getConnection();
try {
$stmt = $db->prepare("SELECT SUM(quantity) as total FROM cart WHERE user_id = ?");
$stmt->execute([$user_id]);
$cart_count = $stmt->fetchColumn() ?: 0;
echo json_encode(['success' => true, 'cart_count' => $cart_count]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'cart_count' => 0]);
<?php
session_start();
require_once __DIR__ . '/../config/database.php';
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
echo json_encode(['success' => false, 'cart_count' => 0]);
exit();
}
$user_id = $_SESSION['user_id'] ?? 0;
$db = Database::getInstance()->getConnection();
try {
$stmt = $db->prepare("SELECT SUM(quantity) as total FROM cart WHERE user_id = ?");
$stmt->execute([$user_id]);
$cart_count = $stmt->fetchColumn() ?: 0;
echo json_encode(['success' => true, 'cart_count' => $cart_count]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'cart_count' => 0]);
}

View File

@@ -1,33 +1,32 @@
<?php
session_start();
require_once __DIR__ . '/../config/database.php';
// Проверяем авторизацию администратора
if (!isset($_SESSION['isAdmin']) || $_SESSION['isAdmin'] !== true) {
echo json_encode(['success' => false, 'message' => 'Доступ запрещен']);
exit();
}
if (!isset($_GET['id'])) {
echo json_encode(['success' => false, 'message' => 'ID не указан']);
exit();
}
try {
$db = Database::getInstance()->getConnection();
$product_id = $_GET['id'];
$stmt = $db->prepare("SELECT * FROM products WHERE product_id = ?");
$stmt->execute([$product_id]);
$product = $stmt->fetch();
if ($product) {
echo json_encode($product);
} else {
echo json_encode(['success' => false, 'message' => 'Товар не найден']);
}
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => 'Ошибка базы данных: ' . $e->getMessage()]);
}
<?php
session_start();
require_once __DIR__ . '/../config/database.php';
if (!isset($_SESSION['isAdmin']) || $_SESSION['isAdmin'] !== true) {
echo json_encode(['success' => false, 'message' => 'Доступ запрещен']);
exit();
}
if (!isset($_GET['id'])) {
echo json_encode(['success' => false, 'message' => 'ID не указан']);
exit();
}
try {
$db = Database::getInstance()->getConnection();
$product_id = $_GET['id'];
$stmt = $db->prepare("SELECT * FROM products WHERE product_id = ?");
$stmt->execute([$product_id]);
$product = $stmt->fetch();
if ($product) {
echo json_encode($product);
} else {
echo json_encode(['success' => false, 'message' => 'Товар не найден']);
}
} catch (PDOException $e) {
echo json_encode(['success' => false, 'message' => 'Ошибка базы данных: ' . $e->getMessage()]);
}
?>

View File

@@ -1,134 +1,124 @@
<?php
// process_order.php
session_start();
require_once __DIR__ . '/../config/database.php';
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
header('Location: login.php?error=auth_required');
exit();
}
$user_id = $_SESSION['user_id'] ?? 0;
if ($user_id == 0) {
header('Location: login.php?error=user_not_found');
exit();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$db = Database::getInstance()->getConnection();
try {
$db->beginTransaction();
// Получаем данные из формы
$customer_name = $_POST['full_name'] ?? '';
$customer_email = $_POST['email'] ?? '';
$customer_phone = $_POST['phone'] ?? '';
$delivery_address = $_POST['address'] ?? '';
$region = $_POST['region'] ?? '';
$payment_method = $_POST['payment'] ?? 'card';
$delivery_method = $_POST['delivery'] ?? 'courier';
$notes = $_POST['notes'] ?? '';
$discount_amount = floatval($_POST['discount'] ?? 0);
$delivery_cost = floatval($_POST['delivery_price'] ?? 2000);
// Генерируем номер заказа
$order_number = 'ORD-' . date('Ymd-His') . '-' . rand(1000, 9999);
// Получаем корзину пользователя
$cartStmt = $db->prepare("
SELECT
c.product_id,
c.quantity,
p.name,
p.price,
p.stock_quantity
FROM cart c
JOIN products p ON c.product_id = p.product_id
WHERE c.user_id = ?
");
$cartStmt->execute([$user_id]);
$cart_items = $cartStmt->fetchAll();
if (empty($cart_items)) {
throw new Exception('Корзина пуста');
}
// Рассчитываем итоги
$total_amount = 0;
foreach ($cart_items as $item) {
$total_amount += $item['price'] * $item['quantity'];
}
$final_amount = $total_amount - $discount_amount + $delivery_cost;
// Создаем заказ
$orderStmt = $db->prepare("
INSERT INTO orders (
user_id, order_number, total_amount, discount_amount,
delivery_cost, final_amount, status, payment_method,
delivery_method, delivery_address, customer_name,
customer_email, customer_phone, notes
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
RETURNING order_id
");
$orderStmt->execute([
$user_id, $order_number, $total_amount, $discount_amount,
$delivery_cost, $final_amount, 'pending', $payment_method,
$delivery_method, $delivery_address, $customer_name,
$customer_email, $customer_phone, $notes
]);
$order_id = $orderStmt->fetchColumn();
// Добавляем товары в заказ и обновляем остатки
foreach ($cart_items as $item) {
// Добавляем в order_items
$itemStmt = $db->prepare("
INSERT INTO order_items (
order_id, product_id, product_name,
quantity, unit_price, total_price
) VALUES (?, ?, ?, ?, ?, ?)
");
$item_total = $item['price'] * $item['quantity'];
$itemStmt->execute([
$order_id, $item['product_id'], $item['name'],
$item['quantity'], $item['price'], $item_total
]);
// Обновляем остатки на складе
$updateStmt = $db->prepare("
UPDATE products
SET stock_quantity = stock_quantity - ?,
updated_at = CURRENT_TIMESTAMP
WHERE product_id = ?
");
$updateStmt->execute([$item['quantity'], $item['product_id']]);
}
// Очищаем корзину
$clearCartStmt = $db->prepare("DELETE FROM cart WHERE user_id = ?");
$clearCartStmt->execute([$user_id]);
// Очищаем сессию
unset($_SESSION['cart']);
$db->commit();
// Перенаправляем на страницу успеха
header('Location: order_success.php?id=' . $order_id);
exit();
} catch (Exception $e) {
$db->rollBack();
header('Location: checkout.php?error=' . urlencode($e->getMessage()));
exit();
}
} else {
header('Location: checkout.php');
exit();
}
<?php
session_start();
require_once __DIR__ . '/../config/database.php';
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
header('Location: login.php?error=auth_required');
exit();
}
$user_id = $_SESSION['user_id'] ?? 0;
if ($user_id == 0) {
header('Location: login.php?error=user_not_found');
exit();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$db = Database::getInstance()->getConnection();
try {
$db->beginTransaction();
$customer_name = $_POST['full_name'] ?? '';
$customer_email = $_POST['email'] ?? '';
$customer_phone = $_POST['phone'] ?? '';
$delivery_address = $_POST['address'] ?? '';
$region = $_POST['region'] ?? '';
$payment_method = $_POST['payment'] ?? 'card';
$delivery_method = $_POST['delivery'] ?? 'courier';
$notes = $_POST['notes'] ?? '';
$discount_amount = floatval($_POST['discount'] ?? 0);
$delivery_cost = floatval($_POST['delivery_price'] ?? 2000);
$order_number = 'ORD-' . date('Ymd-His') . '-' . rand(1000, 9999);
$cartStmt = $db->prepare("
SELECT
c.product_id,
c.quantity,
p.name,
p.price,
p.stock_quantity
FROM cart c
JOIN products p ON c.product_id = p.product_id
WHERE c.user_id = ?
");
$cartStmt->execute([$user_id]);
$cart_items = $cartStmt->fetchAll();
if (empty($cart_items)) {
throw new Exception('Корзина пуста');
}
$total_amount = 0;
foreach ($cart_items as $item) {
$total_amount += $item['price'] * $item['quantity'];
}
$final_amount = $total_amount - $discount_amount + $delivery_cost;
$orderStmt = $db->prepare("
INSERT INTO orders (
user_id, order_number, total_amount, discount_amount,
delivery_cost, final_amount, status, payment_method,
delivery_method, delivery_address, customer_name,
customer_email, customer_phone, notes
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
RETURNING order_id
");
$orderStmt->execute([
$user_id, $order_number, $total_amount, $discount_amount,
$delivery_cost, $final_amount, 'pending', $payment_method,
$delivery_method, $delivery_address, $customer_name,
$customer_email, $customer_phone, $notes
]);
$order_id = $orderStmt->fetchColumn();
foreach ($cart_items as $item) {
$itemStmt = $db->prepare("
INSERT INTO order_items (
order_id, product_id, product_name,
quantity, unit_price, total_price
) VALUES (?, ?, ?, ?, ?, ?)
");
$item_total = $item['price'] * $item['quantity'];
$itemStmt->execute([
$order_id, $item['product_id'], $item['name'],
$item['quantity'], $item['price'], $item_total
]);
$updateStmt = $db->prepare("
UPDATE products
SET stock_quantity = stock_quantity - ?,
updated_at = CURRENT_TIMESTAMP
WHERE product_id = ?
");
$updateStmt->execute([$item['quantity'], $item['product_id']]);
}
$clearCartStmt = $db->prepare("DELETE FROM cart WHERE user_id = ?");
$clearCartStmt->execute([$user_id]);
unset($_SESSION['cart']);
$db->commit();
header('Location: order_success.php?id=' . $order_id);
exit();
} catch (Exception $e) {
$db->rollBack();
header('Location: checkout.php?error=' . urlencode($e->getMessage()));
exit();
}
} else {
header('Location: checkout.php');
exit();
}
?>

View File

@@ -1,175 +1,162 @@
<?php
// register_handler.php
session_start();
require_once __DIR__ . '/../config/database.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$errors = [];
// Получаем данные из формы
$full_name = trim($_POST['fio'] ?? '');
$city = trim($_POST['city'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$password = $_POST['password'] ?? '';
$confirm_password = $_POST['confirm-password'] ?? '';
// Валидация данных
if (empty($full_name) || strlen($full_name) < 3) {
$errors[] = 'ФИО должно содержать минимум 3 символа';
}
if (empty($city) || strlen($city) < 2) {
$errors[] = 'Введите корректное название города';
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Введите корректный email адрес';
}
if (empty($phone) || !preg_match('/^(\+7|8)[\s-]?\(?\d{3}\)?[\s-]?\d{3}[\s-]?\d{2}[\s-]?\d{2}$/', $phone)) {
$errors[] = 'Введите корректный номер телефона';
}
if (empty($password) || strlen($password) < 6) {
$errors[] = 'Пароль должен содержать минимум 6 символов';
}
if ($password !== $confirm_password) {
$errors[] = 'Пароли не совпадают';
}
// Проверка согласия с условиями
if (!isset($_POST['privacy']) || $_POST['privacy'] !== 'on') {
$errors[] = 'Необходимо согласие с условиями обработки персональных данных';
}
// Если есть ошибки, возвращаем на форму
if (!empty($errors)) {
$_SESSION['registration_errors'] = $errors;
$_SESSION['old_data'] = [
'fio' => $full_name,
'city' => $city,
'email' => $email,
'phone' => $phone
];
header('Location: ../register.php');
exit();
}
// Подключаемся к базе данных
$db = Database::getInstance()->getConnection();
try {
// Проверяем, существует ли пользователь с таким email
$checkStmt = $db->prepare("SELECT user_id FROM users WHERE email = ?");
$checkStmt->execute([$email]);
if ($checkStmt->fetch()) {
$_SESSION['registration_errors'] = ['Пользователь с таким email уже существует'];
$_SESSION['old_data'] = [
'fio' => $full_name,
'city' => $city,
'email' => $email,
'phone' => $phone
];
header('Location: ../register.php');
exit();
}
// Хэшируем пароль
$password_hash = password_hash($password, PASSWORD_DEFAULT);
// Определяем, является ли пользователь администратором
$is_admin = false;
$admin_emails = ['admin@aeterna.ru', 'administrator@aeterna.ru', 'aeterna@mail.ru'];
if (in_array(strtolower($email), $admin_emails)) {
$is_admin = true;
}
// Используем CAST для правильной передачи boolean в PostgreSQL
$stmt = $db->prepare("
INSERT INTO users (email, password_hash, full_name, phone, city, is_admin, is_active)
VALUES (?, ?, ?, ?, ?, CAST(? AS boolean), TRUE)
RETURNING user_id
");
$stmt->execute([
$email,
$password_hash,
$full_name,
$phone,
$city,
$is_admin ? 'true' : 'false' // Строковые значения true/false для CAST
]);
$user_id = $stmt->fetchColumn();
if (!$user_id) {
throw new Exception('Ошибка при создании пользователя: user_id не получен');
}
// Проверяем, что пользователь действительно создался
$verifyStmt = $db->prepare("SELECT user_id, email, password_hash FROM users WHERE user_id = ?");
$verifyStmt->execute([$user_id]);
$verifyUser = $verifyStmt->fetch(PDO::FETCH_ASSOC);
if (!$verifyUser) {
throw new Exception('Ошибка: пользователь не найден после создания');
}
// Проверяем, что пароль сохранился правильно
if (empty($verifyUser['password_hash'])) {
throw new Exception('Ошибка: пароль не сохранен');
}
// Автоматически авторизуем пользователя
$_SESSION['user_id'] = $user_id;
$_SESSION['user_email'] = $email;
$_SESSION['full_name'] = $full_name;
$_SESSION['user_phone'] = $phone;
$_SESSION['user_city'] = $city;
$_SESSION['isLoggedIn'] = true;
$_SESSION['isAdmin'] = (bool)$is_admin;
$_SESSION['login_time'] = time();
// Обновляем время последнего входа
$updateStmt = $db->prepare("UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE user_id = ?");
$updateStmt->execute([$user_id]);
// Перенаправляем на главную или каталог
$_SESSION['registration_success'] = 'Регистрация прошла успешно! ' .
($is_admin ? 'Вы зарегистрированы как администратор.' : 'Добро пожаловать в AETERNA!');
header('Location: ../catalog.php');
exit();
} catch (PDOException $e) {
// Логируем полную ошибку для отладки
error_log("Registration DB Error: " . $e->getMessage());
error_log("SQL State: " . $e->getCode());
error_log("Email: " . $email);
$_SESSION['registration_errors'] = ['Ошибка базы данных: ' . $e->getMessage()];
$_SESSION['old_data'] = [
'fio' => $full_name,
'city' => $city,
'email' => $email,
'phone' => $phone
];
header('Location: ../register.php');
exit();
} catch (Exception $e) {
error_log("Registration Error: " . $e->getMessage());
$_SESSION['registration_errors'] = [$e->getMessage()];
header('Location: ../register.php');
exit();
}
} else {
// Если запрос не POST, перенаправляем на форму регистрации
header('Location: register.php');
exit();
}
<?php
session_start();
require_once __DIR__ . '/../config/database.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$errors = [];
$full_name = trim($_POST['fio'] ?? '');
$city = trim($_POST['city'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$password = $_POST['password'] ?? '';
$confirm_password = $_POST['confirm-password'] ?? '';
if (empty($full_name) || strlen($full_name) < 3) {
$errors[] = 'ФИО должно содержать минимум 3 символа';
}
if (empty($city) || strlen($city) < 2) {
$errors[] = 'Введите корректное название города';
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Введите корректный email адрес';
}
if (empty($phone) || !preg_match('/^(\+7|8)[\s-]?\(?\d{3}\)?[\s-]?\d{3}[\s-]?\d{2}[\s-]?\d{2}$/', $phone)) {
$errors[] = 'Введите корректный номер телефона';
}
if (empty($password) || strlen($password) < 6) {
$errors[] = 'Пароль должен содержать минимум 6 символов';
}
if ($password !== $confirm_password) {
$errors[] = 'Пароли не совпадают';
}
if (!isset($_POST['privacy']) || $_POST['privacy'] !== 'on') {
$errors[] = 'Необходимо согласие с условиями обработки персональных данных';
}
if (!empty($errors)) {
$_SESSION['registration_errors'] = $errors;
$_SESSION['old_data'] = [
'fio' => $full_name,
'city' => $city,
'email' => $email,
'phone' => $phone
];
header('Location: ../register.php');
exit();
}
$db = Database::getInstance()->getConnection();
try {
$checkStmt = $db->prepare("SELECT user_id FROM users WHERE email = ?");
$checkStmt->execute([$email]);
if ($checkStmt->fetch()) {
$_SESSION['registration_errors'] = [ользователь с таким email уже существует'];
$_SESSION['old_data'] = [
'fio' => $full_name,
'city' => $city,
'email' => $email,
'phone' => $phone
];
header('Location: ../register.php');
exit();
}
$password_hash = password_hash($password, PASSWORD_DEFAULT);
$is_admin = false;
$admin_emails = ['admin@aeterna.ru', 'administrator@aeterna.ru', 'aeterna@mail.ru'];
if (in_array(strtolower($email), $admin_emails)) {
$is_admin = true;
}
$stmt = $db->prepare("
INSERT INTO users (email, password_hash, full_name, phone, city, is_admin, is_active)
VALUES (?, ?, ?, ?, ?, CAST(? AS boolean), TRUE)
RETURNING user_id
");
$stmt->execute([
$email,
$password_hash,
$full_name,
$phone,
$city,
$is_admin ? 'true' : 'false'
]);
$user_id = $stmt->fetchColumn();
if (!$user_id) {
throw new Exception('Ошибка при создании пользователя: user_id не получен');
}
$verifyStmt = $db->prepare("SELECT user_id, email, password_hash FROM users WHERE user_id = ?");
$verifyStmt->execute([$user_id]);
$verifyUser = $verifyStmt->fetch(PDO::FETCH_ASSOC);
if (!$verifyUser) {
throw new Exception('Ошибка: пользователь не найден после создания');
}
if (empty($verifyUser['password_hash'])) {
throw new Exception('Ошибка: пароль не сохранен');
}
$_SESSION['user_id'] = $user_id;
$_SESSION['user_email'] = $email;
$_SESSION['full_name'] = $full_name;
$_SESSION['user_phone'] = $phone;
$_SESSION['user_city'] = $city;
$_SESSION['isLoggedIn'] = true;
$_SESSION['isAdmin'] = (bool)$is_admin;
$_SESSION['login_time'] = time();
$updateStmt = $db->prepare("UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE user_id = ?");
$updateStmt->execute([$user_id]);
$_SESSION['registration_success'] = 'Регистрация прошла успешно! ' .
($is_admin ? 'Вы зарегистрированы как администратор.' : 'Добро пожаловать в AETERNA!');
header('Location: ../catalog.php');
exit();
} catch (PDOException $e) {
error_log("Registration DB Error: " . $e->getMessage());
error_log("SQL State: " . $e->getCode());
error_log("Email: " . $email);
$_SESSION['registration_errors'] = ['Ошибка базы данных: ' . $e->getMessage()];
$_SESSION['old_data'] = [
'fio' => $full_name,
'city' => $city,
'email' => $email,
'phone' => $phone
];
header('Location: ../register.php');
exit();
} catch (Exception $e) {
error_log("Registration Error: " . $e->getMessage());
$_SESSION['registration_errors'] = [$e->getMessage()];
header('Location: ../register.php');
exit();
}
} else {
header('Location: register.php');
exit();
}
?>