Delete comment
This commit is contained in:
1399
admin/index.php
1399
admin/index.php
File diff suppressed because it is too large
Load Diff
@@ -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' => 'Неверный запрос']);
|
||||
}
|
||||
?>
|
||||
127
api/auth.php
127
api/auth.php
@@ -1,66 +1,63 @@
|
||||
<?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();
|
||||
|
||||
if (!$user) {
|
||||
echo json_encode(['success' => false, 'message' => 'Пользователь не найден']);
|
||||
exit();
|
||||
}
|
||||
|
||||
if (!$user['is_active']) {
|
||||
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();
|
||||
|
||||
if (!$user) {
|
||||
echo json_encode(['success' => false, 'message' => 'Пользователь не найден']);
|
||||
exit();
|
||||
}
|
||||
|
||||
if (!$user['is_active']) {
|
||||
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' => 'Неверный запрос']);
|
||||
}
|
||||
?>
|
||||
57
api/cart.php
57
api/cart.php
@@ -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()]);
|
||||
}
|
||||
|
||||
|
||||
121
api/get_cart.php
121
api/get_cart.php
@@ -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()
|
||||
]);
|
||||
}
|
||||
?>
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -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()]);
|
||||
}
|
||||
?>
|
||||
@@ -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();
|
||||
}
|
||||
?>
|
||||
@@ -1,182 +1,151 @@
|
||||
<?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;
|
||||
}
|
||||
|
||||
// РАЗНЫЕ ВАРИАНТЫ ДЛЯ ТЕСТИРОВАНИЯ - РАСКОММЕНТИРУЙТЕ НУЖНЫЙ
|
||||
|
||||
// Вариант 1: С явным преобразованием boolean (самый надежный)
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO users (email, password_hash, full_name, phone, city, is_admin)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
RETURNING user_id
|
||||
");
|
||||
|
||||
// Преобразуем boolean в integer для PostgreSQL
|
||||
$stmt->execute([
|
||||
$email,
|
||||
$password_hash,
|
||||
$full_name,
|
||||
$phone,
|
||||
$city,
|
||||
$is_admin ? 1 : 0 // Преобразуем в integer (1 или 0)
|
||||
]);
|
||||
|
||||
// Вариант 2: С использованием CAST в SQL (альтернатива)
|
||||
/*
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO users (email, password_hash, full_name, phone, city, is_admin)
|
||||
VALUES (?, ?, ?, ?, ?, CAST(? AS boolean))
|
||||
RETURNING user_id
|
||||
");
|
||||
|
||||
$stmt->execute([
|
||||
$email,
|
||||
$password_hash,
|
||||
$full_name,
|
||||
$phone,
|
||||
$city,
|
||||
$is_admin ? 'true' : 'false' // Строковые значения true/false
|
||||
]);
|
||||
*/
|
||||
|
||||
$user_id = $stmt->fetchColumn();
|
||||
|
||||
if ($user_id) {
|
||||
// Автоматически авторизуем пользователя
|
||||
$_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'] = $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();
|
||||
} else {
|
||||
throw new Exception('Ошибка при создании пользователя');
|
||||
}
|
||||
|
||||
} 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)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
RETURNING user_id
|
||||
");
|
||||
|
||||
$stmt->execute([
|
||||
$email,
|
||||
$password_hash,
|
||||
$full_name,
|
||||
$phone,
|
||||
$city,
|
||||
$is_admin ? 1 : 0
|
||||
]);
|
||||
|
||||
$user_id = $stmt->fetchColumn();
|
||||
|
||||
if ($user_id) {
|
||||
|
||||
$_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'] = $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();
|
||||
} else {
|
||||
throw new Exception('Ошибка при создании пользователя');
|
||||
}
|
||||
|
||||
} 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();
|
||||
}
|
||||
?>
|
||||
@@ -1,62 +1,61 @@
|
||||
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
/* Стили для сообщений внизу страницы */
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@@ -1,346 +1,306 @@
|
||||
// script.js
|
||||
|
||||
$(document).ready(function() {
|
||||
// Инициализация корзины
|
||||
let cart = {
|
||||
items: [
|
||||
{ id: 1, name: 'Кресло OPPORTUNITY', price: 16999, quantity: 1 },
|
||||
{ id: 2, name: 'Кресло GOLDEN', price: 19999, quantity: 1 },
|
||||
{ id: 3, name: 'Светильник POLET', price: 7999, quantity: 1 }
|
||||
],
|
||||
delivery: 2000,
|
||||
discount: 0
|
||||
};
|
||||
|
||||
// Функция обновления общей суммы
|
||||
function updateTotal() {
|
||||
let productsTotal = 0;
|
||||
let totalCount = 0;
|
||||
|
||||
// Пересчитываем товары
|
||||
$('.products__item').each(function() {
|
||||
const $item = $(this);
|
||||
const price = parseInt($item.data('price'));
|
||||
const quantity = parseInt($item.find('.products__qty-value').text());
|
||||
|
||||
productsTotal += price * quantity;
|
||||
totalCount += quantity;
|
||||
});
|
||||
|
||||
// Обновляем отображение
|
||||
$('.products-total').text(productsTotal + ' ₽');
|
||||
$('.summary-count').text(totalCount);
|
||||
$('.total-count').text(totalCount + ' шт.');
|
||||
$('.cart-count').text(totalCount);
|
||||
|
||||
// Обновляем итоговую сумму
|
||||
const finalTotal = productsTotal + cart.delivery - cart.discount;
|
||||
$('.final-total').text(finalTotal + ' ₽');
|
||||
}
|
||||
|
||||
// Функция валидации email
|
||||
function validateEmail(email) {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(email);
|
||||
}
|
||||
|
||||
// Функция валидации имени (ФИО)
|
||||
function validateFullName(name) {
|
||||
// Проверяем, что имя содержит только буквы, пробелы, дефисы и апострофы
|
||||
const nameRegex = /^[a-zA-Zа-яА-ЯёЁ\s\-']+$/;
|
||||
|
||||
// Проверяем, что имя состоит минимум из 2 слов
|
||||
const words = name.trim().split(/\s+/);
|
||||
|
||||
return nameRegex.test(name) && words.length >= 2;
|
||||
}
|
||||
|
||||
// Функция валидации телефона
|
||||
function validatePhone(phone) {
|
||||
// Российский формат телефона: +7XXXXXXXXXX
|
||||
const phoneRegex = /^\+7\d{10}$/;
|
||||
return phoneRegex.test(phone);
|
||||
}
|
||||
|
||||
// Функция отображения сообщения
|
||||
function showMessage(messageId, duration = 5000) {
|
||||
// Скрываем все сообщения
|
||||
$('.message').hide();
|
||||
|
||||
// Показываем нужное сообщение
|
||||
$(messageId).fadeIn(300);
|
||||
|
||||
// Автоматически скрываем через указанное время
|
||||
if (duration > 0) {
|
||||
setTimeout(() => {
|
||||
$(messageId).fadeOut(300);
|
||||
}, duration);
|
||||
}
|
||||
}
|
||||
|
||||
// Функция показа ошибки приватности
|
||||
function showPrivacyError(show) {
|
||||
if (show) {
|
||||
$('#privacy-error').show();
|
||||
} else {
|
||||
$('#privacy-error').hide();
|
||||
}
|
||||
}
|
||||
|
||||
// Функция отображения ошибки конкретного поля
|
||||
function showFieldError(fieldId, message) {
|
||||
// Убираем старые ошибки
|
||||
$(fieldId).removeClass('error-input');
|
||||
$(fieldId + '-error').remove();
|
||||
|
||||
if (message) {
|
||||
$(fieldId).addClass('error-input');
|
||||
$(fieldId).after('<div class="field-error" id="' + fieldId.replace('#', '') + '-error">' + message + '</div>');
|
||||
}
|
||||
}
|
||||
|
||||
// Валидация поля при потере фокуса с указанием конкретной ошибки
|
||||
$('#fullname').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (value) {
|
||||
if (!validateFullName(value)) {
|
||||
showFieldError('#fullname', 'ФИО должно содержать только буквы и состоять минимум из 2 слов');
|
||||
} else {
|
||||
showFieldError('#fullname', '');
|
||||
}
|
||||
} else {
|
||||
showFieldError('#fullname', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#email').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (value) {
|
||||
if (!validateEmail(value)) {
|
||||
showFieldError('#email', 'Введите корректный email адрес (например: example@mail.ru)');
|
||||
} else {
|
||||
showFieldError('#email', '');
|
||||
}
|
||||
} else {
|
||||
showFieldError('#email', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#phone').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (value) {
|
||||
if (!validatePhone(value)) {
|
||||
showFieldError('#phone', 'Введите номер в формате +7XXXXXXXXXX (10 цифр после +7)');
|
||||
} else {
|
||||
showFieldError('#phone', '');
|
||||
}
|
||||
} else {
|
||||
showFieldError('#phone', '');
|
||||
}
|
||||
});
|
||||
|
||||
// Валидация обязательных полей
|
||||
$('#region').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (!value) {
|
||||
showFieldError('#region', 'Укажите регион доставки');
|
||||
} else {
|
||||
showFieldError('#region', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#address').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (!value) {
|
||||
showFieldError('#address', 'Укажите адрес доставки (улица, дом, квартира)');
|
||||
} else {
|
||||
showFieldError('#address', '');
|
||||
}
|
||||
});
|
||||
|
||||
// Очистка ошибки при начале ввода
|
||||
$('.form__input').on('input', function() {
|
||||
const fieldId = '#' + $(this).attr('id');
|
||||
showFieldError(fieldId, '');
|
||||
});
|
||||
|
||||
// Обработчик увеличения количества
|
||||
$('.products__qty-btn.plus').click(function() {
|
||||
const $qtyValue = $(this).siblings('.products__qty-value');
|
||||
let quantity = parseInt($qtyValue.text());
|
||||
$qtyValue.text(quantity + 1);
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
// Обработчик уменьшения количества
|
||||
$('.products__qty-btn.minus').click(function() {
|
||||
const $qtyValue = $(this).siblings('.products__qty-value');
|
||||
let quantity = parseInt($qtyValue.text());
|
||||
if (quantity > 1) {
|
||||
$qtyValue.text(quantity - 1);
|
||||
updateTotal();
|
||||
}
|
||||
});
|
||||
|
||||
// Обработчик удаления товара
|
||||
$('.remove-from-cart').click(function() {
|
||||
const $productItem = $(this).closest('.products__item');
|
||||
$productItem.fadeOut(300, function() {
|
||||
$(this).remove();
|
||||
updateTotal();
|
||||
|
||||
// Показываем сообщение, если корзина пуста
|
||||
if ($('.products__item').length === 0) {
|
||||
$('.products__list').html('<div class="empty-cart">Корзина пуста</div>');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Обработчик применения промокода
|
||||
$('.promo__btn').click(function() {
|
||||
const promoCode = $('.promo__input').val().toUpperCase();
|
||||
|
||||
if (promoCode === 'SALE10') {
|
||||
cart.discount = Math.round(parseInt($('.products-total').text()) * 0.1);
|
||||
$('.discount-total').text(cart.discount + ' ₽');
|
||||
showMessage('#form-error', 3000);
|
||||
$('#form-error').text('Промокод применен! Скидка 10%').removeClass('error').addClass('success');
|
||||
} else if (promoCode === 'FREE') {
|
||||
cart.delivery = 0;
|
||||
$('.delivery-price').text('0 ₽');
|
||||
showMessage('#form-error', 3000);
|
||||
$('#form-error').text('Промокод применен! Бесплатная доставка').removeClass('error').addClass('success');
|
||||
} else if (promoCode) {
|
||||
showMessage('#form-error', 3000);
|
||||
$('#form-error').text('Промокод недействителен').removeClass('success').addClass('error');
|
||||
}
|
||||
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
// Обработчик выбора доставки
|
||||
$('input[name="delivery"]').change(function() {
|
||||
if ($(this).val() === 'pickup') {
|
||||
cart.delivery = 0;
|
||||
$('.delivery-price').text('0 ₽');
|
||||
} else {
|
||||
cart.delivery = 2000;
|
||||
$('.delivery-price').text('2000 ₽');
|
||||
}
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
// Функция проверки всех полей формы
|
||||
function validateForm() {
|
||||
let isValid = true;
|
||||
let errorMessages = [];
|
||||
|
||||
// Очищаем все старые ошибки
|
||||
$('.field-error').remove();
|
||||
$('.form__input').removeClass('error-input');
|
||||
|
||||
// Проверка обязательных полей
|
||||
const requiredFields = [
|
||||
{
|
||||
id: '#fullname',
|
||||
value: $('#fullname').val().trim(),
|
||||
validator: validateFullName,
|
||||
required: true,
|
||||
message: 'ФИО должно содержать только буквы и состоять минимум из 2 слов'
|
||||
},
|
||||
{
|
||||
id: '#phone',
|
||||
value: $('#phone').val().trim(),
|
||||
validator: validatePhone,
|
||||
required: true,
|
||||
message: 'Введите корректный номер телефона в формате +7XXXXXXXXXX'
|
||||
},
|
||||
{
|
||||
id: '#email',
|
||||
value: $('#email').val().trim(),
|
||||
validator: validateEmail,
|
||||
required: true,
|
||||
message: 'Введите корректный email адрес'
|
||||
},
|
||||
{
|
||||
id: '#region',
|
||||
value: $('#region').val().trim(),
|
||||
validator: (val) => val.length > 0,
|
||||
required: true,
|
||||
message: 'Поле "Регион" обязательно для заполнения'
|
||||
},
|
||||
{
|
||||
id: '#address',
|
||||
value: $('#address').val().trim(),
|
||||
validator: (val) => val.length > 0,
|
||||
required: true,
|
||||
message: 'Поле "Адрес" обязательно для заполнения'
|
||||
}
|
||||
];
|
||||
|
||||
// Проверяем каждое поле
|
||||
requiredFields.forEach(field => {
|
||||
if (field.required && (!field.value || !field.validator(field.value))) {
|
||||
isValid = false;
|
||||
errorMessages.push(field.message);
|
||||
showFieldError(field.id, field.message);
|
||||
}
|
||||
});
|
||||
|
||||
// Проверка согласия на обработку данных
|
||||
if (!$('#privacy-checkbox').is(':checked')) {
|
||||
isValid = false;
|
||||
showPrivacyError(true);
|
||||
errorMessages.push('Необходимо согласие на обработку персональных данных');
|
||||
} else {
|
||||
showPrivacyError(false);
|
||||
}
|
||||
|
||||
// Показываем общее сообщение, если есть ошибки
|
||||
if (!isValid && errorMessages.length > 0) {
|
||||
showMessage('#form-error', 5000);
|
||||
$('#form-error').text('Исправьте следующие ошибки: ' + errorMessages.join('; ')).removeClass('success').addClass('error');
|
||||
|
||||
// Прокручиваем к первой ошибке
|
||||
$('html, body').animate({
|
||||
scrollTop: $('.error-input').first().offset().top - 100
|
||||
}, 500);
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
// Обработчик оформления заказа
|
||||
$('#submit-order').click(function() {
|
||||
// Проверка валидации всех полей
|
||||
if (!validateForm()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Симуляция отправки заказа
|
||||
$(this).prop('disabled', true).text('ОБРАБОТКА...');
|
||||
|
||||
setTimeout(() => {
|
||||
showMessage('#order-success', 5000);
|
||||
$(this).prop('disabled', false).text('ОФОРМИТЬ ЗАКАЗ');
|
||||
|
||||
// Здесь можно добавить редирект на страницу благодарности
|
||||
// window.location.href = 'спасибо.html';
|
||||
}, 2000);
|
||||
});
|
||||
|
||||
// Маска для телефона
|
||||
$('#phone').on('input', function() {
|
||||
let phone = $(this).val().replace(/\D/g, '');
|
||||
if (phone.length > 0) {
|
||||
if (phone[0] !== '7' && phone[0] !== '8') {
|
||||
phone = '7' + phone;
|
||||
}
|
||||
phone = '+7' + phone.substring(1, 11);
|
||||
$(this).val(phone);
|
||||
}
|
||||
});
|
||||
|
||||
// Инициализация при загрузке
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
$(document).ready(function() {
|
||||
|
||||
let cart = {
|
||||
items: [
|
||||
{ id: 1, name: 'Кресло OPPORTUNITY', price: 16999, quantity: 1 },
|
||||
{ id: 2, name: 'Кресло GOLDEN', price: 19999, quantity: 1 },
|
||||
{ id: 3, name: 'Светильник POLET', price: 7999, quantity: 1 }
|
||||
],
|
||||
delivery: 2000,
|
||||
discount: 0
|
||||
};
|
||||
|
||||
function updateTotal() {
|
||||
let productsTotal = 0;
|
||||
let totalCount = 0;
|
||||
|
||||
$('.products__item').each(function() {
|
||||
const $item = $(this);
|
||||
const price = parseInt($item.data('price'));
|
||||
const quantity = parseInt($item.find('.products__qty-value').text());
|
||||
|
||||
productsTotal += price * quantity;
|
||||
totalCount += quantity;
|
||||
});
|
||||
|
||||
$('.products-total').text(productsTotal + ' ₽');
|
||||
$('.summary-count').text(totalCount);
|
||||
$('.total-count').text(totalCount + ' шт.');
|
||||
$('.cart-count').text(totalCount);
|
||||
|
||||
const finalTotal = productsTotal + cart.delivery - cart.discount;
|
||||
$('.final-total').text(finalTotal + ' ₽');
|
||||
}
|
||||
|
||||
function validateEmail(email) {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(email);
|
||||
}
|
||||
|
||||
function validateFullName(name) {
|
||||
|
||||
const nameRegex = /^[a-zA-Zа-яА-ЯёЁ\s\-']+$/;
|
||||
|
||||
const words = name.trim().split(/\s+/);
|
||||
|
||||
return nameRegex.test(name) && words.length >= 2;
|
||||
}
|
||||
|
||||
function validatePhone(phone) {
|
||||
const phoneRegex = /^\+7\d{10}$/;
|
||||
return phoneRegex.test(phone);
|
||||
}
|
||||
|
||||
function showMessage(messageId, duration = 5000) {
|
||||
$('.message').hide();
|
||||
|
||||
$(messageId).fadeIn(300);
|
||||
|
||||
if (duration > 0) {
|
||||
setTimeout(() => {
|
||||
$(messageId).fadeOut(300);
|
||||
}, duration);
|
||||
}
|
||||
}
|
||||
|
||||
function showPrivacyError(show) {
|
||||
if (show) {
|
||||
$('#privacy-error').show();
|
||||
} else {
|
||||
$('#privacy-error').hide();
|
||||
}
|
||||
}
|
||||
|
||||
function showFieldError(fieldId, message) {
|
||||
$(fieldId).removeClass('error-input');
|
||||
$(fieldId + '-error').remove();
|
||||
|
||||
if (message) {
|
||||
$(fieldId).addClass('error-input');
|
||||
$(fieldId).after('<div class="field-error" id="' + fieldId.replace('#', '') + '-error">' + message + '</div>');
|
||||
}
|
||||
}
|
||||
|
||||
$('#fullname').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (value) {
|
||||
if (!validateFullName(value)) {
|
||||
showFieldError('#fullname', 'ФИО должно содержать только буквы и состоять минимум из 2 слов');
|
||||
} else {
|
||||
showFieldError('#fullname', '');
|
||||
}
|
||||
} else {
|
||||
showFieldError('#fullname', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#email').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (value) {
|
||||
if (!validateEmail(value)) {
|
||||
showFieldError('#email', 'Введите корректный email адрес (например: example@mail.ru)');
|
||||
} else {
|
||||
showFieldError('#email', '');
|
||||
}
|
||||
} else {
|
||||
showFieldError('#email', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#phone').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (value) {
|
||||
if (!validatePhone(value)) {
|
||||
showFieldError('#phone', 'Введите номер в формате +7XXXXXXXXXX (10 цифр после +7)');
|
||||
} else {
|
||||
showFieldError('#phone', '');
|
||||
}
|
||||
} else {
|
||||
showFieldError('#phone', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#region').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (!value) {
|
||||
showFieldError('#region', 'Укажите регион доставки');
|
||||
} else {
|
||||
showFieldError('#region', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#address').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (!value) {
|
||||
showFieldError('#address', 'Укажите адрес доставки (улица, дом, квартира)');
|
||||
} else {
|
||||
showFieldError('#address', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('.form__input').on('input', function() {
|
||||
const fieldId = '#' + $(this).attr('id');
|
||||
showFieldError(fieldId, '');
|
||||
});
|
||||
|
||||
$('.products__qty-btn.plus').click(function() {
|
||||
const $qtyValue = $(this).siblings('.products__qty-value');
|
||||
let quantity = parseInt($qtyValue.text());
|
||||
$qtyValue.text(quantity + 1);
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
$('.products__qty-btn.minus').click(function() {
|
||||
const $qtyValue = $(this).siblings('.products__qty-value');
|
||||
let quantity = parseInt($qtyValue.text());
|
||||
if (quantity > 1) {
|
||||
$qtyValue.text(quantity - 1);
|
||||
updateTotal();
|
||||
}
|
||||
});
|
||||
|
||||
$('.remove-from-cart').click(function() {
|
||||
const $productItem = $(this).closest('.products__item');
|
||||
$productItem.fadeOut(300, function() {
|
||||
$(this).remove();
|
||||
updateTotal();
|
||||
|
||||
if ($('.products__item').length === 0) {
|
||||
$('.products__list').html('<div class="empty-cart">Корзина пуста</div>');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$('.promo__btn').click(function() {
|
||||
const promoCode = $('.promo__input').val().toUpperCase();
|
||||
|
||||
if (promoCode === 'SALE10') {
|
||||
cart.discount = Math.round(parseInt($('.products-total').text()) * 0.1);
|
||||
$('.discount-total').text(cart.discount + ' ₽');
|
||||
showMessage('#form-error', 3000);
|
||||
$('#form-error').text('Промокод применен! Скидка 10%').removeClass('error').addClass('success');
|
||||
} else if (promoCode === 'FREE') {
|
||||
cart.delivery = 0;
|
||||
$('.delivery-price').text('0 ₽');
|
||||
showMessage('#form-error', 3000);
|
||||
$('#form-error').text('Промокод применен! Бесплатная доставка').removeClass('error').addClass('success');
|
||||
} else if (promoCode) {
|
||||
showMessage('#form-error', 3000);
|
||||
$('#form-error').text('Промокод недействителен').removeClass('success').addClass('error');
|
||||
}
|
||||
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
$('input[name="delivery"]').change(function() {
|
||||
if ($(this).val() === 'pickup') {
|
||||
cart.delivery = 0;
|
||||
$('.delivery-price').text('0 ₽');
|
||||
} else {
|
||||
cart.delivery = 2000;
|
||||
$('.delivery-price').text('2000 ₽');
|
||||
}
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
function validateForm() {
|
||||
let isValid = true;
|
||||
let errorMessages = [];
|
||||
|
||||
$('.field-error').remove();
|
||||
$('.form__input').removeClass('error-input');
|
||||
|
||||
const requiredFields = [
|
||||
{
|
||||
id: '#fullname',
|
||||
value: $('#fullname').val().trim(),
|
||||
validator: validateFullName,
|
||||
required: true,
|
||||
message: 'ФИО должно содержать только буквы и состоять минимум из 2 слов'
|
||||
},
|
||||
{
|
||||
id: '#phone',
|
||||
value: $('#phone').val().trim(),
|
||||
validator: validatePhone,
|
||||
required: true,
|
||||
message: 'Введите корректный номер телефона в формате +7XXXXXXXXXX'
|
||||
},
|
||||
{
|
||||
id: '#email',
|
||||
value: $('#email').val().trim(),
|
||||
validator: validateEmail,
|
||||
required: true,
|
||||
message: 'Введите корректный email адрес'
|
||||
},
|
||||
{
|
||||
id: '#region',
|
||||
value: $('#region').val().trim(),
|
||||
validator: (val) => val.length > 0,
|
||||
required: true,
|
||||
message: 'Поле "Регион" обязательно для заполнения'
|
||||
},
|
||||
{
|
||||
id: '#address',
|
||||
value: $('#address').val().trim(),
|
||||
validator: (val) => val.length > 0,
|
||||
required: true,
|
||||
message: 'Поле "Адрес" обязательно для заполнения'
|
||||
}
|
||||
];
|
||||
|
||||
requiredFields.forEach(field => {
|
||||
if (field.required && (!field.value || !field.validator(field.value))) {
|
||||
isValid = false;
|
||||
errorMessages.push(field.message);
|
||||
showFieldError(field.id, field.message);
|
||||
}
|
||||
});
|
||||
|
||||
if (!$('#privacy-checkbox').is(':checked')) {
|
||||
isValid = false;
|
||||
showPrivacyError(true);
|
||||
errorMessages.push('Необходимо согласие на обработку персональных данных');
|
||||
} else {
|
||||
showPrivacyError(false);
|
||||
}
|
||||
|
||||
if (!isValid && errorMessages.length > 0) {
|
||||
showMessage('#form-error', 5000);
|
||||
$('#form-error').text('Исправьте следующие ошибки: ' + errorMessages.join('; ')).removeClass('success').addClass('error');
|
||||
|
||||
$('html, body').animate({
|
||||
scrollTop: $('.error-input').first().offset().top - 100
|
||||
}, 500);
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
$('#submit-order').click(function() {
|
||||
if (!validateForm()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$(this).prop('disabled', true).text('ОБРАБОТКА...');
|
||||
|
||||
setTimeout(() => {
|
||||
showMessage('#order-success', 5000);
|
||||
$(this).prop('disabled', false).text('ОФОРМИТЬ ЗАКАЗ');
|
||||
|
||||
}, 2000);
|
||||
});
|
||||
|
||||
$('#phone').on('input', function() {
|
||||
let phone = $(this).val().replace(/\D/g, '');
|
||||
if (phone.length > 0) {
|
||||
if (phone[0] !== '7' && phone[0] !== '8') {
|
||||
phone = '7' + phone;
|
||||
}
|
||||
phone = '+7' + phone.substring(1, 11);
|
||||
$(this).val(phone);
|
||||
}
|
||||
});
|
||||
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
@@ -1,384 +1,348 @@
|
||||
$(document).ready(function() {
|
||||
// Функции для отображения сообщений
|
||||
function showMessage(type, text) {
|
||||
const messageId = type + 'Message';
|
||||
const $message = $('#' + messageId);
|
||||
$message.text(text).fadeIn(300);
|
||||
setTimeout(() => {
|
||||
$message.fadeOut(300);
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
// Проверка, является ли email администратора
|
||||
function isAdminEmail(email) {
|
||||
const adminEmails = ['admin@aeterna.ru', 'administrator@aeterna.ru', 'aeterna@mail.ru'];
|
||||
return adminEmails.includes(email.toLowerCase());
|
||||
}
|
||||
|
||||
// Валидация ФИО (без цифр)
|
||||
function validateFIO(fio) {
|
||||
const words = fio.trim().split(/\s+/);
|
||||
// Проверяем, что минимум 2 слова и нет цифр
|
||||
const hasNoDigits = !/\d/.test(fio);
|
||||
return words.length >= 2 && words.every(word => word.length >= 2) && hasNoDigits;
|
||||
}
|
||||
|
||||
// Валидация города
|
||||
function validateCity(city) {
|
||||
return city.trim().length >= 2 && /^[а-яА-ЯёЁ\s-]+$/.test(city);
|
||||
}
|
||||
|
||||
// Валидация email
|
||||
function validateEmail(email) {
|
||||
const localPart = email.split('@')[0];
|
||||
|
||||
// Проверка на кириллические символы перед @
|
||||
if (/[а-яА-ЯёЁ]/.test(localPart)) {
|
||||
showError('email', 'В тексте перед знаком "@" не должно быть кириллических символов');
|
||||
return false;
|
||||
}
|
||||
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
showError('email', 'Введите корректный email адрес');
|
||||
return false;
|
||||
}
|
||||
|
||||
hideError('email');
|
||||
return true;
|
||||
}
|
||||
|
||||
// Валидация телефона
|
||||
function validatePhone(phone) {
|
||||
const phoneRegex = /^(\+7|8)[\s-]?\(?\d{3}\)?[\s-]?\d{3}[\s-]?\d{2}[\s-]?\d{2}$/;
|
||||
return phoneRegex.test(phone.replace(/\s/g, ''));
|
||||
}
|
||||
|
||||
// Валидация пароля
|
||||
function validatePassword(password) {
|
||||
return password.length >= 6;
|
||||
}
|
||||
|
||||
// Показать/скрыть ошибку
|
||||
function showError(fieldId, message) {
|
||||
$('#' + fieldId).addClass('error');
|
||||
$('#' + fieldId + '-error').text(message).show();
|
||||
}
|
||||
|
||||
function hideError(fieldId) {
|
||||
$('#' + fieldId).removeClass('error');
|
||||
$('#' + fieldId + '-error').hide();
|
||||
}
|
||||
|
||||
// Валидация формы
|
||||
function validateForm() {
|
||||
let isValid = true;
|
||||
|
||||
// Валидация ФИО
|
||||
const fio = $('#fio').val();
|
||||
if (!validateFIO(fio)) {
|
||||
if (/\d/.test(fio)) {
|
||||
showError('fio', 'ФИО не должно содержать цифры');
|
||||
} else {
|
||||
showError('fio', 'ФИО должно содержать минимум 2 слова (каждое от 2 символов)');
|
||||
}
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('fio');
|
||||
}
|
||||
|
||||
// Валидация города
|
||||
const city = $('#city').val();
|
||||
if (!validateCity(city)) {
|
||||
showError('city', 'Укажите корректное название города (только русские буквы)');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('city');
|
||||
}
|
||||
|
||||
// Валидация email
|
||||
const email = $('#email').val();
|
||||
if (!validateEmail(email)) {
|
||||
showError('email', 'Введите корректный email адрес');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('email');
|
||||
}
|
||||
|
||||
// Валидация телефона
|
||||
const phone = $('#phone').val();
|
||||
if (!validatePhone(phone)) {
|
||||
showError('phone', 'Введите номер в формате: +7(912)999-12-23');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('phone');
|
||||
}
|
||||
|
||||
// Валидация пароля
|
||||
const password = $('#password').val();
|
||||
if (!validatePassword(password)) {
|
||||
showError('password', 'Пароль должен содержать минимум 6 символов');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('password');
|
||||
}
|
||||
|
||||
// Проверка совпадения паролей
|
||||
const confirmPassword = $('#confirm-password').val();
|
||||
if (password !== confirmPassword) {
|
||||
showError('confirm-password', 'Пароли не совпадают');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('confirm-password');
|
||||
}
|
||||
|
||||
// Проверка согласия с условиями
|
||||
if (!$('#privacy').is(':checked')) {
|
||||
$('#privacy-error').show();
|
||||
isValid = false;
|
||||
} else {
|
||||
$('#privacy-error').hide();
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
// Реальная валидация при вводе
|
||||
$('input').on('blur', function() {
|
||||
const fieldId = $(this).attr('id');
|
||||
const value = $(this).val();
|
||||
|
||||
switch(fieldId) {
|
||||
case 'fio':
|
||||
if (!validateFIO(value)) {
|
||||
if (/\d/.test(value)) {
|
||||
showError(fieldId, 'ФИО не должно содержать цифры');
|
||||
} else {
|
||||
showError(fieldId, 'ФИО должно содержать минимум 2 слова');
|
||||
}
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'city':
|
||||
if (!validateCity(value)) {
|
||||
showError(fieldId, 'Укажите корректное название города');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'email':
|
||||
if (!validateEmail(value)) {
|
||||
showError(fieldId, 'Введите корректный email адрес');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'phone':
|
||||
if (!validatePhone(value)) {
|
||||
showError(fieldId, 'Введите номер в формате: +7(912)999-12-23');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'password':
|
||||
if (!validatePassword(value)) {
|
||||
showError(fieldId, 'Пароль должен содержать минимум 6 символов');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'confirm-password':
|
||||
const password = $('#password').val();
|
||||
if (value !== password) {
|
||||
showError(fieldId, 'Пароли не совпадают');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
// Обработка отправки формы
|
||||
$('#registrationForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
if (validateForm()) {
|
||||
const email = $('#email').val();
|
||||
const isAdmin = isAdminEmail(email);
|
||||
|
||||
// Сохраняем данные пользователя в localStorage
|
||||
const userData = {
|
||||
email: email,
|
||||
fio: $('#fio').val(),
|
||||
phone: $('#phone').val(),
|
||||
isAdmin: isAdmin,
|
||||
registered: new Date().toISOString()
|
||||
};
|
||||
|
||||
localStorage.setItem('userData', JSON.stringify(userData));
|
||||
localStorage.setItem('isLoggedIn', 'true');
|
||||
localStorage.setItem('isAdmin', isAdmin.toString());
|
||||
|
||||
// Эмуляция успешной регистрации
|
||||
showMessage('success', 'Регистрация прошла успешно! ' +
|
||||
(isAdmin ? 'Вы зарегистрированы как администратор.' : 'Добро пожаловать в AETERNA!'));
|
||||
|
||||
setTimeout(() => {
|
||||
// Перенаправление на главную страницу
|
||||
window.location.href = 'cite_mebel.php';
|
||||
}, 2000);
|
||||
} else {
|
||||
showMessage('error', 'Пожалуйста, исправьте ошибки в форме');
|
||||
}
|
||||
});
|
||||
|
||||
// Плавная прокрутка к якорям
|
||||
$('a[href^="#"]').on('click', function(event) {
|
||||
var target = $(this.getAttribute('href'));
|
||||
if (target.length) {
|
||||
event.preventDefault();
|
||||
$('html, body').stop().animate({
|
||||
scrollTop: target.offset().top
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
|
||||
// Переключение между регистрацией и входом
|
||||
$('.login-btn').on('click', function() {
|
||||
showMessage('warning', 'Переход к форме входа...');
|
||||
setTimeout(() => {
|
||||
window.location.href = 'вход.php';
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
// Обработка ссылки "Сменить пароль"
|
||||
$('.password-link').on('click', function(e) {
|
||||
e.preventDefault();
|
||||
showMessage('warning', 'Функция смены пароля будет доступна после регистрации');
|
||||
});
|
||||
|
||||
// Маска для телефона
|
||||
$('#phone').on('input', function() {
|
||||
let value = $(this).val().replace(/\D/g, '');
|
||||
if (value.startsWith('7') || value.startsWith('8')) {
|
||||
value = value.substring(1);
|
||||
}
|
||||
if (value.length > 0) {
|
||||
value = '+7(' + value;
|
||||
if (value.length > 6) value = value.substring(0, 6) + ')' + value.substring(6);
|
||||
if (value.length > 10) value = value.substring(0, 10) + '-' + value.substring(10);
|
||||
if (value.length > 13) value = value.substring(0, 13) + '-' + value.substring(13);
|
||||
if (value.length > 16) value = value.substring(0, 16);
|
||||
}
|
||||
$(this).val(value);
|
||||
});
|
||||
|
||||
// Запрет ввода цифр в поле ФИО
|
||||
$('#fio').on('input', function() {
|
||||
let value = $(this).val();
|
||||
// Удаляем цифры из значения
|
||||
value = value.replace(/\d/g, '');
|
||||
$(this).val(value);
|
||||
});
|
||||
});
|
||||
|
||||
// Для входа (файл вход.html)
|
||||
$(document).ready(function() {
|
||||
// Проверяем, если пользователь уже вошел
|
||||
if (localStorage.getItem('isLoggedIn') === 'true') {
|
||||
const userData = JSON.parse(localStorage.getItem('userData') || '{}');
|
||||
if (userData.email) {
|
||||
$('#login-email').val(userData.email);
|
||||
}
|
||||
}
|
||||
|
||||
// Функция проверки пароля администратора
|
||||
function checkAdminPassword(email, password) {
|
||||
// Административные аккаунты
|
||||
const adminAccounts = {
|
||||
'admin@aeterna.ru': 'admin123',
|
||||
'administrator@aeterna.ru': 'admin123',
|
||||
'aeterna@mail.ru': 'admin123'
|
||||
};
|
||||
|
||||
return adminAccounts[email.toLowerCase()] === password;
|
||||
}
|
||||
|
||||
// Валидация формы входа
|
||||
$('#loginForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
let isValid = true;
|
||||
const email = $('#login-email').val();
|
||||
const password = $('#login-password').val();
|
||||
|
||||
// Валидация email
|
||||
if (!isValidEmail(email)) {
|
||||
$('#email-error').show();
|
||||
isValid = false;
|
||||
} else {
|
||||
$('#email-error').hide();
|
||||
}
|
||||
|
||||
// Валидация пароля
|
||||
if (password.length < 6) {
|
||||
$('#password-error').show();
|
||||
isValid = false;
|
||||
} else {
|
||||
$('#password-error').hide();
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
// Здесь обычно отправка данных на сервер
|
||||
showMessage('success', 'Вы успешно вошли в систему!');
|
||||
|
||||
// Перенаправление на главную страницу через 1.5 секунды
|
||||
setTimeout(function() {
|
||||
window.location.href = 'cite_mebel.php';
|
||||
}, 1500);
|
||||
}
|
||||
});
|
||||
|
||||
// Функция показа сообщений
|
||||
function showMessage(type, text) {
|
||||
const messageId = type + 'Message';
|
||||
const $message = $('#' + messageId);
|
||||
|
||||
$message.text(text).show();
|
||||
|
||||
setTimeout(function() {
|
||||
$message.fadeOut();
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Скрываем сообщения об ошибках при фокусе на полях
|
||||
$('input').on('focus', function() {
|
||||
$(this).next('.error-message').hide();
|
||||
});
|
||||
|
||||
// Обработка чекбокса "Запомнить меня"
|
||||
$('#remember').on('change', function() {
|
||||
if ($(this).is(':checked')) {
|
||||
const email = $('#login-email').val();
|
||||
if (email) {
|
||||
localStorage.setItem('rememberedEmail', email);
|
||||
}
|
||||
} else {
|
||||
localStorage.removeItem('rememberedEmail');
|
||||
}
|
||||
});
|
||||
|
||||
// Автозаполнение email, если пользователь выбрал "Запомнить меня"
|
||||
const rememberedEmail = localStorage.getItem('rememberedEmail');
|
||||
if (rememberedEmail) {
|
||||
$('#login-email').val(rememberedEmail);
|
||||
$('#remember').prop('checked', true);
|
||||
}
|
||||
|
||||
// Обработка ссылки "Забыли пароль?"
|
||||
$('.forgot-password').on('click', function(e) {
|
||||
e.preventDefault();
|
||||
showMessage('info', 'Для восстановления пароля обратитесь к администратору');
|
||||
});
|
||||
});
|
||||
$(document).ready(function() {
|
||||
|
||||
function showMessage(type, text) {
|
||||
const messageId = type + 'Message';
|
||||
const $message = $('#' + messageId);
|
||||
$message.text(text).fadeIn(300);
|
||||
setTimeout(() => {
|
||||
$message.fadeOut(300);
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
function isAdminEmail(email) {
|
||||
const adminEmails = ['admin@aeterna.ru', 'administrator@aeterna.ru', 'aeterna@mail.ru'];
|
||||
return adminEmails.includes(email.toLowerCase());
|
||||
}
|
||||
|
||||
function validateFIO(fio) {
|
||||
const words = fio.trim().split(/\s+/);
|
||||
|
||||
const hasNoDigits = !/\d/.test(fio);
|
||||
return words.length >= 2 && words.every(word => word.length >= 2) && hasNoDigits;
|
||||
}
|
||||
|
||||
function validateCity(city) {
|
||||
return city.trim().length >= 2 && /^[а-яА-ЯёЁ\s-]+$/.test(city);
|
||||
}
|
||||
|
||||
function validateEmail(email) {
|
||||
const localPart = email.split('@')[0];
|
||||
|
||||
if (/[а-яА-ЯёЁ]/.test(localPart)) {
|
||||
showError('email', 'В тексте перед знаком "@" не должно быть кириллических символов');
|
||||
return false;
|
||||
}
|
||||
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
showError('email', 'Введите корректный email адрес');
|
||||
return false;
|
||||
}
|
||||
|
||||
hideError('email');
|
||||
return true;
|
||||
}
|
||||
|
||||
function validatePhone(phone) {
|
||||
const phoneRegex = /^(\+7|8)[\s-]?\(?\d{3}\)?[\s-]?\d{3}[\s-]?\d{2}[\s-]?\d{2}$/;
|
||||
return phoneRegex.test(phone.replace(/\s/g, ''));
|
||||
}
|
||||
|
||||
function validatePassword(password) {
|
||||
return password.length >= 6;
|
||||
}
|
||||
|
||||
function showError(fieldId, message) {
|
||||
$('#' + fieldId).addClass('error');
|
||||
$('#' + fieldId + '-error').text(message).show();
|
||||
}
|
||||
|
||||
function hideError(fieldId) {
|
||||
$('#' + fieldId).removeClass('error');
|
||||
$('#' + fieldId + '-error').hide();
|
||||
}
|
||||
|
||||
function validateForm() {
|
||||
let isValid = true;
|
||||
|
||||
const fio = $('#fio').val();
|
||||
if (!validateFIO(fio)) {
|
||||
if (/\d/.test(fio)) {
|
||||
showError('fio', 'ФИО не должно содержать цифры');
|
||||
} else {
|
||||
showError('fio', 'ФИО должно содержать минимум 2 слова (каждое от 2 символов)');
|
||||
}
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('fio');
|
||||
}
|
||||
|
||||
const city = $('#city').val();
|
||||
if (!validateCity(city)) {
|
||||
showError('city', 'Укажите корректное название города (только русские буквы)');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('city');
|
||||
}
|
||||
|
||||
const email = $('#email').val();
|
||||
if (!validateEmail(email)) {
|
||||
showError('email', 'Введите корректный email адрес');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('email');
|
||||
}
|
||||
|
||||
const phone = $('#phone').val();
|
||||
if (!validatePhone(phone)) {
|
||||
showError('phone', 'Введите номер в формате: +7(912)999-12-23');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('phone');
|
||||
}
|
||||
|
||||
const password = $('#password').val();
|
||||
if (!validatePassword(password)) {
|
||||
showError('password', 'Пароль должен содержать минимум 6 символов');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('password');
|
||||
}
|
||||
|
||||
const confirmPassword = $('#confirm-password').val();
|
||||
if (password !== confirmPassword) {
|
||||
showError('confirm-password', 'Пароли не совпадают');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('confirm-password');
|
||||
}
|
||||
|
||||
if (!$('#privacy').is(':checked')) {
|
||||
$('#privacy-error').show();
|
||||
isValid = false;
|
||||
} else {
|
||||
$('#privacy-error').hide();
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
$('input').on('blur', function() {
|
||||
const fieldId = $(this).attr('id');
|
||||
const value = $(this).val();
|
||||
|
||||
switch(fieldId) {
|
||||
case 'fio':
|
||||
if (!validateFIO(value)) {
|
||||
if (/\d/.test(value)) {
|
||||
showError(fieldId, 'ФИО не должно содержать цифры');
|
||||
} else {
|
||||
showError(fieldId, 'ФИО должно содержать минимум 2 слова');
|
||||
}
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'city':
|
||||
if (!validateCity(value)) {
|
||||
showError(fieldId, 'Укажите корректное название города');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'email':
|
||||
if (!validateEmail(value)) {
|
||||
showError(fieldId, 'Введите корректный email адрес');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'phone':
|
||||
if (!validatePhone(value)) {
|
||||
showError(fieldId, 'Введите номер в формате: +7(912)999-12-23');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'password':
|
||||
if (!validatePassword(value)) {
|
||||
showError(fieldId, 'Пароль должен содержать минимум 6 символов');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'confirm-password':
|
||||
const password = $('#password').val();
|
||||
if (value !== password) {
|
||||
showError(fieldId, 'Пароли не совпадают');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
$('#registrationForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
if (validateForm()) {
|
||||
const email = $('#email').val();
|
||||
const isAdmin = isAdminEmail(email);
|
||||
|
||||
const userData = {
|
||||
email: email,
|
||||
fio: $('#fio').val(),
|
||||
phone: $('#phone').val(),
|
||||
isAdmin: isAdmin,
|
||||
registered: new Date().toISOString()
|
||||
};
|
||||
|
||||
localStorage.setItem('userData', JSON.stringify(userData));
|
||||
localStorage.setItem('isLoggedIn', 'true');
|
||||
localStorage.setItem('isAdmin', isAdmin.toString());
|
||||
|
||||
showMessage('success', 'Регистрация прошла успешно! ' +
|
||||
(isAdmin ? 'Вы зарегистрированы как администратор.' : 'Добро пожаловать в AETERNA!'));
|
||||
|
||||
setTimeout(() => {
|
||||
|
||||
window.location.href = 'cite_mebel.php';
|
||||
}, 2000);
|
||||
} else {
|
||||
showMessage('error', 'Пожалуйста, исправьте ошибки в форме');
|
||||
}
|
||||
});
|
||||
|
||||
$('a[href^="#"]').on('click', function(event) {
|
||||
var target = $(this.getAttribute('href'));
|
||||
if (target.length) {
|
||||
event.preventDefault();
|
||||
$('html, body').stop().animate({
|
||||
scrollTop: target.offset().top
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
|
||||
$('.login-btn').on('click', function() {
|
||||
showMessage('warning', 'Переход к форме входа...');
|
||||
setTimeout(() => {
|
||||
window.location.href = 'вход.php';
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
$('.password-link').on('click', function(e) {
|
||||
e.preventDefault();
|
||||
showMessage('warning', 'Функция смены пароля будет доступна после регистрации');
|
||||
});
|
||||
|
||||
$('#phone').on('input', function() {
|
||||
let value = $(this).val().replace(/\D/g, '');
|
||||
if (value.startsWith('7') || value.startsWith('8')) {
|
||||
value = value.substring(1);
|
||||
}
|
||||
if (value.length > 0) {
|
||||
value = '+7(' + value;
|
||||
if (value.length > 6) value = value.substring(0, 6) + ')' + value.substring(6);
|
||||
if (value.length > 10) value = value.substring(0, 10) + '-' + value.substring(10);
|
||||
if (value.length > 13) value = value.substring(0, 13) + '-' + value.substring(13);
|
||||
if (value.length > 16) value = value.substring(0, 16);
|
||||
}
|
||||
$(this).val(value);
|
||||
});
|
||||
|
||||
$('#fio').on('input', function() {
|
||||
let value = $(this).val();
|
||||
|
||||
value = value.replace(/\d/g, '');
|
||||
$(this).val(value);
|
||||
});
|
||||
});
|
||||
|
||||
$(document).ready(function() {
|
||||
|
||||
if (localStorage.getItem('isLoggedIn') === 'true') {
|
||||
const userData = JSON.parse(localStorage.getItem('userData') || '{}');
|
||||
if (userData.email) {
|
||||
$('#login-email').val(userData.email);
|
||||
}
|
||||
}
|
||||
|
||||
function checkAdminPassword(email, password) {
|
||||
|
||||
const adminAccounts = {
|
||||
'admin@aeterna.ru': 'admin123',
|
||||
'administrator@aeterna.ru': 'admin123',
|
||||
'aeterna@mail.ru': 'admin123'
|
||||
};
|
||||
|
||||
return adminAccounts[email.toLowerCase()] === password;
|
||||
}
|
||||
|
||||
$('#loginForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
let isValid = true;
|
||||
const email = $('#login-email').val();
|
||||
const password = $('#login-password').val();
|
||||
|
||||
if (!isValidEmail(email)) {
|
||||
$('#email-error').show();
|
||||
isValid = false;
|
||||
} else {
|
||||
$('#email-error').hide();
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
$('#password-error').show();
|
||||
isValid = false;
|
||||
} else {
|
||||
$('#password-error').hide();
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
|
||||
showMessage('success', 'Вы успешно вошли в систему!');
|
||||
|
||||
setTimeout(function() {
|
||||
window.location.href = 'cite_mebel.php';
|
||||
}, 1500);
|
||||
}
|
||||
});
|
||||
|
||||
function showMessage(type, text) {
|
||||
const messageId = type + 'Message';
|
||||
const $message = $('#' + messageId);
|
||||
|
||||
$message.text(text).show();
|
||||
|
||||
setTimeout(function() {
|
||||
$message.fadeOut();
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
$('input').on('focus', function() {
|
||||
$(this).next('.error-message').hide();
|
||||
});
|
||||
|
||||
$('#remember').on('change', function() {
|
||||
if ($(this).is(':checked')) {
|
||||
const email = $('#login-email').val();
|
||||
if (email) {
|
||||
localStorage.setItem('rememberedEmail', email);
|
||||
}
|
||||
} else {
|
||||
localStorage.removeItem('rememberedEmail');
|
||||
}
|
||||
});
|
||||
|
||||
const rememberedEmail = localStorage.getItem('rememberedEmail');
|
||||
if (rememberedEmail) {
|
||||
$('#login-email').val(rememberedEmail);
|
||||
$('#remember').prop('checked', true);
|
||||
}
|
||||
|
||||
$('.forgot-password').on('click', function(e) {
|
||||
e.preventDefault();
|
||||
showMessage('info', 'Для восстановления пароля обратитесь к администратору');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,142 +1,137 @@
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
/* Стили для сообщений внизу страницы */
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Дополнительные стили для формы регистрации */
|
||||
.input-group {
|
||||
position: relative;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.profile-form input.error {
|
||||
border-color: #ff0000;
|
||||
background-color: #fff5f5;
|
||||
}
|
||||
|
||||
.privacy-checkbox {
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.privacy-checkbox label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.privacy-checkbox input[type="checkbox"] {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Исправление отступов для страницы регистрации */
|
||||
.profile-page-main {
|
||||
padding: 40px 0;
|
||||
min-height: calc(100vh - 200px);
|
||||
}
|
||||
|
||||
/* Убедимся, что контейнер не перекрывает шапку и футер */
|
||||
.profile-container {
|
||||
margin: 0 auto;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.input-hint {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
/* Стили для страницы входа */
|
||||
.form-options {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.remember-me {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
}
|
||||
|
||||
.remember-me input[type="checkbox"] {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.forgot-password {
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.forgot-password:hover {
|
||||
color: #617365;
|
||||
text-decoration: none;
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.input-group {
|
||||
position: relative;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.profile-form input.error {
|
||||
border-color: #ff0000;
|
||||
background-color: #fff5f5;
|
||||
}
|
||||
|
||||
.privacy-checkbox {
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.privacy-checkbox label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.privacy-checkbox input[type="checkbox"] {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.profile-page-main {
|
||||
padding: 40px 0;
|
||||
min-height: calc(100vh - 200px);
|
||||
}
|
||||
|
||||
.profile-container {
|
||||
margin: 0 auto;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.input-hint {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.form-options {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.remember-me {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
}
|
||||
|
||||
.remember-me input[type="checkbox"] {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.forgot-password {
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.forgot-password:hover {
|
||||
color: #617365;
|
||||
text-decoration: none;
|
||||
}
|
||||
@@ -83,4 +83,3 @@
|
||||
border-color: @color-primary;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,114 +1,107 @@
|
||||
// check_auth.js
|
||||
$(document).ready(function() {
|
||||
// Проверка авторизации при загрузке страницы
|
||||
checkAuthStatus();
|
||||
|
||||
// Обработка формы входа
|
||||
$('#loginForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const email = $('#login-email').val();
|
||||
const password = $('#login-password').val();
|
||||
const remember = $('#remember').is(':checked');
|
||||
|
||||
$.ajax({
|
||||
url: 'login_handler.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
email: email,
|
||||
password: password
|
||||
},
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.success) {
|
||||
// Сохраняем в localStorage если выбрано "Запомнить меня"
|
||||
if (remember) {
|
||||
localStorage.setItem('rememberedEmail', email);
|
||||
} else {
|
||||
localStorage.removeItem('rememberedEmail');
|
||||
}
|
||||
|
||||
// Перенаправляем
|
||||
window.location.href = result.redirect || 'catalog.php';
|
||||
} else {
|
||||
showMessage('error', result.message || 'Ошибка авторизации');
|
||||
}
|
||||
} catch(e) {
|
||||
showMessage('error', 'Ошибка обработки ответа');
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
showMessage('error', 'Ошибка сервера');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Проверка статуса авторизации
|
||||
function checkAuthStatus() {
|
||||
$.ajax({
|
||||
url: 'check_auth_status.php',
|
||||
method: 'GET',
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.loggedIn) {
|
||||
updateUserProfile(result.user);
|
||||
}
|
||||
} catch(e) {
|
||||
console.error('Ошибка проверки авторизации', e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Обновление профиля пользователя
|
||||
function updateUserProfile(user) {
|
||||
// Обновляем шапку, если есть элементы для профиля
|
||||
if ($('#userEmail').length) {
|
||||
$('#userEmail').text(user.email);
|
||||
}
|
||||
if ($('#userName').length) {
|
||||
$('#userName').text(user.full_name);
|
||||
}
|
||||
}
|
||||
|
||||
// Показать сообщение
|
||||
function showMessage(type, text) {
|
||||
const $message = $('#' + type + 'Message');
|
||||
if ($message.length) {
|
||||
$message.text(text).fadeIn();
|
||||
setTimeout(() => $message.fadeOut(), 5000);
|
||||
} else {
|
||||
alert(text);
|
||||
}
|
||||
}
|
||||
|
||||
// Проверка авторизации для ссылок
|
||||
function checkAuth(redirectUrl) {
|
||||
$.ajax({
|
||||
url: 'check_auth_status.php',
|
||||
method: 'GET',
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.loggedIn) {
|
||||
window.location.href = redirectUrl;
|
||||
} else {
|
||||
// Показываем модальное окно или перенаправляем на вход
|
||||
showLoginModal(redirectUrl);
|
||||
}
|
||||
} catch(e) {
|
||||
showLoginModal(redirectUrl);
|
||||
}
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
// Показать модальное окно входа
|
||||
function showLoginModal(redirectUrl) {
|
||||
// Можно реализовать модальное окно или перенаправить на страницу входа
|
||||
window.location.href = 'вход.php?redirect=' + encodeURIComponent(redirectUrl);
|
||||
}
|
||||
});
|
||||
|
||||
$(document).ready(function() {
|
||||
|
||||
checkAuthStatus();
|
||||
|
||||
$('#loginForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const email = $('#login-email').val();
|
||||
const password = $('#login-password').val();
|
||||
const remember = $('#remember').is(':checked');
|
||||
|
||||
$.ajax({
|
||||
url: 'login_handler.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
email: email,
|
||||
password: password
|
||||
},
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.success) {
|
||||
|
||||
if (remember) {
|
||||
localStorage.setItem('rememberedEmail', email);
|
||||
} else {
|
||||
localStorage.removeItem('rememberedEmail');
|
||||
}
|
||||
|
||||
window.location.href = result.redirect || 'catalog.php';
|
||||
} else {
|
||||
showMessage('error', result.message || 'Ошибка авторизации');
|
||||
}
|
||||
} catch(e) {
|
||||
showMessage('error', 'Ошибка обработки ответа');
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
showMessage('error', 'Ошибка сервера');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function checkAuthStatus() {
|
||||
$.ajax({
|
||||
url: 'check_auth_status.php',
|
||||
method: 'GET',
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.loggedIn) {
|
||||
updateUserProfile(result.user);
|
||||
}
|
||||
} catch(e) {
|
||||
console.error('Ошибка проверки авторизации', e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function updateUserProfile(user) {
|
||||
|
||||
if ($('#userEmail').length) {
|
||||
$('#userEmail').text(user.email);
|
||||
}
|
||||
if ($('#userName').length) {
|
||||
$('#userName').text(user.full_name);
|
||||
}
|
||||
}
|
||||
|
||||
function showMessage(type, text) {
|
||||
const $message = $('#' + type + 'Message');
|
||||
if ($message.length) {
|
||||
$message.text(text).fadeIn();
|
||||
setTimeout(() => $message.fadeOut(), 5000);
|
||||
} else {
|
||||
alert(text);
|
||||
}
|
||||
}
|
||||
|
||||
function checkAuth(redirectUrl) {
|
||||
$.ajax({
|
||||
url: 'check_auth_status.php',
|
||||
method: 'GET',
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.loggedIn) {
|
||||
window.location.href = redirectUrl;
|
||||
} else {
|
||||
|
||||
showLoginModal(redirectUrl);
|
||||
}
|
||||
} catch(e) {
|
||||
showLoginModal(redirectUrl);
|
||||
}
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
function showLoginModal(redirectUrl) {
|
||||
|
||||
window.location.href = 'вход.php?redirect=' + encodeURIComponent(redirectUrl);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
<?php
|
||||
// config/database.php
|
||||
class Database {
|
||||
private static $instance = null;
|
||||
private $connection;
|
||||
|
||||
private function __construct() {
|
||||
try {
|
||||
$this->connection = new PDO(
|
||||
"pgsql:host=185.130.224.177;port=5481;dbname=postgres",
|
||||
"admin",
|
||||
"38feaad2840ccfda0e71243a6faaecfd"
|
||||
);
|
||||
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$this->connection->exec("SET NAMES 'utf8'");
|
||||
} catch(PDOException $e) {
|
||||
die("Ошибка подключения: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static function getInstance() {
|
||||
if (self::$instance == null) {
|
||||
self::$instance = new Database();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public function getConnection() {
|
||||
return $this->connection;
|
||||
}
|
||||
}
|
||||
<?php
|
||||
|
||||
class Database {
|
||||
private static $instance = null;
|
||||
private $connection;
|
||||
|
||||
private function __construct() {
|
||||
try {
|
||||
$this->connection = new PDO(
|
||||
"pgsql:host=185.130.224.177;port=5481;dbname=postgres",
|
||||
"admin",
|
||||
"38feaad2840ccfda0e71243a6faaecfd"
|
||||
);
|
||||
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$this->connection->exec("SET NAMES 'utf8'");
|
||||
} catch(PDOException $e) {
|
||||
die("Ошибка подключения: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static function getInstance() {
|
||||
if (self::$instance == null) {
|
||||
self::$instance = new Database();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public function getConnection() {
|
||||
return $this->connection;
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -1,16 +1,10 @@
|
||||
<?php
|
||||
/**
|
||||
* Функции авторизации для AETERNA
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
/**
|
||||
* Авторизация пользователя
|
||||
*/
|
||||
function loginUser(string $email, string $password): array {
|
||||
$db = Database::getInstance()->getConnection();
|
||||
|
||||
|
||||
try {
|
||||
$stmt = $db->prepare("
|
||||
SELECT user_id, email, password_hash, full_name, phone, city, is_admin, is_active
|
||||
@@ -31,7 +25,6 @@ function loginUser(string $email, string $password): array {
|
||||
return ['success' => false, 'message' => 'Неверный пароль'];
|
||||
}
|
||||
|
||||
// Сохраняем в сессию
|
||||
$_SESSION['user_id'] = $user['user_id'];
|
||||
$_SESSION['user_email'] = $user['email'];
|
||||
$_SESSION['full_name'] = $user['full_name'];
|
||||
@@ -41,7 +34,6 @@ function loginUser(string $email, string $password): array {
|
||||
$_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']]);
|
||||
|
||||
@@ -52,43 +44,38 @@ function loginUser(string $email, string $password): array {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Регистрация нового пользователя
|
||||
*/
|
||||
function registerUser(array $data): array {
|
||||
$db = Database::getInstance()->getConnection();
|
||||
|
||||
|
||||
$email = trim($data['email'] ?? '');
|
||||
$password = $data['password'] ?? '';
|
||||
$fullName = trim($data['full_name'] ?? '');
|
||||
$phone = trim($data['phone'] ?? '');
|
||||
$city = trim($data['city'] ?? '');
|
||||
|
||||
// Валидация
|
||||
|
||||
if (empty($email) || empty($password) || empty($fullName)) {
|
||||
return ['success' => false, 'message' => 'Заполните все обязательные поля'];
|
||||
}
|
||||
|
||||
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
return ['success' => false, 'message' => 'Некорректный email'];
|
||||
}
|
||||
|
||||
|
||||
if (strlen($password) < 6) {
|
||||
return ['success' => false, 'message' => 'Пароль должен содержать минимум 6 символов'];
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
// Проверяем существование пользователя
|
||||
|
||||
$checkStmt = $db->prepare("SELECT user_id FROM users WHERE email = ?");
|
||||
$checkStmt->execute([$email]);
|
||||
|
||||
|
||||
if ($checkStmt->fetch()) {
|
||||
return ['success' => false, 'message' => 'Пользователь с таким email уже существует'];
|
||||
}
|
||||
|
||||
// Создаем пользователя
|
||||
|
||||
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
|
||||
|
||||
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO users (email, password_hash, full_name, phone, city, is_active)
|
||||
VALUES (?, ?, ?, ?, ?, TRUE)
|
||||
@@ -96,8 +83,7 @@ function registerUser(array $data): array {
|
||||
");
|
||||
$stmt->execute([$email, $passwordHash, $fullName, $phone, $city]);
|
||||
$userId = $stmt->fetchColumn();
|
||||
|
||||
// Автоматически авторизуем
|
||||
|
||||
$_SESSION['user_id'] = $userId;
|
||||
$_SESSION['user_email'] = $email;
|
||||
$_SESSION['full_name'] = $fullName;
|
||||
@@ -106,20 +92,17 @@ function registerUser(array $data): array {
|
||||
$_SESSION['isLoggedIn'] = true;
|
||||
$_SESSION['isAdmin'] = false;
|
||||
$_SESSION['login_time'] = time();
|
||||
|
||||
|
||||
return ['success' => true, 'user_id' => $userId];
|
||||
|
||||
|
||||
} catch (PDOException $e) {
|
||||
return ['success' => false, 'message' => 'Ошибка базы данных: ' . $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Выход пользователя
|
||||
*/
|
||||
function logoutUser(): void {
|
||||
$_SESSION = [];
|
||||
|
||||
|
||||
if (ini_get("session.use_cookies")) {
|
||||
$params = session_get_cookie_params();
|
||||
setcookie(session_name(), '', time() - 42000,
|
||||
@@ -127,22 +110,18 @@ function logoutUser(): void {
|
||||
$params["secure"], $params["httponly"]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
session_destroy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка является ли пользователь администратором
|
||||
*/
|
||||
function checkAdminAccess(): bool {
|
||||
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
if (!isset($_SESSION['isAdmin']) || $_SESSION['isAdmin'] !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -47,4 +47,3 @@
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -1,25 +1,13 @@
|
||||
<?php
|
||||
/**
|
||||
* Общие функции для AETERNA
|
||||
*/
|
||||
|
||||
/**
|
||||
* Проверка авторизации пользователя
|
||||
*/
|
||||
function isLoggedIn(): bool {
|
||||
return isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка прав администратора
|
||||
*/
|
||||
function isAdmin(): bool {
|
||||
return isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Требовать авторизацию - редирект на login если не авторизован
|
||||
*/
|
||||
function requireAuth(string $redirectUrl = 'login.php'): void {
|
||||
if (!isLoggedIn()) {
|
||||
header('Location: ' . $redirectUrl . '?error=auth_required&redirect=' . urlencode($_SERVER['REQUEST_URI']));
|
||||
@@ -27,9 +15,6 @@ function requireAuth(string $redirectUrl = 'login.php'): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Требовать права администратора
|
||||
*/
|
||||
function requireAdmin(string $redirectUrl = 'login.php'): void {
|
||||
if (!isAdmin()) {
|
||||
header('Location: ' . $redirectUrl . '?error=admin_required');
|
||||
@@ -37,14 +22,11 @@ function requireAdmin(string $redirectUrl = 'login.php'): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить текущего пользователя
|
||||
*/
|
||||
function getCurrentUser(): ?array {
|
||||
if (!isLoggedIn()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
return [
|
||||
'user_id' => $_SESSION['user_id'] ?? 0,
|
||||
'email' => $_SESSION['user_email'] ?? '',
|
||||
@@ -53,38 +35,23 @@ function getCurrentUser(): ?array {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Форматирование цены
|
||||
*/
|
||||
function formatPrice(float $price): string {
|
||||
return number_format($price, 0, '', ' ') . ' ₽';
|
||||
}
|
||||
|
||||
/**
|
||||
* Безопасный вывод HTML
|
||||
*/
|
||||
function e(string $str): string {
|
||||
return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерация номера заказа
|
||||
*/
|
||||
function generateOrderNumber(): string {
|
||||
return 'AET-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерация SKU для товара
|
||||
*/
|
||||
function generateSKU(string $productName): string {
|
||||
$prefix = strtoupper(substr(preg_replace('/[^a-zA-Z0-9]/', '', transliterate($productName)), 0, 6));
|
||||
return $prefix . '-' . rand(100, 999);
|
||||
}
|
||||
|
||||
/**
|
||||
* Транслитерация кириллицы в латиницу
|
||||
*/
|
||||
function transliterate(string $str): string {
|
||||
$converter = [
|
||||
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd',
|
||||
@@ -105,9 +72,6 @@ function transliterate(string $str): string {
|
||||
return strtr($str, $converter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Создание slug из строки
|
||||
*/
|
||||
function createSlug(string $str): string {
|
||||
$slug = transliterate($str);
|
||||
$slug = strtolower($slug);
|
||||
@@ -116,9 +80,6 @@ function createSlug(string $str): string {
|
||||
return $slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Показать flash-сообщение
|
||||
*/
|
||||
function setFlashMessage(string $type, string $message): void {
|
||||
$_SESSION['flash_message'] = [
|
||||
'type' => $type,
|
||||
@@ -126,9 +87,6 @@ function setFlashMessage(string $type, string $message): void {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить и удалить flash-сообщение
|
||||
*/
|
||||
function getFlashMessage(): ?array {
|
||||
if (isset($_SESSION['flash_message'])) {
|
||||
$message = $_SESSION['flash_message'];
|
||||
@@ -137,4 +95,3 @@ function getFlashMessage(): ?array {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
<?php
|
||||
/**
|
||||
* Единый header для всех страниц AETERNA
|
||||
* Подключение: require_once 'includes/header.php';
|
||||
*/
|
||||
|
||||
// Запускаем сессию если еще не запущена
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
// Определяем текущую страницу
|
||||
$currentPage = basename($_SERVER['PHP_SELF'], '.php');
|
||||
|
||||
// Проверяем авторизацию
|
||||
$isLoggedIn = isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] === true;
|
||||
$isAdmin = isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true;
|
||||
$userEmail = $_SESSION['user_email'] ?? '';
|
||||
@@ -29,7 +22,7 @@ $fullName = $_SESSION['full_name'] ?? $userEmail;
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<style>
|
||||
/* Стили для профиля пользователя */
|
||||
|
||||
.user-profile-dropdown { position: relative; display: inline-block; }
|
||||
.user-profile-toggle { display: flex; align-items: center; gap: 10px; cursor: pointer; padding: 8px 12px; border-radius: 4px; transition: all 0.3s ease; }
|
||||
.user-profile-toggle:hover { background-color: rgba(0, 0, 0, 0.05); }
|
||||
@@ -86,13 +79,12 @@ $fullName = $_SESSION['full_name'] ?? $userEmail;
|
||||
|
||||
<div class="header__icons--top">
|
||||
<?php if ($isLoggedIn): ?>
|
||||
<!-- Иконка корзины -->
|
||||
|
||||
<a href="checkout.php" class="icon cart-icon">
|
||||
<i class="fas fa-shopping-cart"></i>
|
||||
<span class="cart-count" id="cartCount">0</span>
|
||||
</a>
|
||||
|
||||
<!-- Блок профиля -->
|
||||
<div class="user-profile-dropdown">
|
||||
<div class="user-profile-toggle" id="profileToggle">
|
||||
<div class="user-avatar"><?= !empty($userEmail) ? strtoupper(substr($userEmail, 0, 1)) : 'U' ?></div>
|
||||
@@ -149,19 +141,18 @@ $fullName = $_SESSION['full_name'] ?? $userEmail;
|
||||
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
// Профиль пользователя - открытие/закрытие
|
||||
|
||||
$('#profileToggle').click(function(e) {
|
||||
e.stopPropagation();
|
||||
$('#profileMenu').toggle();
|
||||
});
|
||||
|
||||
|
||||
$(document).click(function(e) {
|
||||
if (!$(e.target).closest('.user-profile-dropdown').length) {
|
||||
$('#profileMenu').hide();
|
||||
}
|
||||
});
|
||||
|
||||
// Обновление счетчика корзины
|
||||
<?php if ($isLoggedIn): ?>
|
||||
$.ajax({
|
||||
url: 'api/cart.php?action=count',
|
||||
@@ -178,4 +169,3 @@ $(document).ready(function() {
|
||||
<?php endif; ?>
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
<?php
|
||||
/**
|
||||
* Быстрый скрипт для назначения прав администратора пользователю admin@mail.ru
|
||||
* Запуск: php migrations/grant_admin.php
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
@@ -16,7 +12,6 @@ try {
|
||||
|
||||
$email = 'admin@mail.ru';
|
||||
|
||||
// Проверяем, существует ли пользователь
|
||||
$checkStmt = $db->prepare("SELECT user_id, email, full_name, is_admin, is_active FROM users WHERE email = ?");
|
||||
$checkStmt->execute([$email]);
|
||||
$user = $checkStmt->fetch(PDO::FETCH_ASSOC);
|
||||
@@ -31,9 +26,9 @@ try {
|
||||
if ($user['is_admin']) {
|
||||
echo "[INFO] Пользователь уже имеет права администратора\n";
|
||||
} else {
|
||||
// Обновляем права
|
||||
|
||||
$updateStmt = $db->prepare("
|
||||
UPDATE users
|
||||
UPDATE users
|
||||
SET is_admin = TRUE,
|
||||
is_active = TRUE,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
@@ -47,8 +42,6 @@ try {
|
||||
echo "[WARN] Пользователь с email $email не найден\n";
|
||||
echo "[INFO] Создаю нового пользователя с правами администратора...\n";
|
||||
|
||||
// Создаем пользователя с правами админа
|
||||
// Пароль по умолчанию: admin123
|
||||
$password_hash = password_hash('admin123', PASSWORD_DEFAULT);
|
||||
|
||||
$insertStmt = $db->prepare("
|
||||
@@ -73,7 +66,6 @@ try {
|
||||
echo "[WARN] Рекомендуется сменить пароль после первого входа!\n";
|
||||
}
|
||||
|
||||
// Проверяем результат
|
||||
$verifyStmt = $db->prepare("SELECT user_id, email, full_name, is_admin, is_active FROM users WHERE email = ?");
|
||||
$verifyStmt->execute([$email]);
|
||||
$finalUser = $verifyStmt->fetch(PDO::FETCH_ASSOC);
|
||||
@@ -91,4 +83,3 @@ try {
|
||||
echo "[ERROR] Ошибка: " . $e->getMessage() . "\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
<?php
|
||||
/**
|
||||
* Простой раннер миграций для PostgreSQL
|
||||
* Запуск: php migrations/migrate.php
|
||||
*/
|
||||
|
||||
// Подключаем конфиг базы данных
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
echo "===========================================\n";
|
||||
@@ -15,7 +10,6 @@ try {
|
||||
$db = Database::getInstance()->getConnection();
|
||||
echo "[OK] Подключение к базе данных успешно\n\n";
|
||||
|
||||
// 1. Создаем таблицу для отслеживания миграций
|
||||
$db->exec("
|
||||
CREATE TABLE IF NOT EXISTS migrations (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -25,12 +19,10 @@ try {
|
||||
");
|
||||
echo "[OK] Таблица migrations готова\n";
|
||||
|
||||
// 2. Получаем список уже примененных миграций
|
||||
$stmt = $db->query("SELECT filename FROM migrations ORDER BY filename");
|
||||
$applied = $stmt->fetchAll(PDO::FETCH_COLUMN);
|
||||
echo "[INFO] Уже применено миграций: " . count($applied) . "\n\n";
|
||||
|
||||
// 3. Сканируем папку на SQL-файлы
|
||||
$migrationFiles = glob(__DIR__ . '/*.sql');
|
||||
sort($migrationFiles);
|
||||
|
||||
@@ -38,30 +30,26 @@ try {
|
||||
|
||||
foreach ($migrationFiles as $file) {
|
||||
$filename = basename($file);
|
||||
|
||||
// Пропускаем seed_data.sql - он запускается отдельно
|
||||
|
||||
if ($filename === 'seed_data.sql') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Проверяем, была ли миграция уже применена
|
||||
if (in_array($filename, $applied)) {
|
||||
echo "[SKIP] $filename (уже применена)\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
// Применяем миграцию
|
||||
echo "[RUN] Применяю $filename... ";
|
||||
|
||||
|
||||
$sql = file_get_contents($file);
|
||||
|
||||
|
||||
try {
|
||||
$db->exec($sql);
|
||||
|
||||
// Записываем в таблицу миграций
|
||||
|
||||
$stmt = $db->prepare("INSERT INTO migrations (filename) VALUES (?)");
|
||||
$stmt->execute([$filename]);
|
||||
|
||||
|
||||
echo "OK\n";
|
||||
$newMigrations++;
|
||||
} catch (PDOException $e) {
|
||||
@@ -73,19 +61,18 @@ try {
|
||||
}
|
||||
|
||||
echo "\n-------------------------------------------\n";
|
||||
|
||||
|
||||
if ($newMigrations > 0) {
|
||||
echo "[SUCCESS] Применено новых миграций: $newMigrations\n";
|
||||
} else {
|
||||
echo "[INFO] Все миграции уже применены\n";
|
||||
}
|
||||
|
||||
// 4. Спрашиваем про seed_data
|
||||
$seedFile = __DIR__ . '/seed_data.sql';
|
||||
if (file_exists($seedFile)) {
|
||||
echo "\n[?] Хотите загрузить начальные данные (seed_data.sql)?\n";
|
||||
echo " Запустите: php migrations/migrate.php --seed\n";
|
||||
|
||||
|
||||
if (isset($argv[1]) && $argv[1] === '--seed') {
|
||||
echo "\n[RUN] Загружаю seed_data.sql... ";
|
||||
try {
|
||||
@@ -106,4 +93,3 @@ try {
|
||||
echo "[ERROR] Ошибка подключения к БД: " . $e->getMessage() . "\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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' => 'Неверный запрос']);
|
||||
}
|
||||
?>
|
||||
@@ -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' => 'Неверный запрос']);
|
||||
}
|
||||
?>
|
||||
@@ -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()]);
|
||||
}
|
||||
|
||||
|
||||
@@ -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()
|
||||
]);
|
||||
}
|
||||
?>
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -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()]);
|
||||
}
|
||||
?>
|
||||
@@ -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();
|
||||
}
|
||||
?>
|
||||
@@ -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();
|
||||
}
|
||||
?>
|
||||
@@ -1,62 +1,61 @@
|
||||
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
/* Стили для сообщений внизу страницы */
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@@ -1,346 +1,306 @@
|
||||
// script.js
|
||||
|
||||
$(document).ready(function() {
|
||||
// Инициализация корзины
|
||||
let cart = {
|
||||
items: [
|
||||
{ id: 1, name: 'Кресло OPPORTUNITY', price: 16999, quantity: 1 },
|
||||
{ id: 2, name: 'Кресло GOLDEN', price: 19999, quantity: 1 },
|
||||
{ id: 3, name: 'Светильник POLET', price: 7999, quantity: 1 }
|
||||
],
|
||||
delivery: 2000,
|
||||
discount: 0
|
||||
};
|
||||
|
||||
// Функция обновления общей суммы
|
||||
function updateTotal() {
|
||||
let productsTotal = 0;
|
||||
let totalCount = 0;
|
||||
|
||||
// Пересчитываем товары
|
||||
$('.products__item').each(function() {
|
||||
const $item = $(this);
|
||||
const price = parseInt($item.data('price'));
|
||||
const quantity = parseInt($item.find('.products__qty-value').text());
|
||||
|
||||
productsTotal += price * quantity;
|
||||
totalCount += quantity;
|
||||
});
|
||||
|
||||
// Обновляем отображение
|
||||
$('.products-total').text(productsTotal + ' ₽');
|
||||
$('.summary-count').text(totalCount);
|
||||
$('.total-count').text(totalCount + ' шт.');
|
||||
$('.cart-count').text(totalCount);
|
||||
|
||||
// Обновляем итоговую сумму
|
||||
const finalTotal = productsTotal + cart.delivery - cart.discount;
|
||||
$('.final-total').text(finalTotal + ' ₽');
|
||||
}
|
||||
|
||||
// Функция валидации email
|
||||
function validateEmail(email) {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(email);
|
||||
}
|
||||
|
||||
// Функция валидации имени (ФИО)
|
||||
function validateFullName(name) {
|
||||
// Проверяем, что имя содержит только буквы, пробелы, дефисы и апострофы
|
||||
const nameRegex = /^[a-zA-Zа-яА-ЯёЁ\s\-']+$/;
|
||||
|
||||
// Проверяем, что имя состоит минимум из 2 слов
|
||||
const words = name.trim().split(/\s+/);
|
||||
|
||||
return nameRegex.test(name) && words.length >= 2;
|
||||
}
|
||||
|
||||
// Функция валидации телефона
|
||||
function validatePhone(phone) {
|
||||
// Российский формат телефона: +7XXXXXXXXXX
|
||||
const phoneRegex = /^\+7\d{10}$/;
|
||||
return phoneRegex.test(phone);
|
||||
}
|
||||
|
||||
// Функция отображения сообщения
|
||||
function showMessage(messageId, duration = 5000) {
|
||||
// Скрываем все сообщения
|
||||
$('.message').hide();
|
||||
|
||||
// Показываем нужное сообщение
|
||||
$(messageId).fadeIn(300);
|
||||
|
||||
// Автоматически скрываем через указанное время
|
||||
if (duration > 0) {
|
||||
setTimeout(() => {
|
||||
$(messageId).fadeOut(300);
|
||||
}, duration);
|
||||
}
|
||||
}
|
||||
|
||||
// Функция показа ошибки приватности
|
||||
function showPrivacyError(show) {
|
||||
if (show) {
|
||||
$('#privacy-error').show();
|
||||
} else {
|
||||
$('#privacy-error').hide();
|
||||
}
|
||||
}
|
||||
|
||||
// Функция отображения ошибки конкретного поля
|
||||
function showFieldError(fieldId, message) {
|
||||
// Убираем старые ошибки
|
||||
$(fieldId).removeClass('error-input');
|
||||
$(fieldId + '-error').remove();
|
||||
|
||||
if (message) {
|
||||
$(fieldId).addClass('error-input');
|
||||
$(fieldId).after('<div class="field-error" id="' + fieldId.replace('#', '') + '-error">' + message + '</div>');
|
||||
}
|
||||
}
|
||||
|
||||
// Валидация поля при потере фокуса с указанием конкретной ошибки
|
||||
$('#fullname').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (value) {
|
||||
if (!validateFullName(value)) {
|
||||
showFieldError('#fullname', 'ФИО должно содержать только буквы и состоять минимум из 2 слов');
|
||||
} else {
|
||||
showFieldError('#fullname', '');
|
||||
}
|
||||
} else {
|
||||
showFieldError('#fullname', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#email').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (value) {
|
||||
if (!validateEmail(value)) {
|
||||
showFieldError('#email', 'Введите корректный email адрес (например: example@mail.ru)');
|
||||
} else {
|
||||
showFieldError('#email', '');
|
||||
}
|
||||
} else {
|
||||
showFieldError('#email', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#phone').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (value) {
|
||||
if (!validatePhone(value)) {
|
||||
showFieldError('#phone', 'Введите номер в формате +7XXXXXXXXXX (10 цифр после +7)');
|
||||
} else {
|
||||
showFieldError('#phone', '');
|
||||
}
|
||||
} else {
|
||||
showFieldError('#phone', '');
|
||||
}
|
||||
});
|
||||
|
||||
// Валидация обязательных полей
|
||||
$('#region').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (!value) {
|
||||
showFieldError('#region', 'Укажите регион доставки');
|
||||
} else {
|
||||
showFieldError('#region', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#address').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (!value) {
|
||||
showFieldError('#address', 'Укажите адрес доставки (улица, дом, квартира)');
|
||||
} else {
|
||||
showFieldError('#address', '');
|
||||
}
|
||||
});
|
||||
|
||||
// Очистка ошибки при начале ввода
|
||||
$('.form__input').on('input', function() {
|
||||
const fieldId = '#' + $(this).attr('id');
|
||||
showFieldError(fieldId, '');
|
||||
});
|
||||
|
||||
// Обработчик увеличения количества
|
||||
$('.products__qty-btn.plus').click(function() {
|
||||
const $qtyValue = $(this).siblings('.products__qty-value');
|
||||
let quantity = parseInt($qtyValue.text());
|
||||
$qtyValue.text(quantity + 1);
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
// Обработчик уменьшения количества
|
||||
$('.products__qty-btn.minus').click(function() {
|
||||
const $qtyValue = $(this).siblings('.products__qty-value');
|
||||
let quantity = parseInt($qtyValue.text());
|
||||
if (quantity > 1) {
|
||||
$qtyValue.text(quantity - 1);
|
||||
updateTotal();
|
||||
}
|
||||
});
|
||||
|
||||
// Обработчик удаления товара
|
||||
$('.remove-from-cart').click(function() {
|
||||
const $productItem = $(this).closest('.products__item');
|
||||
$productItem.fadeOut(300, function() {
|
||||
$(this).remove();
|
||||
updateTotal();
|
||||
|
||||
// Показываем сообщение, если корзина пуста
|
||||
if ($('.products__item').length === 0) {
|
||||
$('.products__list').html('<div class="empty-cart">Корзина пуста</div>');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Обработчик применения промокода
|
||||
$('.promo__btn').click(function() {
|
||||
const promoCode = $('.promo__input').val().toUpperCase();
|
||||
|
||||
if (promoCode === 'SALE10') {
|
||||
cart.discount = Math.round(parseInt($('.products-total').text()) * 0.1);
|
||||
$('.discount-total').text(cart.discount + ' ₽');
|
||||
showMessage('#form-error', 3000);
|
||||
$('#form-error').text('Промокод применен! Скидка 10%').removeClass('error').addClass('success');
|
||||
} else if (promoCode === 'FREE') {
|
||||
cart.delivery = 0;
|
||||
$('.delivery-price').text('0 ₽');
|
||||
showMessage('#form-error', 3000);
|
||||
$('#form-error').text('Промокод применен! Бесплатная доставка').removeClass('error').addClass('success');
|
||||
} else if (promoCode) {
|
||||
showMessage('#form-error', 3000);
|
||||
$('#form-error').text('Промокод недействителен').removeClass('success').addClass('error');
|
||||
}
|
||||
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
// Обработчик выбора доставки
|
||||
$('input[name="delivery"]').change(function() {
|
||||
if ($(this).val() === 'pickup') {
|
||||
cart.delivery = 0;
|
||||
$('.delivery-price').text('0 ₽');
|
||||
} else {
|
||||
cart.delivery = 2000;
|
||||
$('.delivery-price').text('2000 ₽');
|
||||
}
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
// Функция проверки всех полей формы
|
||||
function validateForm() {
|
||||
let isValid = true;
|
||||
let errorMessages = [];
|
||||
|
||||
// Очищаем все старые ошибки
|
||||
$('.field-error').remove();
|
||||
$('.form__input').removeClass('error-input');
|
||||
|
||||
// Проверка обязательных полей
|
||||
const requiredFields = [
|
||||
{
|
||||
id: '#fullname',
|
||||
value: $('#fullname').val().trim(),
|
||||
validator: validateFullName,
|
||||
required: true,
|
||||
message: 'ФИО должно содержать только буквы и состоять минимум из 2 слов'
|
||||
},
|
||||
{
|
||||
id: '#phone',
|
||||
value: $('#phone').val().trim(),
|
||||
validator: validatePhone,
|
||||
required: true,
|
||||
message: 'Введите корректный номер телефона в формате +7XXXXXXXXXX'
|
||||
},
|
||||
{
|
||||
id: '#email',
|
||||
value: $('#email').val().trim(),
|
||||
validator: validateEmail,
|
||||
required: true,
|
||||
message: 'Введите корректный email адрес'
|
||||
},
|
||||
{
|
||||
id: '#region',
|
||||
value: $('#region').val().trim(),
|
||||
validator: (val) => val.length > 0,
|
||||
required: true,
|
||||
message: 'Поле "Регион" обязательно для заполнения'
|
||||
},
|
||||
{
|
||||
id: '#address',
|
||||
value: $('#address').val().trim(),
|
||||
validator: (val) => val.length > 0,
|
||||
required: true,
|
||||
message: 'Поле "Адрес" обязательно для заполнения'
|
||||
}
|
||||
];
|
||||
|
||||
// Проверяем каждое поле
|
||||
requiredFields.forEach(field => {
|
||||
if (field.required && (!field.value || !field.validator(field.value))) {
|
||||
isValid = false;
|
||||
errorMessages.push(field.message);
|
||||
showFieldError(field.id, field.message);
|
||||
}
|
||||
});
|
||||
|
||||
// Проверка согласия на обработку данных
|
||||
if (!$('#privacy-checkbox').is(':checked')) {
|
||||
isValid = false;
|
||||
showPrivacyError(true);
|
||||
errorMessages.push('Необходимо согласие на обработку персональных данных');
|
||||
} else {
|
||||
showPrivacyError(false);
|
||||
}
|
||||
|
||||
// Показываем общее сообщение, если есть ошибки
|
||||
if (!isValid && errorMessages.length > 0) {
|
||||
showMessage('#form-error', 5000);
|
||||
$('#form-error').text('Исправьте следующие ошибки: ' + errorMessages.join('; ')).removeClass('success').addClass('error');
|
||||
|
||||
// Прокручиваем к первой ошибке
|
||||
$('html, body').animate({
|
||||
scrollTop: $('.error-input').first().offset().top - 100
|
||||
}, 500);
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
// Обработчик оформления заказа
|
||||
$('#submit-order').click(function() {
|
||||
// Проверка валидации всех полей
|
||||
if (!validateForm()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Симуляция отправки заказа
|
||||
$(this).prop('disabled', true).text('ОБРАБОТКА...');
|
||||
|
||||
setTimeout(() => {
|
||||
showMessage('#order-success', 5000);
|
||||
$(this).prop('disabled', false).text('ОФОРМИТЬ ЗАКАЗ');
|
||||
|
||||
// Здесь можно добавить редирект на страницу благодарности
|
||||
// window.location.href = 'спасибо.html';
|
||||
}, 2000);
|
||||
});
|
||||
|
||||
// Маска для телефона
|
||||
$('#phone').on('input', function() {
|
||||
let phone = $(this).val().replace(/\D/g, '');
|
||||
if (phone.length > 0) {
|
||||
if (phone[0] !== '7' && phone[0] !== '8') {
|
||||
phone = '7' + phone;
|
||||
}
|
||||
phone = '+7' + phone.substring(1, 11);
|
||||
$(this).val(phone);
|
||||
}
|
||||
});
|
||||
|
||||
// Инициализация при загрузке
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
$(document).ready(function() {
|
||||
|
||||
let cart = {
|
||||
items: [
|
||||
{ id: 1, name: 'Кресло OPPORTUNITY', price: 16999, quantity: 1 },
|
||||
{ id: 2, name: 'Кресло GOLDEN', price: 19999, quantity: 1 },
|
||||
{ id: 3, name: 'Светильник POLET', price: 7999, quantity: 1 }
|
||||
],
|
||||
delivery: 2000,
|
||||
discount: 0
|
||||
};
|
||||
|
||||
function updateTotal() {
|
||||
let productsTotal = 0;
|
||||
let totalCount = 0;
|
||||
|
||||
$('.products__item').each(function() {
|
||||
const $item = $(this);
|
||||
const price = parseInt($item.data('price'));
|
||||
const quantity = parseInt($item.find('.products__qty-value').text());
|
||||
|
||||
productsTotal += price * quantity;
|
||||
totalCount += quantity;
|
||||
});
|
||||
|
||||
$('.products-total').text(productsTotal + ' ₽');
|
||||
$('.summary-count').text(totalCount);
|
||||
$('.total-count').text(totalCount + ' шт.');
|
||||
$('.cart-count').text(totalCount);
|
||||
|
||||
const finalTotal = productsTotal + cart.delivery - cart.discount;
|
||||
$('.final-total').text(finalTotal + ' ₽');
|
||||
}
|
||||
|
||||
function validateEmail(email) {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(email);
|
||||
}
|
||||
|
||||
function validateFullName(name) {
|
||||
|
||||
const nameRegex = /^[a-zA-Zа-яА-ЯёЁ\s\-']+$/;
|
||||
|
||||
const words = name.trim().split(/\s+/);
|
||||
|
||||
return nameRegex.test(name) && words.length >= 2;
|
||||
}
|
||||
|
||||
function validatePhone(phone) {
|
||||
const phoneRegex = /^\+7\d{10}$/;
|
||||
return phoneRegex.test(phone);
|
||||
}
|
||||
|
||||
function showMessage(messageId, duration = 5000) {
|
||||
$('.message').hide();
|
||||
|
||||
$(messageId).fadeIn(300);
|
||||
|
||||
if (duration > 0) {
|
||||
setTimeout(() => {
|
||||
$(messageId).fadeOut(300);
|
||||
}, duration);
|
||||
}
|
||||
}
|
||||
|
||||
function showPrivacyError(show) {
|
||||
if (show) {
|
||||
$('#privacy-error').show();
|
||||
} else {
|
||||
$('#privacy-error').hide();
|
||||
}
|
||||
}
|
||||
|
||||
function showFieldError(fieldId, message) {
|
||||
$(fieldId).removeClass('error-input');
|
||||
$(fieldId + '-error').remove();
|
||||
|
||||
if (message) {
|
||||
$(fieldId).addClass('error-input');
|
||||
$(fieldId).after('<div class="field-error" id="' + fieldId.replace('#', '') + '-error">' + message + '</div>');
|
||||
}
|
||||
}
|
||||
|
||||
$('#fullname').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (value) {
|
||||
if (!validateFullName(value)) {
|
||||
showFieldError('#fullname', 'ФИО должно содержать только буквы и состоять минимум из 2 слов');
|
||||
} else {
|
||||
showFieldError('#fullname', '');
|
||||
}
|
||||
} else {
|
||||
showFieldError('#fullname', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#email').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (value) {
|
||||
if (!validateEmail(value)) {
|
||||
showFieldError('#email', 'Введите корректный email адрес (например: example@mail.ru)');
|
||||
} else {
|
||||
showFieldError('#email', '');
|
||||
}
|
||||
} else {
|
||||
showFieldError('#email', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#phone').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (value) {
|
||||
if (!validatePhone(value)) {
|
||||
showFieldError('#phone', 'Введите номер в формате +7XXXXXXXXXX (10 цифр после +7)');
|
||||
} else {
|
||||
showFieldError('#phone', '');
|
||||
}
|
||||
} else {
|
||||
showFieldError('#phone', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#region').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (!value) {
|
||||
showFieldError('#region', 'Укажите регион доставки');
|
||||
} else {
|
||||
showFieldError('#region', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('#address').on('blur', function() {
|
||||
const value = $(this).val().trim();
|
||||
if (!value) {
|
||||
showFieldError('#address', 'Укажите адрес доставки (улица, дом, квартира)');
|
||||
} else {
|
||||
showFieldError('#address', '');
|
||||
}
|
||||
});
|
||||
|
||||
$('.form__input').on('input', function() {
|
||||
const fieldId = '#' + $(this).attr('id');
|
||||
showFieldError(fieldId, '');
|
||||
});
|
||||
|
||||
$('.products__qty-btn.plus').click(function() {
|
||||
const $qtyValue = $(this).siblings('.products__qty-value');
|
||||
let quantity = parseInt($qtyValue.text());
|
||||
$qtyValue.text(quantity + 1);
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
$('.products__qty-btn.minus').click(function() {
|
||||
const $qtyValue = $(this).siblings('.products__qty-value');
|
||||
let quantity = parseInt($qtyValue.text());
|
||||
if (quantity > 1) {
|
||||
$qtyValue.text(quantity - 1);
|
||||
updateTotal();
|
||||
}
|
||||
});
|
||||
|
||||
$('.remove-from-cart').click(function() {
|
||||
const $productItem = $(this).closest('.products__item');
|
||||
$productItem.fadeOut(300, function() {
|
||||
$(this).remove();
|
||||
updateTotal();
|
||||
|
||||
if ($('.products__item').length === 0) {
|
||||
$('.products__list').html('<div class="empty-cart">Корзина пуста</div>');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$('.promo__btn').click(function() {
|
||||
const promoCode = $('.promo__input').val().toUpperCase();
|
||||
|
||||
if (promoCode === 'SALE10') {
|
||||
cart.discount = Math.round(parseInt($('.products-total').text()) * 0.1);
|
||||
$('.discount-total').text(cart.discount + ' ₽');
|
||||
showMessage('#form-error', 3000);
|
||||
$('#form-error').text('Промокод применен! Скидка 10%').removeClass('error').addClass('success');
|
||||
} else if (promoCode === 'FREE') {
|
||||
cart.delivery = 0;
|
||||
$('.delivery-price').text('0 ₽');
|
||||
showMessage('#form-error', 3000);
|
||||
$('#form-error').text('Промокод применен! Бесплатная доставка').removeClass('error').addClass('success');
|
||||
} else if (promoCode) {
|
||||
showMessage('#form-error', 3000);
|
||||
$('#form-error').text('Промокод недействителен').removeClass('success').addClass('error');
|
||||
}
|
||||
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
$('input[name="delivery"]').change(function() {
|
||||
if ($(this).val() === 'pickup') {
|
||||
cart.delivery = 0;
|
||||
$('.delivery-price').text('0 ₽');
|
||||
} else {
|
||||
cart.delivery = 2000;
|
||||
$('.delivery-price').text('2000 ₽');
|
||||
}
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
function validateForm() {
|
||||
let isValid = true;
|
||||
let errorMessages = [];
|
||||
|
||||
$('.field-error').remove();
|
||||
$('.form__input').removeClass('error-input');
|
||||
|
||||
const requiredFields = [
|
||||
{
|
||||
id: '#fullname',
|
||||
value: $('#fullname').val().trim(),
|
||||
validator: validateFullName,
|
||||
required: true,
|
||||
message: 'ФИО должно содержать только буквы и состоять минимум из 2 слов'
|
||||
},
|
||||
{
|
||||
id: '#phone',
|
||||
value: $('#phone').val().trim(),
|
||||
validator: validatePhone,
|
||||
required: true,
|
||||
message: 'Введите корректный номер телефона в формате +7XXXXXXXXXX'
|
||||
},
|
||||
{
|
||||
id: '#email',
|
||||
value: $('#email').val().trim(),
|
||||
validator: validateEmail,
|
||||
required: true,
|
||||
message: 'Введите корректный email адрес'
|
||||
},
|
||||
{
|
||||
id: '#region',
|
||||
value: $('#region').val().trim(),
|
||||
validator: (val) => val.length > 0,
|
||||
required: true,
|
||||
message: 'Поле "Регион" обязательно для заполнения'
|
||||
},
|
||||
{
|
||||
id: '#address',
|
||||
value: $('#address').val().trim(),
|
||||
validator: (val) => val.length > 0,
|
||||
required: true,
|
||||
message: 'Поле "Адрес" обязательно для заполнения'
|
||||
}
|
||||
];
|
||||
|
||||
requiredFields.forEach(field => {
|
||||
if (field.required && (!field.value || !field.validator(field.value))) {
|
||||
isValid = false;
|
||||
errorMessages.push(field.message);
|
||||
showFieldError(field.id, field.message);
|
||||
}
|
||||
});
|
||||
|
||||
if (!$('#privacy-checkbox').is(':checked')) {
|
||||
isValid = false;
|
||||
showPrivacyError(true);
|
||||
errorMessages.push('Необходимо согласие на обработку персональных данных');
|
||||
} else {
|
||||
showPrivacyError(false);
|
||||
}
|
||||
|
||||
if (!isValid && errorMessages.length > 0) {
|
||||
showMessage('#form-error', 5000);
|
||||
$('#form-error').text('Исправьте следующие ошибки: ' + errorMessages.join('; ')).removeClass('success').addClass('error');
|
||||
|
||||
$('html, body').animate({
|
||||
scrollTop: $('.error-input').first().offset().top - 100
|
||||
}, 500);
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
$('#submit-order').click(function() {
|
||||
if (!validateForm()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$(this).prop('disabled', true).text('ОБРАБОТКА...');
|
||||
|
||||
setTimeout(() => {
|
||||
showMessage('#order-success', 5000);
|
||||
$(this).prop('disabled', false).text('ОФОРМИТЬ ЗАКАЗ');
|
||||
|
||||
}, 2000);
|
||||
});
|
||||
|
||||
$('#phone').on('input', function() {
|
||||
let phone = $(this).val().replace(/\D/g, '');
|
||||
if (phone.length > 0) {
|
||||
if (phone[0] !== '7' && phone[0] !== '8') {
|
||||
phone = '7' + phone;
|
||||
}
|
||||
phone = '+7' + phone.substring(1, 11);
|
||||
$(this).val(phone);
|
||||
}
|
||||
});
|
||||
|
||||
updateTotal();
|
||||
});
|
||||
|
||||
@@ -1,384 +1,348 @@
|
||||
$(document).ready(function() {
|
||||
// Функции для отображения сообщений
|
||||
function showMessage(type, text) {
|
||||
const messageId = type + 'Message';
|
||||
const $message = $('#' + messageId);
|
||||
$message.text(text).fadeIn(300);
|
||||
setTimeout(() => {
|
||||
$message.fadeOut(300);
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
// Проверка, является ли email администратора
|
||||
function isAdminEmail(email) {
|
||||
const adminEmails = ['admin@aeterna.ru', 'administrator@aeterna.ru', 'aeterna@mail.ru'];
|
||||
return adminEmails.includes(email.toLowerCase());
|
||||
}
|
||||
|
||||
// Валидация ФИО (без цифр)
|
||||
function validateFIO(fio) {
|
||||
const words = fio.trim().split(/\s+/);
|
||||
// Проверяем, что минимум 2 слова и нет цифр
|
||||
const hasNoDigits = !/\d/.test(fio);
|
||||
return words.length >= 2 && words.every(word => word.length >= 2) && hasNoDigits;
|
||||
}
|
||||
|
||||
// Валидация города
|
||||
function validateCity(city) {
|
||||
return city.trim().length >= 2 && /^[а-яА-ЯёЁ\s-]+$/.test(city);
|
||||
}
|
||||
|
||||
// Валидация email
|
||||
function validateEmail(email) {
|
||||
const localPart = email.split('@')[0];
|
||||
|
||||
// Проверка на кириллические символы перед @
|
||||
if (/[а-яА-ЯёЁ]/.test(localPart)) {
|
||||
showError('email', 'В тексте перед знаком "@" не должно быть кириллических символов');
|
||||
return false;
|
||||
}
|
||||
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
showError('email', 'Введите корректный email адрес');
|
||||
return false;
|
||||
}
|
||||
|
||||
hideError('email');
|
||||
return true;
|
||||
}
|
||||
|
||||
// Валидация телефона
|
||||
function validatePhone(phone) {
|
||||
const phoneRegex = /^(\+7|8)[\s-]?\(?\d{3}\)?[\s-]?\d{3}[\s-]?\d{2}[\s-]?\d{2}$/;
|
||||
return phoneRegex.test(phone.replace(/\s/g, ''));
|
||||
}
|
||||
|
||||
// Валидация пароля
|
||||
function validatePassword(password) {
|
||||
return password.length >= 6;
|
||||
}
|
||||
|
||||
// Показать/скрыть ошибку
|
||||
function showError(fieldId, message) {
|
||||
$('#' + fieldId).addClass('error');
|
||||
$('#' + fieldId + '-error').text(message).show();
|
||||
}
|
||||
|
||||
function hideError(fieldId) {
|
||||
$('#' + fieldId).removeClass('error');
|
||||
$('#' + fieldId + '-error').hide();
|
||||
}
|
||||
|
||||
// Валидация формы
|
||||
function validateForm() {
|
||||
let isValid = true;
|
||||
|
||||
// Валидация ФИО
|
||||
const fio = $('#fio').val();
|
||||
if (!validateFIO(fio)) {
|
||||
if (/\d/.test(fio)) {
|
||||
showError('fio', 'ФИО не должно содержать цифры');
|
||||
} else {
|
||||
showError('fio', 'ФИО должно содержать минимум 2 слова (каждое от 2 символов)');
|
||||
}
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('fio');
|
||||
}
|
||||
|
||||
// Валидация города
|
||||
const city = $('#city').val();
|
||||
if (!validateCity(city)) {
|
||||
showError('city', 'Укажите корректное название города (только русские буквы)');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('city');
|
||||
}
|
||||
|
||||
// Валидация email
|
||||
const email = $('#email').val();
|
||||
if (!validateEmail(email)) {
|
||||
showError('email', 'Введите корректный email адрес');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('email');
|
||||
}
|
||||
|
||||
// Валидация телефона
|
||||
const phone = $('#phone').val();
|
||||
if (!validatePhone(phone)) {
|
||||
showError('phone', 'Введите номер в формате: +7(912)999-12-23');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('phone');
|
||||
}
|
||||
|
||||
// Валидация пароля
|
||||
const password = $('#password').val();
|
||||
if (!validatePassword(password)) {
|
||||
showError('password', 'Пароль должен содержать минимум 6 символов');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('password');
|
||||
}
|
||||
|
||||
// Проверка совпадения паролей
|
||||
const confirmPassword = $('#confirm-password').val();
|
||||
if (password !== confirmPassword) {
|
||||
showError('confirm-password', 'Пароли не совпадают');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('confirm-password');
|
||||
}
|
||||
|
||||
// Проверка согласия с условиями
|
||||
if (!$('#privacy').is(':checked')) {
|
||||
$('#privacy-error').show();
|
||||
isValid = false;
|
||||
} else {
|
||||
$('#privacy-error').hide();
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
// Реальная валидация при вводе
|
||||
$('input').on('blur', function() {
|
||||
const fieldId = $(this).attr('id');
|
||||
const value = $(this).val();
|
||||
|
||||
switch(fieldId) {
|
||||
case 'fio':
|
||||
if (!validateFIO(value)) {
|
||||
if (/\d/.test(value)) {
|
||||
showError(fieldId, 'ФИО не должно содержать цифры');
|
||||
} else {
|
||||
showError(fieldId, 'ФИО должно содержать минимум 2 слова');
|
||||
}
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'city':
|
||||
if (!validateCity(value)) {
|
||||
showError(fieldId, 'Укажите корректное название города');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'email':
|
||||
if (!validateEmail(value)) {
|
||||
showError(fieldId, 'Введите корректный email адрес');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'phone':
|
||||
if (!validatePhone(value)) {
|
||||
showError(fieldId, 'Введите номер в формате: +7(912)999-12-23');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'password':
|
||||
if (!validatePassword(value)) {
|
||||
showError(fieldId, 'Пароль должен содержать минимум 6 символов');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'confirm-password':
|
||||
const password = $('#password').val();
|
||||
if (value !== password) {
|
||||
showError(fieldId, 'Пароли не совпадают');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
// Обработка отправки формы
|
||||
$('#registrationForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
if (validateForm()) {
|
||||
const email = $('#email').val();
|
||||
const isAdmin = isAdminEmail(email);
|
||||
|
||||
// Сохраняем данные пользователя в localStorage
|
||||
const userData = {
|
||||
email: email,
|
||||
fio: $('#fio').val(),
|
||||
phone: $('#phone').val(),
|
||||
isAdmin: isAdmin,
|
||||
registered: new Date().toISOString()
|
||||
};
|
||||
|
||||
localStorage.setItem('userData', JSON.stringify(userData));
|
||||
localStorage.setItem('isLoggedIn', 'true');
|
||||
localStorage.setItem('isAdmin', isAdmin.toString());
|
||||
|
||||
// Эмуляция успешной регистрации
|
||||
showMessage('success', 'Регистрация прошла успешно! ' +
|
||||
(isAdmin ? 'Вы зарегистрированы как администратор.' : 'Добро пожаловать в AETERNA!'));
|
||||
|
||||
setTimeout(() => {
|
||||
// Перенаправление на главную страницу
|
||||
window.location.href = 'cite_mebel.php';
|
||||
}, 2000);
|
||||
} else {
|
||||
showMessage('error', 'Пожалуйста, исправьте ошибки в форме');
|
||||
}
|
||||
});
|
||||
|
||||
// Плавная прокрутка к якорям
|
||||
$('a[href^="#"]').on('click', function(event) {
|
||||
var target = $(this.getAttribute('href'));
|
||||
if (target.length) {
|
||||
event.preventDefault();
|
||||
$('html, body').stop().animate({
|
||||
scrollTop: target.offset().top
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
|
||||
// Переключение между регистрацией и входом
|
||||
$('.login-btn').on('click', function() {
|
||||
showMessage('warning', 'Переход к форме входа...');
|
||||
setTimeout(() => {
|
||||
window.location.href = 'вход.php';
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
// Обработка ссылки "Сменить пароль"
|
||||
$('.password-link').on('click', function(e) {
|
||||
e.preventDefault();
|
||||
showMessage('warning', 'Функция смены пароля будет доступна после регистрации');
|
||||
});
|
||||
|
||||
// Маска для телефона
|
||||
$('#phone').on('input', function() {
|
||||
let value = $(this).val().replace(/\D/g, '');
|
||||
if (value.startsWith('7') || value.startsWith('8')) {
|
||||
value = value.substring(1);
|
||||
}
|
||||
if (value.length > 0) {
|
||||
value = '+7(' + value;
|
||||
if (value.length > 6) value = value.substring(0, 6) + ')' + value.substring(6);
|
||||
if (value.length > 10) value = value.substring(0, 10) + '-' + value.substring(10);
|
||||
if (value.length > 13) value = value.substring(0, 13) + '-' + value.substring(13);
|
||||
if (value.length > 16) value = value.substring(0, 16);
|
||||
}
|
||||
$(this).val(value);
|
||||
});
|
||||
|
||||
// Запрет ввода цифр в поле ФИО
|
||||
$('#fio').on('input', function() {
|
||||
let value = $(this).val();
|
||||
// Удаляем цифры из значения
|
||||
value = value.replace(/\d/g, '');
|
||||
$(this).val(value);
|
||||
});
|
||||
});
|
||||
|
||||
// Для входа (файл вход.html)
|
||||
$(document).ready(function() {
|
||||
// Проверяем, если пользователь уже вошел
|
||||
if (localStorage.getItem('isLoggedIn') === 'true') {
|
||||
const userData = JSON.parse(localStorage.getItem('userData') || '{}');
|
||||
if (userData.email) {
|
||||
$('#login-email').val(userData.email);
|
||||
}
|
||||
}
|
||||
|
||||
// Функция проверки пароля администратора
|
||||
function checkAdminPassword(email, password) {
|
||||
// Административные аккаунты
|
||||
const adminAccounts = {
|
||||
'admin@aeterna.ru': 'admin123',
|
||||
'administrator@aeterna.ru': 'admin123',
|
||||
'aeterna@mail.ru': 'admin123'
|
||||
};
|
||||
|
||||
return adminAccounts[email.toLowerCase()] === password;
|
||||
}
|
||||
|
||||
// Валидация формы входа
|
||||
$('#loginForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
let isValid = true;
|
||||
const email = $('#login-email').val();
|
||||
const password = $('#login-password').val();
|
||||
|
||||
// Валидация email
|
||||
if (!isValidEmail(email)) {
|
||||
$('#email-error').show();
|
||||
isValid = false;
|
||||
} else {
|
||||
$('#email-error').hide();
|
||||
}
|
||||
|
||||
// Валидация пароля
|
||||
if (password.length < 6) {
|
||||
$('#password-error').show();
|
||||
isValid = false;
|
||||
} else {
|
||||
$('#password-error').hide();
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
// Здесь обычно отправка данных на сервер
|
||||
showMessage('success', 'Вы успешно вошли в систему!');
|
||||
|
||||
// Перенаправление на главную страницу через 1.5 секунды
|
||||
setTimeout(function() {
|
||||
window.location.href = 'cite_mebel.php';
|
||||
}, 1500);
|
||||
}
|
||||
});
|
||||
|
||||
// Функция показа сообщений
|
||||
function showMessage(type, text) {
|
||||
const messageId = type + 'Message';
|
||||
const $message = $('#' + messageId);
|
||||
|
||||
$message.text(text).show();
|
||||
|
||||
setTimeout(function() {
|
||||
$message.fadeOut();
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Скрываем сообщения об ошибках при фокусе на полях
|
||||
$('input').on('focus', function() {
|
||||
$(this).next('.error-message').hide();
|
||||
});
|
||||
|
||||
// Обработка чекбокса "Запомнить меня"
|
||||
$('#remember').on('change', function() {
|
||||
if ($(this).is(':checked')) {
|
||||
const email = $('#login-email').val();
|
||||
if (email) {
|
||||
localStorage.setItem('rememberedEmail', email);
|
||||
}
|
||||
} else {
|
||||
localStorage.removeItem('rememberedEmail');
|
||||
}
|
||||
});
|
||||
|
||||
// Автозаполнение email, если пользователь выбрал "Запомнить меня"
|
||||
const rememberedEmail = localStorage.getItem('rememberedEmail');
|
||||
if (rememberedEmail) {
|
||||
$('#login-email').val(rememberedEmail);
|
||||
$('#remember').prop('checked', true);
|
||||
}
|
||||
|
||||
// Обработка ссылки "Забыли пароль?"
|
||||
$('.forgot-password').on('click', function(e) {
|
||||
e.preventDefault();
|
||||
showMessage('info', 'Для восстановления пароля обратитесь к администратору');
|
||||
});
|
||||
});
|
||||
$(document).ready(function() {
|
||||
|
||||
function showMessage(type, text) {
|
||||
const messageId = type + 'Message';
|
||||
const $message = $('#' + messageId);
|
||||
$message.text(text).fadeIn(300);
|
||||
setTimeout(() => {
|
||||
$message.fadeOut(300);
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
function isAdminEmail(email) {
|
||||
const adminEmails = ['admin@aeterna.ru', 'administrator@aeterna.ru', 'aeterna@mail.ru'];
|
||||
return adminEmails.includes(email.toLowerCase());
|
||||
}
|
||||
|
||||
function validateFIO(fio) {
|
||||
const words = fio.trim().split(/\s+/);
|
||||
|
||||
const hasNoDigits = !/\d/.test(fio);
|
||||
return words.length >= 2 && words.every(word => word.length >= 2) && hasNoDigits;
|
||||
}
|
||||
|
||||
function validateCity(city) {
|
||||
return city.trim().length >= 2 && /^[а-яА-ЯёЁ\s-]+$/.test(city);
|
||||
}
|
||||
|
||||
function validateEmail(email) {
|
||||
const localPart = email.split('@')[0];
|
||||
|
||||
if (/[а-яА-ЯёЁ]/.test(localPart)) {
|
||||
showError('email', 'В тексте перед знаком "@" не должно быть кириллических символов');
|
||||
return false;
|
||||
}
|
||||
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
showError('email', 'Введите корректный email адрес');
|
||||
return false;
|
||||
}
|
||||
|
||||
hideError('email');
|
||||
return true;
|
||||
}
|
||||
|
||||
function validatePhone(phone) {
|
||||
const phoneRegex = /^(\+7|8)[\s-]?\(?\d{3}\)?[\s-]?\d{3}[\s-]?\d{2}[\s-]?\d{2}$/;
|
||||
return phoneRegex.test(phone.replace(/\s/g, ''));
|
||||
}
|
||||
|
||||
function validatePassword(password) {
|
||||
return password.length >= 6;
|
||||
}
|
||||
|
||||
function showError(fieldId, message) {
|
||||
$('#' + fieldId).addClass('error');
|
||||
$('#' + fieldId + '-error').text(message).show();
|
||||
}
|
||||
|
||||
function hideError(fieldId) {
|
||||
$('#' + fieldId).removeClass('error');
|
||||
$('#' + fieldId + '-error').hide();
|
||||
}
|
||||
|
||||
function validateForm() {
|
||||
let isValid = true;
|
||||
|
||||
const fio = $('#fio').val();
|
||||
if (!validateFIO(fio)) {
|
||||
if (/\d/.test(fio)) {
|
||||
showError('fio', 'ФИО не должно содержать цифры');
|
||||
} else {
|
||||
showError('fio', 'ФИО должно содержать минимум 2 слова (каждое от 2 символов)');
|
||||
}
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('fio');
|
||||
}
|
||||
|
||||
const city = $('#city').val();
|
||||
if (!validateCity(city)) {
|
||||
showError('city', 'Укажите корректное название города (только русские буквы)');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('city');
|
||||
}
|
||||
|
||||
const email = $('#email').val();
|
||||
if (!validateEmail(email)) {
|
||||
showError('email', 'Введите корректный email адрес');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('email');
|
||||
}
|
||||
|
||||
const phone = $('#phone').val();
|
||||
if (!validatePhone(phone)) {
|
||||
showError('phone', 'Введите номер в формате: +7(912)999-12-23');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('phone');
|
||||
}
|
||||
|
||||
const password = $('#password').val();
|
||||
if (!validatePassword(password)) {
|
||||
showError('password', 'Пароль должен содержать минимум 6 символов');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('password');
|
||||
}
|
||||
|
||||
const confirmPassword = $('#confirm-password').val();
|
||||
if (password !== confirmPassword) {
|
||||
showError('confirm-password', 'Пароли не совпадают');
|
||||
isValid = false;
|
||||
} else {
|
||||
hideError('confirm-password');
|
||||
}
|
||||
|
||||
if (!$('#privacy').is(':checked')) {
|
||||
$('#privacy-error').show();
|
||||
isValid = false;
|
||||
} else {
|
||||
$('#privacy-error').hide();
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
$('input').on('blur', function() {
|
||||
const fieldId = $(this).attr('id');
|
||||
const value = $(this).val();
|
||||
|
||||
switch(fieldId) {
|
||||
case 'fio':
|
||||
if (!validateFIO(value)) {
|
||||
if (/\d/.test(value)) {
|
||||
showError(fieldId, 'ФИО не должно содержать цифры');
|
||||
} else {
|
||||
showError(fieldId, 'ФИО должно содержать минимум 2 слова');
|
||||
}
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'city':
|
||||
if (!validateCity(value)) {
|
||||
showError(fieldId, 'Укажите корректное название города');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'email':
|
||||
if (!validateEmail(value)) {
|
||||
showError(fieldId, 'Введите корректный email адрес');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'phone':
|
||||
if (!validatePhone(value)) {
|
||||
showError(fieldId, 'Введите номер в формате: +7(912)999-12-23');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'password':
|
||||
if (!validatePassword(value)) {
|
||||
showError(fieldId, 'Пароль должен содержать минимум 6 символов');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
case 'confirm-password':
|
||||
const password = $('#password').val();
|
||||
if (value !== password) {
|
||||
showError(fieldId, 'Пароли не совпадают');
|
||||
} else {
|
||||
hideError(fieldId);
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
$('#registrationForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
if (validateForm()) {
|
||||
const email = $('#email').val();
|
||||
const isAdmin = isAdminEmail(email);
|
||||
|
||||
const userData = {
|
||||
email: email,
|
||||
fio: $('#fio').val(),
|
||||
phone: $('#phone').val(),
|
||||
isAdmin: isAdmin,
|
||||
registered: new Date().toISOString()
|
||||
};
|
||||
|
||||
localStorage.setItem('userData', JSON.stringify(userData));
|
||||
localStorage.setItem('isLoggedIn', 'true');
|
||||
localStorage.setItem('isAdmin', isAdmin.toString());
|
||||
|
||||
showMessage('success', 'Регистрация прошла успешно! ' +
|
||||
(isAdmin ? 'Вы зарегистрированы как администратор.' : 'Добро пожаловать в AETERNA!'));
|
||||
|
||||
setTimeout(() => {
|
||||
|
||||
window.location.href = 'cite_mebel.php';
|
||||
}, 2000);
|
||||
} else {
|
||||
showMessage('error', 'Пожалуйста, исправьте ошибки в форме');
|
||||
}
|
||||
});
|
||||
|
||||
$('a[href^="#"]').on('click', function(event) {
|
||||
var target = $(this.getAttribute('href'));
|
||||
if (target.length) {
|
||||
event.preventDefault();
|
||||
$('html, body').stop().animate({
|
||||
scrollTop: target.offset().top
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
|
||||
$('.login-btn').on('click', function() {
|
||||
showMessage('warning', 'Переход к форме входа...');
|
||||
setTimeout(() => {
|
||||
window.location.href = 'вход.php';
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
$('.password-link').on('click', function(e) {
|
||||
e.preventDefault();
|
||||
showMessage('warning', 'Функция смены пароля будет доступна после регистрации');
|
||||
});
|
||||
|
||||
$('#phone').on('input', function() {
|
||||
let value = $(this).val().replace(/\D/g, '');
|
||||
if (value.startsWith('7') || value.startsWith('8')) {
|
||||
value = value.substring(1);
|
||||
}
|
||||
if (value.length > 0) {
|
||||
value = '+7(' + value;
|
||||
if (value.length > 6) value = value.substring(0, 6) + ')' + value.substring(6);
|
||||
if (value.length > 10) value = value.substring(0, 10) + '-' + value.substring(10);
|
||||
if (value.length > 13) value = value.substring(0, 13) + '-' + value.substring(13);
|
||||
if (value.length > 16) value = value.substring(0, 16);
|
||||
}
|
||||
$(this).val(value);
|
||||
});
|
||||
|
||||
$('#fio').on('input', function() {
|
||||
let value = $(this).val();
|
||||
|
||||
value = value.replace(/\d/g, '');
|
||||
$(this).val(value);
|
||||
});
|
||||
});
|
||||
|
||||
$(document).ready(function() {
|
||||
|
||||
if (localStorage.getItem('isLoggedIn') === 'true') {
|
||||
const userData = JSON.parse(localStorage.getItem('userData') || '{}');
|
||||
if (userData.email) {
|
||||
$('#login-email').val(userData.email);
|
||||
}
|
||||
}
|
||||
|
||||
function checkAdminPassword(email, password) {
|
||||
|
||||
const adminAccounts = {
|
||||
'admin@aeterna.ru': 'admin123',
|
||||
'administrator@aeterna.ru': 'admin123',
|
||||
'aeterna@mail.ru': 'admin123'
|
||||
};
|
||||
|
||||
return adminAccounts[email.toLowerCase()] === password;
|
||||
}
|
||||
|
||||
$('#loginForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
let isValid = true;
|
||||
const email = $('#login-email').val();
|
||||
const password = $('#login-password').val();
|
||||
|
||||
if (!isValidEmail(email)) {
|
||||
$('#email-error').show();
|
||||
isValid = false;
|
||||
} else {
|
||||
$('#email-error').hide();
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
$('#password-error').show();
|
||||
isValid = false;
|
||||
} else {
|
||||
$('#password-error').hide();
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
|
||||
showMessage('success', 'Вы успешно вошли в систему!');
|
||||
|
||||
setTimeout(function() {
|
||||
window.location.href = 'cite_mebel.php';
|
||||
}, 1500);
|
||||
}
|
||||
});
|
||||
|
||||
function showMessage(type, text) {
|
||||
const messageId = type + 'Message';
|
||||
const $message = $('#' + messageId);
|
||||
|
||||
$message.text(text).show();
|
||||
|
||||
setTimeout(function() {
|
||||
$message.fadeOut();
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
$('input').on('focus', function() {
|
||||
$(this).next('.error-message').hide();
|
||||
});
|
||||
|
||||
$('#remember').on('change', function() {
|
||||
if ($(this).is(':checked')) {
|
||||
const email = $('#login-email').val();
|
||||
if (email) {
|
||||
localStorage.setItem('rememberedEmail', email);
|
||||
}
|
||||
} else {
|
||||
localStorage.removeItem('rememberedEmail');
|
||||
}
|
||||
});
|
||||
|
||||
const rememberedEmail = localStorage.getItem('rememberedEmail');
|
||||
if (rememberedEmail) {
|
||||
$('#login-email').val(rememberedEmail);
|
||||
$('#remember').prop('checked', true);
|
||||
}
|
||||
|
||||
$('.forgot-password').on('click', function(e) {
|
||||
e.preventDefault();
|
||||
showMessage('info', 'Для восстановления пароля обратитесь к администратору');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,142 +1,137 @@
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
/* Стили для сообщений внизу страницы */
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Дополнительные стили для формы регистрации */
|
||||
.input-group {
|
||||
position: relative;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.profile-form input.error {
|
||||
border-color: #ff0000;
|
||||
background-color: #fff5f5;
|
||||
}
|
||||
|
||||
.privacy-checkbox {
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.privacy-checkbox label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.privacy-checkbox input[type="checkbox"] {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Исправление отступов для страницы регистрации */
|
||||
.profile-page-main {
|
||||
padding: 40px 0;
|
||||
min-height: calc(100vh - 200px);
|
||||
}
|
||||
|
||||
/* Убедимся, что контейнер не перекрывает шапку и футер */
|
||||
.profile-container {
|
||||
margin: 0 auto;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.input-hint {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
/* Стили для страницы входа */
|
||||
.form-options {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.remember-me {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
}
|
||||
|
||||
.remember-me input[type="checkbox"] {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.forgot-password {
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.forgot-password:hover {
|
||||
color: #617365;
|
||||
text-decoration: none;
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.input-group {
|
||||
position: relative;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.profile-form input.error {
|
||||
border-color: #ff0000;
|
||||
background-color: #fff5f5;
|
||||
}
|
||||
|
||||
.privacy-checkbox {
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.privacy-checkbox label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.privacy-checkbox input[type="checkbox"] {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.profile-page-main {
|
||||
padding: 40px 0;
|
||||
min-height: calc(100vh - 200px);
|
||||
}
|
||||
|
||||
.profile-container {
|
||||
margin: 0 auto;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.input-hint {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.form-options {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.remember-me {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
}
|
||||
|
||||
.remember-me input[type="checkbox"] {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.forgot-password {
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.forgot-password:hover {
|
||||
color: #617365;
|
||||
text-decoration: none;
|
||||
}
|
||||
@@ -83,4 +83,3 @@
|
||||
border-color: @color-primary;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
2647
public/catalog.php
2647
public/catalog.php
File diff suppressed because it is too large
Load Diff
@@ -1,114 +1,107 @@
|
||||
// check_auth.js
|
||||
$(document).ready(function() {
|
||||
// Проверка авторизации при загрузке страницы
|
||||
checkAuthStatus();
|
||||
|
||||
// Обработка формы входа
|
||||
$('#loginForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const email = $('#login-email').val();
|
||||
const password = $('#login-password').val();
|
||||
const remember = $('#remember').is(':checked');
|
||||
|
||||
$.ajax({
|
||||
url: 'login_handler.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
email: email,
|
||||
password: password
|
||||
},
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.success) {
|
||||
// Сохраняем в localStorage если выбрано "Запомнить меня"
|
||||
if (remember) {
|
||||
localStorage.setItem('rememberedEmail', email);
|
||||
} else {
|
||||
localStorage.removeItem('rememberedEmail');
|
||||
}
|
||||
|
||||
// Перенаправляем
|
||||
window.location.href = result.redirect || 'catalog.php';
|
||||
} else {
|
||||
showMessage('error', result.message || 'Ошибка авторизации');
|
||||
}
|
||||
} catch(e) {
|
||||
showMessage('error', 'Ошибка обработки ответа');
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
showMessage('error', 'Ошибка сервера');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Проверка статуса авторизации
|
||||
function checkAuthStatus() {
|
||||
$.ajax({
|
||||
url: 'check_auth_status.php',
|
||||
method: 'GET',
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.loggedIn) {
|
||||
updateUserProfile(result.user);
|
||||
}
|
||||
} catch(e) {
|
||||
console.error('Ошибка проверки авторизации', e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Обновление профиля пользователя
|
||||
function updateUserProfile(user) {
|
||||
// Обновляем шапку, если есть элементы для профиля
|
||||
if ($('#userEmail').length) {
|
||||
$('#userEmail').text(user.email);
|
||||
}
|
||||
if ($('#userName').length) {
|
||||
$('#userName').text(user.full_name);
|
||||
}
|
||||
}
|
||||
|
||||
// Показать сообщение
|
||||
function showMessage(type, text) {
|
||||
const $message = $('#' + type + 'Message');
|
||||
if ($message.length) {
|
||||
$message.text(text).fadeIn();
|
||||
setTimeout(() => $message.fadeOut(), 5000);
|
||||
} else {
|
||||
alert(text);
|
||||
}
|
||||
}
|
||||
|
||||
// Проверка авторизации для ссылок
|
||||
function checkAuth(redirectUrl) {
|
||||
$.ajax({
|
||||
url: 'check_auth_status.php',
|
||||
method: 'GET',
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.loggedIn) {
|
||||
window.location.href = redirectUrl;
|
||||
} else {
|
||||
// Показываем модальное окно или перенаправляем на вход
|
||||
showLoginModal(redirectUrl);
|
||||
}
|
||||
} catch(e) {
|
||||
showLoginModal(redirectUrl);
|
||||
}
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
// Показать модальное окно входа
|
||||
function showLoginModal(redirectUrl) {
|
||||
// Можно реализовать модальное окно или перенаправить на страницу входа
|
||||
window.location.href = 'вход.php?redirect=' + encodeURIComponent(redirectUrl);
|
||||
}
|
||||
});
|
||||
|
||||
$(document).ready(function() {
|
||||
|
||||
checkAuthStatus();
|
||||
|
||||
$('#loginForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const email = $('#login-email').val();
|
||||
const password = $('#login-password').val();
|
||||
const remember = $('#remember').is(':checked');
|
||||
|
||||
$.ajax({
|
||||
url: 'login_handler.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
email: email,
|
||||
password: password
|
||||
},
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.success) {
|
||||
|
||||
if (remember) {
|
||||
localStorage.setItem('rememberedEmail', email);
|
||||
} else {
|
||||
localStorage.removeItem('rememberedEmail');
|
||||
}
|
||||
|
||||
window.location.href = result.redirect || 'catalog.php';
|
||||
} else {
|
||||
showMessage('error', result.message || 'Ошибка авторизации');
|
||||
}
|
||||
} catch(e) {
|
||||
showMessage('error', 'Ошибка обработки ответа');
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
showMessage('error', 'Ошибка сервера');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function checkAuthStatus() {
|
||||
$.ajax({
|
||||
url: 'check_auth_status.php',
|
||||
method: 'GET',
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.loggedIn) {
|
||||
updateUserProfile(result.user);
|
||||
}
|
||||
} catch(e) {
|
||||
console.error('Ошибка проверки авторизации', e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function updateUserProfile(user) {
|
||||
|
||||
if ($('#userEmail').length) {
|
||||
$('#userEmail').text(user.email);
|
||||
}
|
||||
if ($('#userName').length) {
|
||||
$('#userName').text(user.full_name);
|
||||
}
|
||||
}
|
||||
|
||||
function showMessage(type, text) {
|
||||
const $message = $('#' + type + 'Message');
|
||||
if ($message.length) {
|
||||
$message.text(text).fadeIn();
|
||||
setTimeout(() => $message.fadeOut(), 5000);
|
||||
} else {
|
||||
alert(text);
|
||||
}
|
||||
}
|
||||
|
||||
function checkAuth(redirectUrl) {
|
||||
$.ajax({
|
||||
url: 'check_auth_status.php',
|
||||
method: 'GET',
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.loggedIn) {
|
||||
window.location.href = redirectUrl;
|
||||
} else {
|
||||
|
||||
showLoginModal(redirectUrl);
|
||||
}
|
||||
} catch(e) {
|
||||
showLoginModal(redirectUrl);
|
||||
}
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
function showLoginModal(redirectUrl) {
|
||||
|
||||
window.location.href = 'вход.php?redirect=' + encodeURIComponent(redirectUrl);
|
||||
}
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,114 +1,107 @@
|
||||
// check_auth.js
|
||||
$(document).ready(function() {
|
||||
// Проверка авторизации при загрузке страницы
|
||||
checkAuthStatus();
|
||||
|
||||
// Обработка формы входа
|
||||
$('#loginForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const email = $('#login-email').val();
|
||||
const password = $('#login-password').val();
|
||||
const remember = $('#remember').is(':checked');
|
||||
|
||||
$.ajax({
|
||||
url: 'login_handler.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
email: email,
|
||||
password: password
|
||||
},
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.success) {
|
||||
// Сохраняем в localStorage если выбрано "Запомнить меня"
|
||||
if (remember) {
|
||||
localStorage.setItem('rememberedEmail', email);
|
||||
} else {
|
||||
localStorage.removeItem('rememberedEmail');
|
||||
}
|
||||
|
||||
// Перенаправляем
|
||||
window.location.href = result.redirect || 'catalog.php';
|
||||
} else {
|
||||
showMessage('error', result.message || 'Ошибка авторизации');
|
||||
}
|
||||
} catch(e) {
|
||||
showMessage('error', 'Ошибка обработки ответа');
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
showMessage('error', 'Ошибка сервера');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Проверка статуса авторизации
|
||||
function checkAuthStatus() {
|
||||
$.ajax({
|
||||
url: 'check_auth_status.php',
|
||||
method: 'GET',
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.loggedIn) {
|
||||
updateUserProfile(result.user);
|
||||
}
|
||||
} catch(e) {
|
||||
console.error('Ошибка проверки авторизации', e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Обновление профиля пользователя
|
||||
function updateUserProfile(user) {
|
||||
// Обновляем шапку, если есть элементы для профиля
|
||||
if ($('#userEmail').length) {
|
||||
$('#userEmail').text(user.email);
|
||||
}
|
||||
if ($('#userName').length) {
|
||||
$('#userName').text(user.full_name);
|
||||
}
|
||||
}
|
||||
|
||||
// Показать сообщение
|
||||
function showMessage(type, text) {
|
||||
const $message = $('#' + type + 'Message');
|
||||
if ($message.length) {
|
||||
$message.text(text).fadeIn();
|
||||
setTimeout(() => $message.fadeOut(), 5000);
|
||||
} else {
|
||||
alert(text);
|
||||
}
|
||||
}
|
||||
|
||||
// Проверка авторизации для ссылок
|
||||
function checkAuth(redirectUrl) {
|
||||
$.ajax({
|
||||
url: 'check_auth_status.php',
|
||||
method: 'GET',
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.loggedIn) {
|
||||
window.location.href = redirectUrl;
|
||||
} else {
|
||||
// Показываем модальное окно или перенаправляем на вход
|
||||
showLoginModal(redirectUrl);
|
||||
}
|
||||
} catch(e) {
|
||||
showLoginModal(redirectUrl);
|
||||
}
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
// Показать модальное окно входа
|
||||
function showLoginModal(redirectUrl) {
|
||||
// Можно реализовать модальное окно или перенаправить на страницу входа
|
||||
window.location.href = 'вход.php?redirect=' + encodeURIComponent(redirectUrl);
|
||||
}
|
||||
});
|
||||
|
||||
$(document).ready(function() {
|
||||
|
||||
checkAuthStatus();
|
||||
|
||||
$('#loginForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const email = $('#login-email').val();
|
||||
const password = $('#login-password').val();
|
||||
const remember = $('#remember').is(':checked');
|
||||
|
||||
$.ajax({
|
||||
url: 'login_handler.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
email: email,
|
||||
password: password
|
||||
},
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.success) {
|
||||
|
||||
if (remember) {
|
||||
localStorage.setItem('rememberedEmail', email);
|
||||
} else {
|
||||
localStorage.removeItem('rememberedEmail');
|
||||
}
|
||||
|
||||
window.location.href = result.redirect || 'catalog.php';
|
||||
} else {
|
||||
showMessage('error', result.message || 'Ошибка авторизации');
|
||||
}
|
||||
} catch(e) {
|
||||
showMessage('error', 'Ошибка обработки ответа');
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
showMessage('error', 'Ошибка сервера');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function checkAuthStatus() {
|
||||
$.ajax({
|
||||
url: 'check_auth_status.php',
|
||||
method: 'GET',
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.loggedIn) {
|
||||
updateUserProfile(result.user);
|
||||
}
|
||||
} catch(e) {
|
||||
console.error('Ошибка проверки авторизации', e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function updateUserProfile(user) {
|
||||
|
||||
if ($('#userEmail').length) {
|
||||
$('#userEmail').text(user.email);
|
||||
}
|
||||
if ($('#userName').length) {
|
||||
$('#userName').text(user.full_name);
|
||||
}
|
||||
}
|
||||
|
||||
function showMessage(type, text) {
|
||||
const $message = $('#' + type + 'Message');
|
||||
if ($message.length) {
|
||||
$message.text(text).fadeIn();
|
||||
setTimeout(() => $message.fadeOut(), 5000);
|
||||
} else {
|
||||
alert(text);
|
||||
}
|
||||
}
|
||||
|
||||
function checkAuth(redirectUrl) {
|
||||
$.ajax({
|
||||
url: 'check_auth_status.php',
|
||||
method: 'GET',
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.loggedIn) {
|
||||
window.location.href = redirectUrl;
|
||||
} else {
|
||||
|
||||
showLoginModal(redirectUrl);
|
||||
}
|
||||
} catch(e) {
|
||||
showLoginModal(redirectUrl);
|
||||
}
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
function showLoginModal(redirectUrl) {
|
||||
|
||||
window.location.href = 'вход.php?redirect=' + encodeURIComponent(redirectUrl);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
<?php
|
||||
// config/database.php
|
||||
class Database {
|
||||
private static $instance = null;
|
||||
private $connection;
|
||||
|
||||
private function __construct() {
|
||||
try {
|
||||
$this->connection = new PDO(
|
||||
"pgsql:host=185.130.224.177;port=5481;dbname=postgres",
|
||||
"admin",
|
||||
"38feaad2840ccfda0e71243a6faaecfd"
|
||||
);
|
||||
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$this->connection->exec("SET NAMES 'utf8'");
|
||||
} catch(PDOException $e) {
|
||||
die("Ошибка подключения: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static function getInstance() {
|
||||
if (self::$instance == null) {
|
||||
self::$instance = new Database();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public function getConnection() {
|
||||
return $this->connection;
|
||||
}
|
||||
}
|
||||
<?php
|
||||
|
||||
class Database {
|
||||
private static $instance = null;
|
||||
private $connection;
|
||||
|
||||
private function __construct() {
|
||||
try {
|
||||
$this->connection = new PDO(
|
||||
"pgsql:host=185.130.224.177;port=5481;dbname=postgres",
|
||||
"admin",
|
||||
"38feaad2840ccfda0e71243a6faaecfd"
|
||||
);
|
||||
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$this->connection->exec("SET NAMES 'utf8'");
|
||||
} catch(PDOException $e) {
|
||||
die("Ошибка подключения: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static function getInstance() {
|
||||
if (self::$instance == null) {
|
||||
self::$instance = new Database();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public function getConnection() {
|
||||
return $this->connection;
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -1,174 +1,174 @@
|
||||
<?php
|
||||
// В начале файла
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>AETERNA - Доставка и оплата</title>
|
||||
<link rel="stylesheet/less" type="text/css" href="style_for_cite.less">
|
||||
<script src="https://cdn.jsdelivr.net/npm/less"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<script src="check_auth.js"></script>
|
||||
<style>
|
||||
/* Стили для блокировки доступа */
|
||||
.link-disabled {
|
||||
cursor: not-allowed !important;
|
||||
opacity: 0.7 !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
.auth-required {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.auth-required::after {
|
||||
content: "🔒";
|
||||
position: absolute;
|
||||
top: -5px;
|
||||
right: -10px;
|
||||
font-size: 10px;
|
||||
}
|
||||
</style>
|
||||
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<?php include 'header_common.php'; ?>
|
||||
|
||||
<main class="catalog-main">
|
||||
<div class="container">
|
||||
<div class="breadcrumbs">
|
||||
<a href="cite_mebel.php">Главная</a> • <span class="current-page">Доставка и оплата</span>
|
||||
</div>
|
||||
|
||||
<div class="delivery-content">
|
||||
<h1>ДОСТАВКА И ОПЛАТА</h1>
|
||||
|
||||
<div class="delivery-section">
|
||||
<div class="delivery-card">
|
||||
<div class="delivery-icon">
|
||||
<i class="fas fa-truck"></i>
|
||||
</div>
|
||||
<h3>Курьерская доставка</h3>
|
||||
<div class="delivery-details">
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Бесплатная доставка:</span>
|
||||
<span class="detail-value">при заказе от 30 000 ₽</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">В пределах МКАД:</span>
|
||||
<span class="detail-value">1 500 ₽</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">За МКАД:</span>
|
||||
<span class="detail-value">1 500 ₽ + 50 ₽/км</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Время доставки:</span>
|
||||
<span class="detail-value">с 9:00 до 21:00</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="delivery-card">
|
||||
<div class="delivery-icon">
|
||||
<i class="fas fa-store"></i>
|
||||
</div>
|
||||
<h3>Самовывоз из шоурума</h3>
|
||||
<div class="delivery-details">
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Адрес:</span>
|
||||
<span class="detail-value">г. Москва, ул. Дизайнерская, 15</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Стоимость:</span>
|
||||
<span class="detail-value">Бесплатно</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Время получения:</span>
|
||||
<span class="detail-value">в течение 2 часов после подтверждения</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Парковка:</span>
|
||||
<span class="detail-value">Бесплатная для клиентов</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="delivery-card">
|
||||
<div class="delivery-icon">
|
||||
<i class="fas fa-map-marked-alt"></i>
|
||||
</div>
|
||||
<h3>Доставка по России</h3>
|
||||
<div class="delivery-details">
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Стоимость:</span>
|
||||
<span class="detail-value">рассчитывается индивидуально</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Сроки:</span>
|
||||
<span class="detail-value">от 3 до 14 дней</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Транспортные компании:</span>
|
||||
<span class="detail-value">СДЭК, Boxberry, Деловые Линии</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="footer" id="footer">
|
||||
<div class="container footer__content">
|
||||
<div class="footer__col footer__col--logo">
|
||||
<div class="logo">AETERNA</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОКУПАТЕЛЮ</h5>
|
||||
<ul>
|
||||
<li><a href="/catalog.php">Каталог</a></li>
|
||||
<li><a href="services.php">Услуги</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОМОЩЬ</h5>
|
||||
<ul>
|
||||
<li><a href="доставка.php">Доставка и оплата</a></li>
|
||||
<li><a href="гарантия.php">Гарантия и возврат</a></li>
|
||||
<li><a href="cite_mebel.php#faq">Ответы на вопросы</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>КОНТАКТЫ</h5>
|
||||
<p>aeterna@mail.ru</p>
|
||||
<p>+7(912)999-12-23</p>
|
||||
<div class="social-icons">
|
||||
<span class="icon"><i class="fab fa-telegram"></i></span>
|
||||
<span class="icon"><i class="fab fa-instagram"></i></span>
|
||||
<span class="icon"><i class="fab fa-vk"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПРИНИМАЕМ К ОПЛАТЕ</h5>
|
||||
<div class="payment-icons">
|
||||
<span class="pay-icon"><i class="fab fa-cc-visa"></i></span>
|
||||
<span class="pay-icon"><i class="fab fa-cc-mastercard"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="copyright">
|
||||
<p>© 2025 AETERNA. Все права защищены.</p>
|
||||
</div>
|
||||
</footer>
|
||||
</body>
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>AETERNA - Доставка и оплата</title>
|
||||
<link rel="stylesheet/less" type="text/css" href="style_for_cite.less">
|
||||
<script src="https://cdn.jsdelivr.net/npm/less"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<script src="check_auth.js"></script>
|
||||
<style>
|
||||
|
||||
.link-disabled {
|
||||
cursor: not-allowed !important;
|
||||
opacity: 0.7 !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
.auth-required {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.auth-required::after {
|
||||
content: "🔒";
|
||||
position: absolute;
|
||||
top: -5px;
|
||||
right: -10px;
|
||||
font-size: 10px;
|
||||
}
|
||||
</style>
|
||||
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<?php include 'header_common.php'; ?>
|
||||
|
||||
<main class="catalog-main">
|
||||
<div class="container">
|
||||
<div class="breadcrumbs">
|
||||
<a href="cite_mebel.php">Главная</a> • <span class="current-page">Доставка и оплата</span>
|
||||
</div>
|
||||
|
||||
<div class="delivery-content">
|
||||
<h1>ДОСТАВКА И ОПЛАТА</h1>
|
||||
|
||||
<div class="delivery-section">
|
||||
<div class="delivery-card">
|
||||
<div class="delivery-icon">
|
||||
<i class="fas fa-truck"></i>
|
||||
</div>
|
||||
<h3>Курьерская доставка</h3>
|
||||
<div class="delivery-details">
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Бесплатная доставка:</span>
|
||||
<span class="detail-value">при заказе от 30 000 ₽</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">В пределах МКАД:</span>
|
||||
<span class="detail-value">1 500 ₽</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">За МКАД:</span>
|
||||
<span class="detail-value">1 500 ₽ + 50 ₽/км</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Время доставки:</span>
|
||||
<span class="detail-value">с 9:00 до 21:00</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="delivery-card">
|
||||
<div class="delivery-icon">
|
||||
<i class="fas fa-store"></i>
|
||||
</div>
|
||||
<h3>Самовывоз из шоурума</h3>
|
||||
<div class="delivery-details">
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Адрес:</span>
|
||||
<span class="detail-value">г. Москва, ул. Дизайнерская, 15</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Стоимость:</span>
|
||||
<span class="detail-value">Бесплатно</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Время получения:</span>
|
||||
<span class="detail-value">в течение 2 часов после подтверждения</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Парковка:</span>
|
||||
<span class="detail-value">Бесплатная для клиентов</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="delivery-card">
|
||||
<div class="delivery-icon">
|
||||
<i class="fas fa-map-marked-alt"></i>
|
||||
</div>
|
||||
<h3>Доставка по России</h3>
|
||||
<div class="delivery-details">
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Стоимость:</span>
|
||||
<span class="detail-value">рассчитывается индивидуально</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Сроки:</span>
|
||||
<span class="detail-value">от 3 до 14 дней</span>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<span class="detail-label">Транспортные компании:</span>
|
||||
<span class="detail-value">СДЭК, Boxberry, Деловые Линии</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="footer" id="footer">
|
||||
<div class="container footer__content">
|
||||
<div class="footer__col footer__col--logo">
|
||||
<div class="logo">AETERNA</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОКУПАТЕЛЮ</h5>
|
||||
<ul>
|
||||
<li><a href="/catalog.php">Каталог</a></li>
|
||||
<li><a href="services.php">Услуги</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОМОЩЬ</h5>
|
||||
<ul>
|
||||
<li><a href="доставка.php">Доставка и оплата</a></li>
|
||||
<li><a href="гарантия.php">Гарантия и возврат</a></li>
|
||||
<li><a href="cite_mebel.php#faq">Ответы на вопросы</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>КОНТАКТЫ</h5>
|
||||
<p>aeterna@mail.ru</p>
|
||||
<p>+7(912)999-12-23</p>
|
||||
<div class="social-icons">
|
||||
<span class="icon"><i class="fab fa-telegram"></i></span>
|
||||
<span class="icon"><i class="fab fa-instagram"></i></span>
|
||||
<span class="icon"><i class="fab fa-vk"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПРИНИМАЕМ К ОПЛАТЕ</h5>
|
||||
<div class="payment-icons">
|
||||
<span class="pay-icon"><i class="fab fa-cc-visa"></i></span>
|
||||
<span class="pay-icon"><i class="fab fa-cc-mastercard"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="copyright">
|
||||
<p>© 2025 AETERNA. Все права защищены.</p>
|
||||
</div>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -47,4 +47,3 @@
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
<?php
|
||||
/**
|
||||
* Единый header для страниц AETERNA (версия для public/)
|
||||
* Подключение: include 'header_common.php';
|
||||
*/
|
||||
|
||||
// Запускаем сессию если еще не запущена
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
// Определяем текущую страницу
|
||||
$currentPage = basename($_SERVER['PHP_SELF'], '.php');
|
||||
|
||||
// Проверяем авторизацию
|
||||
$isLoggedIn = isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] === true;
|
||||
$isAdmin = isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true;
|
||||
$userEmail = $_SESSION['user_email'] ?? '';
|
||||
@@ -49,13 +42,12 @@ $fullName = $_SESSION['full_name'] ?? $userEmail;
|
||||
|
||||
<div class="header__icons--top">
|
||||
<?php if ($isLoggedIn): ?>
|
||||
<!-- Иконка корзины -->
|
||||
|
||||
<a href="checkout.php" class="icon cart-icon">
|
||||
<i class="fas fa-shopping-cart"></i>
|
||||
<span class="cart-count" id="cartCount">0</span>
|
||||
</a>
|
||||
|
||||
<!-- Блок профиля -->
|
||||
<div class="user-profile-dropdown">
|
||||
<div class="user-profile-toggle" id="profileToggle">
|
||||
<div class="user-avatar"><?= !empty($userEmail) ? strtoupper(substr($userEmail, 0, 1)) : 'U' ?></div>
|
||||
@@ -111,7 +103,7 @@ $fullName = $_SESSION['full_name'] ?? $userEmail;
|
||||
</header>
|
||||
|
||||
<style>
|
||||
/* Стили для профиля пользователя */
|
||||
|
||||
.user-profile-dropdown { position: relative; display: inline-block; }
|
||||
.user-profile-toggle { display: flex; align-items: center; gap: 10px; cursor: pointer; padding: 8px 12px; border-radius: 4px; transition: all 0.3s ease; }
|
||||
.user-profile-toggle:hover { background-color: rgba(0, 0, 0, 0.05); }
|
||||
@@ -137,19 +129,18 @@ $fullName = $_SESSION['full_name'] ?? $userEmail;
|
||||
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
// Профиль пользователя - открытие/закрытие
|
||||
|
||||
$('#profileToggle').click(function(e) {
|
||||
e.stopPropagation();
|
||||
$('#profileMenu').toggle();
|
||||
});
|
||||
|
||||
|
||||
$(document).click(function(e) {
|
||||
if (!$(e.target).closest('.user-profile-dropdown').length) {
|
||||
$('#profileMenu').hide();
|
||||
}
|
||||
});
|
||||
|
||||
// Обновление счетчика корзины
|
||||
<?php if ($isLoggedIn): ?>
|
||||
$.ajax({
|
||||
url: 'api/cart.php?action=count',
|
||||
@@ -166,4 +157,3 @@ $(document).ready(function() {
|
||||
<?php endif; ?>
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,62 +1,61 @@
|
||||
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
/* Стили для сообщений внизу страницы */
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@@ -1,62 +1,61 @@
|
||||
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
/* Стили для сообщений внизу страницы */
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
<?php
|
||||
/**
|
||||
* Функции авторизации для AETERNA
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
/**
|
||||
* Авторизация пользователя
|
||||
*/
|
||||
function loginUser(string $email, string $password): array {
|
||||
$db = Database::getInstance()->getConnection();
|
||||
|
||||
|
||||
try {
|
||||
$stmt = $db->prepare("
|
||||
SELECT user_id, email, password_hash, full_name, phone, city, is_admin, is_active
|
||||
@@ -31,7 +25,6 @@ function loginUser(string $email, string $password): array {
|
||||
return ['success' => false, 'message' => 'Неверный пароль'];
|
||||
}
|
||||
|
||||
// Сохраняем в сессию
|
||||
$_SESSION['user_id'] = $user['user_id'];
|
||||
$_SESSION['user_email'] = $user['email'];
|
||||
$_SESSION['full_name'] = $user['full_name'];
|
||||
@@ -41,7 +34,6 @@ function loginUser(string $email, string $password): array {
|
||||
$_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']]);
|
||||
|
||||
@@ -52,43 +44,38 @@ function loginUser(string $email, string $password): array {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Регистрация нового пользователя
|
||||
*/
|
||||
function registerUser(array $data): array {
|
||||
$db = Database::getInstance()->getConnection();
|
||||
|
||||
|
||||
$email = trim($data['email'] ?? '');
|
||||
$password = $data['password'] ?? '';
|
||||
$fullName = trim($data['full_name'] ?? '');
|
||||
$phone = trim($data['phone'] ?? '');
|
||||
$city = trim($data['city'] ?? '');
|
||||
|
||||
// Валидация
|
||||
|
||||
if (empty($email) || empty($password) || empty($fullName)) {
|
||||
return ['success' => false, 'message' => 'Заполните все обязательные поля'];
|
||||
}
|
||||
|
||||
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
return ['success' => false, 'message' => 'Некорректный email'];
|
||||
}
|
||||
|
||||
|
||||
if (strlen($password) < 6) {
|
||||
return ['success' => false, 'message' => 'Пароль должен содержать минимум 6 символов'];
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
// Проверяем существование пользователя
|
||||
|
||||
$checkStmt = $db->prepare("SELECT user_id FROM users WHERE email = ?");
|
||||
$checkStmt->execute([$email]);
|
||||
|
||||
|
||||
if ($checkStmt->fetch()) {
|
||||
return ['success' => false, 'message' => 'Пользователь с таким email уже существует'];
|
||||
}
|
||||
|
||||
// Создаем пользователя
|
||||
|
||||
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
|
||||
|
||||
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO users (email, password_hash, full_name, phone, city, is_active)
|
||||
VALUES (?, ?, ?, ?, ?, TRUE)
|
||||
@@ -96,8 +83,7 @@ function registerUser(array $data): array {
|
||||
");
|
||||
$stmt->execute([$email, $passwordHash, $fullName, $phone, $city]);
|
||||
$userId = $stmt->fetchColumn();
|
||||
|
||||
// Автоматически авторизуем
|
||||
|
||||
$_SESSION['user_id'] = $userId;
|
||||
$_SESSION['user_email'] = $email;
|
||||
$_SESSION['full_name'] = $fullName;
|
||||
@@ -106,20 +92,17 @@ function registerUser(array $data): array {
|
||||
$_SESSION['isLoggedIn'] = true;
|
||||
$_SESSION['isAdmin'] = false;
|
||||
$_SESSION['login_time'] = time();
|
||||
|
||||
|
||||
return ['success' => true, 'user_id' => $userId];
|
||||
|
||||
|
||||
} catch (PDOException $e) {
|
||||
return ['success' => false, 'message' => 'Ошибка базы данных: ' . $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Выход пользователя
|
||||
*/
|
||||
function logoutUser(): void {
|
||||
$_SESSION = [];
|
||||
|
||||
|
||||
if (ini_get("session.use_cookies")) {
|
||||
$params = session_get_cookie_params();
|
||||
setcookie(session_name(), '', time() - 42000,
|
||||
@@ -127,22 +110,18 @@ function logoutUser(): void {
|
||||
$params["secure"], $params["httponly"]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
session_destroy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка является ли пользователь администратором
|
||||
*/
|
||||
function checkAdminAccess(): bool {
|
||||
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
if (!isset($_SESSION['isAdmin']) || $_SESSION['isAdmin'] !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -47,4 +47,3 @@
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -1,25 +1,13 @@
|
||||
<?php
|
||||
/**
|
||||
* Общие функции для AETERNA
|
||||
*/
|
||||
|
||||
/**
|
||||
* Проверка авторизации пользователя
|
||||
*/
|
||||
function isLoggedIn(): bool {
|
||||
return isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка прав администратора
|
||||
*/
|
||||
function isAdmin(): bool {
|
||||
return isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Требовать авторизацию - редирект на login если не авторизован
|
||||
*/
|
||||
function requireAuth(string $redirectUrl = 'login.php'): void {
|
||||
if (!isLoggedIn()) {
|
||||
header('Location: ' . $redirectUrl . '?error=auth_required&redirect=' . urlencode($_SERVER['REQUEST_URI']));
|
||||
@@ -27,9 +15,6 @@ function requireAuth(string $redirectUrl = 'login.php'): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Требовать права администратора
|
||||
*/
|
||||
function requireAdmin(string $redirectUrl = 'login.php'): void {
|
||||
if (!isAdmin()) {
|
||||
header('Location: ' . $redirectUrl . '?error=admin_required');
|
||||
@@ -37,14 +22,11 @@ function requireAdmin(string $redirectUrl = 'login.php'): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить текущего пользователя
|
||||
*/
|
||||
function getCurrentUser(): ?array {
|
||||
if (!isLoggedIn()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
return [
|
||||
'user_id' => $_SESSION['user_id'] ?? 0,
|
||||
'email' => $_SESSION['user_email'] ?? '',
|
||||
@@ -53,38 +35,23 @@ function getCurrentUser(): ?array {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Форматирование цены
|
||||
*/
|
||||
function formatPrice(float $price): string {
|
||||
return number_format($price, 0, '', ' ') . ' ₽';
|
||||
}
|
||||
|
||||
/**
|
||||
* Безопасный вывод HTML
|
||||
*/
|
||||
function e(string $str): string {
|
||||
return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерация номера заказа
|
||||
*/
|
||||
function generateOrderNumber(): string {
|
||||
return 'AET-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерация SKU для товара
|
||||
*/
|
||||
function generateSKU(string $productName): string {
|
||||
$prefix = strtoupper(substr(preg_replace('/[^a-zA-Z0-9]/', '', transliterate($productName)), 0, 6));
|
||||
return $prefix . '-' . rand(100, 999);
|
||||
}
|
||||
|
||||
/**
|
||||
* Транслитерация кириллицы в латиницу
|
||||
*/
|
||||
function transliterate(string $str): string {
|
||||
$converter = [
|
||||
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd',
|
||||
@@ -105,9 +72,6 @@ function transliterate(string $str): string {
|
||||
return strtr($str, $converter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Создание slug из строки
|
||||
*/
|
||||
function createSlug(string $str): string {
|
||||
$slug = transliterate($str);
|
||||
$slug = strtolower($slug);
|
||||
@@ -116,9 +80,6 @@ function createSlug(string $str): string {
|
||||
return $slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Показать flash-сообщение
|
||||
*/
|
||||
function setFlashMessage(string $type, string $message): void {
|
||||
$_SESSION['flash_message'] = [
|
||||
'type' => $type,
|
||||
@@ -126,9 +87,6 @@ function setFlashMessage(string $type, string $message): void {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить и удалить flash-сообщение
|
||||
*/
|
||||
function getFlashMessage(): ?array {
|
||||
if (isset($_SESSION['flash_message'])) {
|
||||
$message = $_SESSION['flash_message'];
|
||||
@@ -137,4 +95,3 @@ function getFlashMessage(): ?array {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
<?php
|
||||
/**
|
||||
* Единый header для всех страниц AETERNA
|
||||
* Подключение: require_once 'includes/header.php';
|
||||
*/
|
||||
|
||||
// Запускаем сессию если еще не запущена
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
// Определяем текущую страницу
|
||||
$currentPage = basename($_SERVER['PHP_SELF'], '.php');
|
||||
|
||||
// Проверяем авторизацию
|
||||
$isLoggedIn = isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] === true;
|
||||
$isAdmin = isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true;
|
||||
$userEmail = $_SESSION['user_email'] ?? '';
|
||||
@@ -29,7 +22,7 @@ $fullName = $_SESSION['full_name'] ?? $userEmail;
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<style>
|
||||
/* Стили для профиля пользователя */
|
||||
|
||||
.user-profile-dropdown { position: relative; display: inline-block; }
|
||||
.user-profile-toggle { display: flex; align-items: center; gap: 10px; cursor: pointer; padding: 8px 12px; border-radius: 4px; transition: all 0.3s ease; }
|
||||
.user-profile-toggle:hover { background-color: rgba(0, 0, 0, 0.05); }
|
||||
@@ -88,13 +81,12 @@ $fullName = $_SESSION['full_name'] ?? $userEmail;
|
||||
|
||||
<div class="header__icons--top">
|
||||
<?php if ($isLoggedIn): ?>
|
||||
<!-- Иконка корзины -->
|
||||
|
||||
<a href="checkout.php" class="icon cart-icon">
|
||||
<i class="fas fa-shopping-cart"></i>
|
||||
<span class="cart-count" id="cartCount">0</span>
|
||||
</a>
|
||||
|
||||
<!-- Блок профиля -->
|
||||
<div class="user-profile-dropdown">
|
||||
<div class="user-profile-toggle" id="profileToggle">
|
||||
<div class="user-avatar"><?= !empty($userEmail) ? strtoupper(substr($userEmail, 0, 1)) : 'U' ?></div>
|
||||
@@ -151,19 +143,18 @@ $fullName = $_SESSION['full_name'] ?? $userEmail;
|
||||
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
// Профиль пользователя - открытие/закрытие
|
||||
|
||||
$('#profileToggle').click(function(e) {
|
||||
e.stopPropagation();
|
||||
$('#profileMenu').toggle();
|
||||
});
|
||||
|
||||
|
||||
$(document).click(function(e) {
|
||||
if (!$(e.target).closest('.user-profile-dropdown').length) {
|
||||
$('#profileMenu').hide();
|
||||
}
|
||||
});
|
||||
|
||||
// Обновление счетчика корзины
|
||||
<?php if ($isLoggedIn): ?>
|
||||
$.ajax({
|
||||
url: 'api/cart.php?action=count',
|
||||
@@ -180,4 +171,3 @@ $(document).ready(function() {
|
||||
<?php endif; ?>
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
1532
public/index.php
1532
public/index.php
File diff suppressed because it is too large
Load Diff
593
public/login.php
593
public/login.php
@@ -1,299 +1,294 @@
|
||||
<?php
|
||||
session_start();
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>AETERNA - Вход</title>
|
||||
<link rel="stylesheet/less" type="text/css" href="style_for_cite.less">
|
||||
<script src="https://cdn.jsdelivr.net/npm/less"></script>
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<style>
|
||||
/* Добавляем стили для статуса пользователя */
|
||||
.user-status {
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 1000;
|
||||
background: white;
|
||||
padding: 10px 15px;
|
||||
border-radius: 5px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.user-status.admin {
|
||||
border-left: 4px solid #617365;
|
||||
}
|
||||
|
||||
.user-status.user {
|
||||
border-left: 4px solid #28a745;
|
||||
}
|
||||
|
||||
.status-icon {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.admin-icon {
|
||||
color: #617365;
|
||||
}
|
||||
|
||||
.user-icon {
|
||||
color: #28a745;
|
||||
}
|
||||
</style>
|
||||
<script src="check_auth.js"></script>
|
||||
<style>
|
||||
/* Стили для блокировки доступа */
|
||||
.link-disabled {
|
||||
cursor: not-allowed !important;
|
||||
opacity: 0.7 !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
.auth-required {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.auth-required::after {
|
||||
content: "🔒";
|
||||
position: absolute;
|
||||
top: -5px;
|
||||
right: -10px;
|
||||
font-size: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Статус пользователя -->
|
||||
<div class="user-status" id="userStatus" style="display: none;">
|
||||
<i class="fas fa-user status-icon" id="statusIcon"></i>
|
||||
<div>
|
||||
<div id="statusText"></div>
|
||||
<div id="userEmail" style="font-size: 12px; color: #666;"></div>
|
||||
</div>
|
||||
<button onclick="logout()" style="background: none; border: none; color: #666; cursor: pointer;">
|
||||
<i class="fas fa-sign-out-alt"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<header class="header">
|
||||
<div class="header__top">
|
||||
<div class="container header__top-content">
|
||||
<div class="logo">AETERNA</div>
|
||||
|
||||
<div class="search-catalog">
|
||||
<div class="catalog-dropdown">
|
||||
Все категории <span>▼</span>
|
||||
<div class="catalog-dropdown__menu">
|
||||
<ul>
|
||||
<li>Диваны</li>
|
||||
<li>Кровати</li>
|
||||
<li>Шкафы</li>
|
||||
<li>Стулья</li>
|
||||
<li>Столы</li>
|
||||
<li>Комоды</li>
|
||||
<li>Тумбы</li>
|
||||
<li>Полки</li>
|
||||
<li>Стенки</li>
|
||||
<li>Аксессуары</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="search-box">
|
||||
<input type="text" placeholder="Поиск товаров">
|
||||
<span class="search-icon"><i class="fas fa-search"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="header__icons header__icons--top">
|
||||
<a href="checkout.php" class="icon"><i class="fas fa-shopping-cart"></i></a>
|
||||
<a href="register.php" class="icon"><i class="far fa-user"></i></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="header__bottom">
|
||||
<div class="container header__bottom-content">
|
||||
<div class="catalog-menu">
|
||||
<a href="/catalog.php" class="catalog-link">
|
||||
<div class="catalog-icon">
|
||||
<span class="line"></span>
|
||||
<span class="line"></span>
|
||||
<span class="line"></span>
|
||||
</div>
|
||||
<span class="catalog-lines">☰</span>
|
||||
Каталог
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<nav class="nav">
|
||||
<ul class="nav-list">
|
||||
<li><a href="cite_mebel.php">Главная</a></li>
|
||||
<li><a href="services.php">Услуги</a></li>
|
||||
<li><a href="delivery.php">Доставка и оплата</a></li>
|
||||
<li><a href="warranty.php">Гарантия</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<div class="header-phone">+7(912)999-12-23</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="profile-page-main">
|
||||
<div class="profile-container">
|
||||
<div class="profile-left-col">
|
||||
<div class="logo">AETERNA</div>
|
||||
</div>
|
||||
|
||||
<div class="profile-right-col">
|
||||
<div class="profile-form-block">
|
||||
<h2>ВХОД В АККАУНТ</h2>
|
||||
<form class="profile-form" action="#" method="POST" id="loginForm">
|
||||
<div class="input-group">
|
||||
<label for="login-email">E-mail</label>
|
||||
<input type="email" id="login-email" name="email" placeholder="Ваш электронный адрес" required>
|
||||
<div class="error-message" id="email-error">
|
||||
Введите корректный email адрес
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="input-group">
|
||||
<label for="login-password">Пароль</label>
|
||||
<input type="password" id="login-password" name="password" placeholder="Введите пароль" required>
|
||||
<div class="error-message" id="password-error">Неверный пароль</div>
|
||||
</div>
|
||||
|
||||
<div class="form-options">
|
||||
<label class="remember-me">
|
||||
<input type="checkbox" id="remember" name="remember">
|
||||
Запомнить меня
|
||||
</label>
|
||||
<a href="#" class="forgot-password">Забыли пароль?</a>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn primary-btn save-btn">Войти</button>
|
||||
|
||||
<div class="auth-actions">
|
||||
<span class="auth-text">Нет аккаунта?</span>
|
||||
<a href="register.php" class="login-btn">Зарегистрироваться</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Блок для системных сообщений -->
|
||||
<div class="page-messages">
|
||||
<div class="message error" id="errorMessage"></div>
|
||||
<div class="message success" id="successMessage"></div>
|
||||
<div class="message warning" id="warningMessage"></div>
|
||||
</div>
|
||||
|
||||
<footer class="footer" id="footer">
|
||||
<div class="container footer__content">
|
||||
<div class="footer__col footer__col--logo">
|
||||
<div class="logo">AETERNA</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОКУПАТЕЛЮ</h5>
|
||||
<ul>
|
||||
<li><a href="/catalog.php">Каталог</a></li>
|
||||
<li><a href="услуги.html">Услуги</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОМОЩЬ</h5>
|
||||
<ul>
|
||||
<li><a href="Доставка.html">Доставка и оплата</a></li>
|
||||
<li><a href="Гарантия.html">Гарантия и возврат</a></li>
|
||||
<li><a href="cite_mebel.html#faq">Ответы на вопросы</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>КОНТАКТЫ</h5>
|
||||
<p>aeterna@mail.ru</p>
|
||||
<p>+7(912)999-12-23</p>
|
||||
<div class="social-icons">
|
||||
<span class="icon"><i class="fab fa-telegram"></i></span>
|
||||
<span class="icon"><i class="fab fa-instagram"></i></span>
|
||||
<span class="icon"><i class="fab fa-vk"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПРИНИМАЕМ К ОПЛАТЕ</h5>
|
||||
<div class="payment-icons">
|
||||
<span class="pay-icon"><i class="fab fa-cc-visa"></i></span>
|
||||
<span class="pay-icon"><i class="fab fa-cc-mastercard"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="copyright">
|
||||
<p>© 2025 AETERNA. Все права защищены.</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
// Проверяем редирект после входа
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const redirectUrl = urlParams.get('redirect');
|
||||
|
||||
// Если есть редирект - сохраняем его
|
||||
if (redirectUrl) {
|
||||
sessionStorage.setItem('redirectAfterLogin', redirectUrl);
|
||||
}
|
||||
|
||||
// Обработка формы входа
|
||||
$('#loginForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const email = $('#login-email').val();
|
||||
const password = $('#login-password').val();
|
||||
|
||||
// Валидация на клиенте
|
||||
if (!email || !password) {
|
||||
alert('Заполните все поля');
|
||||
return;
|
||||
}
|
||||
|
||||
// Отправляем данные на сервер для PHP сессии
|
||||
$.ajax({
|
||||
url: 'api/auth.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
email: email,
|
||||
password: password
|
||||
},
|
||||
dataType: 'json',
|
||||
success: function(result) {
|
||||
if (result.success) {
|
||||
// Редирект на сохраненный URL или каталог
|
||||
const savedRedirect = sessionStorage.getItem('redirectAfterLogin') || 'catalog.php';
|
||||
sessionStorage.removeItem('redirectAfterLogin');
|
||||
window.location.href = savedRedirect;
|
||||
} else {
|
||||
alert(result.message || 'Ошибка авторизации');
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
alert('Ошибка сервера. Попробуйте позже.');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
<?php
|
||||
session_start();
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>AETERNA - Вход</title>
|
||||
<link rel="stylesheet/less" type="text/css" href="style_for_cite.less">
|
||||
<script src="https://cdn.jsdelivr.net/npm/less"></script>
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<style>
|
||||
|
||||
.user-status {
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 1000;
|
||||
background: white;
|
||||
padding: 10px 15px;
|
||||
border-radius: 5px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.user-status.admin {
|
||||
border-left: 4px solid #617365;
|
||||
}
|
||||
|
||||
.user-status.user {
|
||||
border-left: 4px solid #28a745;
|
||||
}
|
||||
|
||||
.status-icon {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.admin-icon {
|
||||
color: #617365;
|
||||
}
|
||||
|
||||
.user-icon {
|
||||
color: #28a745;
|
||||
}
|
||||
</style>
|
||||
<script src="check_auth.js"></script>
|
||||
<style>
|
||||
|
||||
.link-disabled {
|
||||
cursor: not-allowed !important;
|
||||
opacity: 0.7 !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
.auth-required {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.auth-required::after {
|
||||
content: "🔒";
|
||||
position: absolute;
|
||||
top: -5px;
|
||||
right: -10px;
|
||||
font-size: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="user-status" id="userStatus" style="display: none;">
|
||||
<i class="fas fa-user status-icon" id="statusIcon"></i>
|
||||
<div>
|
||||
<div id="statusText"></div>
|
||||
<div id="userEmail" style="font-size: 12px; color: #666;"></div>
|
||||
</div>
|
||||
<button onclick="logout()" style="background: none; border: none; color: #666; cursor: pointer;">
|
||||
<i class="fas fa-sign-out-alt"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<header class="header">
|
||||
<div class="header__top">
|
||||
<div class="container header__top-content">
|
||||
<div class="logo">AETERNA</div>
|
||||
|
||||
<div class="search-catalog">
|
||||
<div class="catalog-dropdown">
|
||||
Все категории <span>▼</span>
|
||||
<div class="catalog-dropdown__menu">
|
||||
<ul>
|
||||
<li>Диваны</li>
|
||||
<li>Кровати</li>
|
||||
<li>Шкафы</li>
|
||||
<li>Стулья</li>
|
||||
<li>Столы</li>
|
||||
<li>Комоды</li>
|
||||
<li>Тумбы</li>
|
||||
<li>Полки</li>
|
||||
<li>Стенки</li>
|
||||
<li>Аксессуары</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="search-box">
|
||||
<input type="text" placeholder="Поиск товаров">
|
||||
<span class="search-icon"><i class="fas fa-search"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="header__icons header__icons--top">
|
||||
<a href="checkout.php" class="icon"><i class="fas fa-shopping-cart"></i></a>
|
||||
<a href="register.php" class="icon"><i class="far fa-user"></i></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="header__bottom">
|
||||
<div class="container header__bottom-content">
|
||||
<div class="catalog-menu">
|
||||
<a href="/catalog.php" class="catalog-link">
|
||||
<div class="catalog-icon">
|
||||
<span class="line"></span>
|
||||
<span class="line"></span>
|
||||
<span class="line"></span>
|
||||
</div>
|
||||
<span class="catalog-lines">☰</span>
|
||||
Каталог
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<nav class="nav">
|
||||
<ul class="nav-list">
|
||||
<li><a href="cite_mebel.php">Главная</a></li>
|
||||
<li><a href="services.php">Услуги</a></li>
|
||||
<li><a href="delivery.php">Доставка и оплата</a></li>
|
||||
<li><a href="warranty.php">Гарантия</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<div class="header-phone">+7(912)999-12-23</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="profile-page-main">
|
||||
<div class="profile-container">
|
||||
<div class="profile-left-col">
|
||||
<div class="logo">AETERNA</div>
|
||||
</div>
|
||||
|
||||
<div class="profile-right-col">
|
||||
<div class="profile-form-block">
|
||||
<h2>ВХОД В АККАУНТ</h2>
|
||||
<form class="profile-form" action="#" method="POST" id="loginForm">
|
||||
<div class="input-group">
|
||||
<label for="login-email">E-mail</label>
|
||||
<input type="email" id="login-email" name="email" placeholder="Ваш электронный адрес" required>
|
||||
<div class="error-message" id="email-error">
|
||||
Введите корректный email адрес
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="input-group">
|
||||
<label for="login-password">Пароль</label>
|
||||
<input type="password" id="login-password" name="password" placeholder="Введите пароль" required>
|
||||
<div class="error-message" id="password-error">Неверный пароль</div>
|
||||
</div>
|
||||
|
||||
<div class="form-options">
|
||||
<label class="remember-me">
|
||||
<input type="checkbox" id="remember" name="remember">
|
||||
Запомнить меня
|
||||
</label>
|
||||
<a href="#" class="forgot-password">Забыли пароль?</a>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn primary-btn save-btn">Войти</button>
|
||||
|
||||
<div class="auth-actions">
|
||||
<span class="auth-text">Нет аккаунта?</span>
|
||||
<a href="register.php" class="login-btn">Зарегистрироваться</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<div class="page-messages">
|
||||
<div class="message error" id="errorMessage"></div>
|
||||
<div class="message success" id="successMessage"></div>
|
||||
<div class="message warning" id="warningMessage"></div>
|
||||
</div>
|
||||
|
||||
<footer class="footer" id="footer">
|
||||
<div class="container footer__content">
|
||||
<div class="footer__col footer__col--logo">
|
||||
<div class="logo">AETERNA</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОКУПАТЕЛЮ</h5>
|
||||
<ul>
|
||||
<li><a href="/catalog.php">Каталог</a></li>
|
||||
<li><a href="услуги.html">Услуги</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОМОЩЬ</h5>
|
||||
<ul>
|
||||
<li><a href="Доставка.html">Доставка и оплата</a></li>
|
||||
<li><a href="Гарантия.html">Гарантия и возврат</a></li>
|
||||
<li><a href="cite_mebel.html#faq">Ответы на вопросы</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>КОНТАКТЫ</h5>
|
||||
<p>aeterna@mail.ru</p>
|
||||
<p>+7(912)999-12-23</p>
|
||||
<div class="social-icons">
|
||||
<span class="icon"><i class="fab fa-telegram"></i></span>
|
||||
<span class="icon"><i class="fab fa-instagram"></i></span>
|
||||
<span class="icon"><i class="fab fa-vk"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПРИНИМАЕМ К ОПЛАТЕ</h5>
|
||||
<div class="payment-icons">
|
||||
<span class="pay-icon"><i class="fab fa-cc-visa"></i></span>
|
||||
<span class="pay-icon"><i class="fab fa-cc-mastercard"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="copyright">
|
||||
<p>© 2025 AETERNA. Все права защищены.</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const redirectUrl = urlParams.get('redirect');
|
||||
|
||||
if (redirectUrl) {
|
||||
sessionStorage.setItem('redirectAfterLogin', redirectUrl);
|
||||
}
|
||||
|
||||
$('#loginForm').on('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const email = $('#login-email').val();
|
||||
const password = $('#login-password').val();
|
||||
|
||||
if (!email || !password) {
|
||||
alert('Заполните все поля');
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: 'api/auth.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
email: email,
|
||||
password: password
|
||||
},
|
||||
dataType: 'json',
|
||||
success: function(result) {
|
||||
if (result.success) {
|
||||
|
||||
const savedRedirect = sessionStorage.getItem('redirectAfterLogin') || 'catalog.php';
|
||||
sessionStorage.removeItem('redirectAfterLogin');
|
||||
window.location.href = savedRedirect;
|
||||
} else {
|
||||
alert(result.message || 'Ошибка авторизации');
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
alert('Ошибка сервера. Попробуйте позже.');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
<?php
|
||||
session_start();
|
||||
|
||||
// Очищаем все данные сессии
|
||||
$_SESSION = [];
|
||||
|
||||
// Удаляем cookie сессии
|
||||
if (ini_get("session.use_cookies")) {
|
||||
$params = session_get_cookie_params();
|
||||
setcookie(session_name(), '', time() - 42000,
|
||||
@@ -13,10 +11,7 @@ if (ini_get("session.use_cookies")) {
|
||||
);
|
||||
}
|
||||
|
||||
// Уничтожаем сессию
|
||||
session_destroy();
|
||||
|
||||
// Очищаем localStorage через JS
|
||||
header('Location: index.php');
|
||||
exit();
|
||||
|
||||
|
||||
@@ -1,492 +1,484 @@
|
||||
<?php
|
||||
// product_page.php
|
||||
session_start();
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
// Проверка авторизации
|
||||
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
|
||||
header('Location: login.php?error=auth_required&redirect=' . urlencode($_SERVER['REQUEST_URI']));
|
||||
exit();
|
||||
}
|
||||
|
||||
if (!isset($_GET['id'])) {
|
||||
header('Location: catalog.php');
|
||||
exit();
|
||||
}
|
||||
|
||||
$product_id = intval($_GET['id']);
|
||||
|
||||
$db = Database::getInstance()->getConnection();
|
||||
|
||||
try {
|
||||
// Получаем информацию о товаре
|
||||
$productStmt = $db->prepare("
|
||||
SELECT
|
||||
p.*,
|
||||
c.name as category_name,
|
||||
c.slug as category_slug
|
||||
FROM products p
|
||||
LEFT JOIN categories c ON p.category_id = c.category_id
|
||||
WHERE p.product_id = ? AND p.is_available = TRUE
|
||||
");
|
||||
$productStmt->execute([$product_id]);
|
||||
$product = $productStmt->fetch();
|
||||
|
||||
if (!$product) {
|
||||
header('Location: catalog.php?error=product_not_found');
|
||||
exit();
|
||||
}
|
||||
|
||||
// Получаем похожие товары
|
||||
$similarStmt = $db->prepare("
|
||||
SELECT * FROM products
|
||||
WHERE category_id = ?
|
||||
AND product_id != ?
|
||||
AND is_available = TRUE
|
||||
ORDER BY RANDOM()
|
||||
LIMIT 3
|
||||
");
|
||||
$similarStmt->execute([$product['category_id'], $product_id]);
|
||||
$similarProducts = $similarStmt->fetchAll();
|
||||
|
||||
// Получаем отзывы (если есть отдельная таблица reviews)
|
||||
$reviewsStmt = $db->prepare("
|
||||
SELECT rating, comment, created_at
|
||||
FROM reviews
|
||||
WHERE product_id = ?
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 5
|
||||
");
|
||||
$reviewsStmt->execute([$product_id]);
|
||||
$reviews = $reviewsStmt->fetchAll();
|
||||
|
||||
} catch (PDOException $e) {
|
||||
die("Ошибка базы данных: " . $e->getMessage());
|
||||
}
|
||||
|
||||
// HTML код страницы товара
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>AETERNA - <?= htmlspecialchars($product['name']) ?></title>
|
||||
<link rel="stylesheet/less" type="text/css" href="style_for_cite.less">
|
||||
<script src="https://cdn.jsdelivr.net/npm/less"></script>
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<style>
|
||||
.product-attributes {
|
||||
background: #f8f9fa;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
.attribute-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 10px 0;
|
||||
border-bottom: 1px solid #ddd;
|
||||
}
|
||||
.attribute-label {
|
||||
font-weight: bold;
|
||||
color: #453227;
|
||||
}
|
||||
.attribute-value {
|
||||
color: #617365;
|
||||
}
|
||||
.stock-status {
|
||||
font-weight: bold;
|
||||
padding: 5px 10px;
|
||||
border-radius: 4px;
|
||||
display: inline-block;
|
||||
}
|
||||
.in-stock {
|
||||
background: #d4edda;
|
||||
color: #155724;
|
||||
}
|
||||
.low-stock {
|
||||
background: #fff3cd;
|
||||
color: #856404;
|
||||
}
|
||||
.out-of-stock {
|
||||
background: #f8d7da;
|
||||
color: #721c24;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="header">
|
||||
<div class="header__top">
|
||||
<div class="container header__top-content">
|
||||
<div class="logo">AETERNA</div>
|
||||
|
||||
<div class="search-catalog">
|
||||
<div class="catalog-dropdown">
|
||||
Все категории <span>▼</span>
|
||||
<div class="catalog-dropdown__menu">
|
||||
<ul>
|
||||
<li><a href="#">Диваны</a></li>
|
||||
<li><a href="#">Кровати</a></li>
|
||||
<li><a href="#">Шкафы</a></li>
|
||||
<li><a href="#">Стулья</a></li>
|
||||
<li><a href="#">Столы</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="search-box">
|
||||
<input type="text" placeholder="Поиск товаров">
|
||||
<span class="search-icon"><i class="fas fa-search"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="header__icons--top">
|
||||
|
||||
<a href="checkout.php" class="icon"><i class="fas fa-shopping-cart"></i></a>
|
||||
<a href="register.php" class="icon"><i class="far fa-user"></i></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="header__bottom">
|
||||
<div class="container header__bottom-content">
|
||||
<div class="catalog-menu">
|
||||
<a href="/catalog.php" class="catalog-link active-catalog">
|
||||
<div class="catalog-icon">
|
||||
<span class="line"></span>
|
||||
<span class="line"></span>
|
||||
<span class="line"></span>
|
||||
</div>
|
||||
<span class="catalog-lines">☰</span>
|
||||
Каталог
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<nav class="nav">
|
||||
<ul class="nav-list">
|
||||
<li><a href="cite_mebel.php">Главная</a></li>
|
||||
<li><a href="services.php">Услуги</a></li>
|
||||
<li><a href="delivery.php">Доставка и оплата</a></li>
|
||||
<li><a href="warranty.php">Гарантия</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<div class="header-phone">+7(912)999-12-23</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="container">
|
||||
<div class="breadcrumbs">
|
||||
<a href="cite_mebel.php">Главная</a> •
|
||||
<a href="/catalog.php">Каталог</a> •
|
||||
<?php if ($product['category_name']): ?>
|
||||
<a href="/catalog.php?category=<?= $product['category_id'] ?>">
|
||||
<?= htmlspecialchars($product['category_name']) ?>
|
||||
</a> •
|
||||
<?php endif; ?>
|
||||
<span><?= htmlspecialchars($product['name']) ?></span>
|
||||
</div>
|
||||
|
||||
<div class="product__section">
|
||||
<div class="product__gallery">
|
||||
<div class="product__main-image">
|
||||
<img src="<?= htmlspecialchars($product['image_url'] ?? 'img1/default.jpg') ?>"
|
||||
alt="<?= htmlspecialchars($product['name']) ?>"
|
||||
id="mainImage">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="product__info">
|
||||
<h1><?= htmlspecialchars($product['name']) ?></h1>
|
||||
|
||||
<div class="product__rating">
|
||||
<div class="stars">
|
||||
<?php
|
||||
$rating = $product['rating'] ?? 0;
|
||||
$fullStars = floor($rating);
|
||||
$hasHalfStar = $rating - $fullStars >= 0.5;
|
||||
|
||||
for ($i = 1; $i <= 5; $i++) {
|
||||
if ($i <= $fullStars) {
|
||||
echo '<span class="star filled">★</span>';
|
||||
} elseif ($i == $fullStars + 1 && $hasHalfStar) {
|
||||
echo '<span class="star half">★</span>';
|
||||
} else {
|
||||
echo '<span class="star">☆</span>';
|
||||
}
|
||||
}
|
||||
?>
|
||||
</div>
|
||||
<span class="rating-value"><?= number_format($rating, 1) ?></span>
|
||||
<span class="reviews-count">(<?= $product['review_count'] ?> отзывов)</span>
|
||||
</div>
|
||||
|
||||
<div class="product__price">
|
||||
<span class="current-price">
|
||||
<?= number_format($product['price'], 0, '', ' ') ?> ₽
|
||||
</span>
|
||||
<?php if ($product['old_price'] && $product['old_price'] > $product['price']): ?>
|
||||
<span class="old-price">
|
||||
<?= number_format($product['old_price'], 0, '', ' ') ?> ₽
|
||||
</span>
|
||||
<span class="discount-badge">
|
||||
-<?= round(($product['old_price'] - $product['price']) / $product['old_price'] * 100) ?>%
|
||||
</span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div class="stock-status <?php
|
||||
if ($product['stock_quantity'] > 10) echo 'in-stock';
|
||||
elseif ($product['stock_quantity'] > 0) echo 'low-stock';
|
||||
else echo 'out-of-stock';
|
||||
?>">
|
||||
<?php
|
||||
if ($product['stock_quantity'] > 10) {
|
||||
echo '<i class="fas fa-check-circle"></i> В наличии';
|
||||
} elseif ($product['stock_quantity'] > 0) {
|
||||
echo '<i class="fas fa-exclamation-circle"></i> Осталось мало: ' . $product['stock_quantity'] . ' шт.';
|
||||
} else {
|
||||
echo '<i class="fas fa-times-circle"></i> Нет в наличии';
|
||||
}
|
||||
?>
|
||||
</div>
|
||||
|
||||
<div class="product-attributes">
|
||||
<div class="attribute-row">
|
||||
<span class="attribute-label">Артикул:</span>
|
||||
<span class="attribute-value"><?= $product['sku'] ?? 'N/A' ?></span>
|
||||
</div>
|
||||
<div class="attribute-row">
|
||||
<span class="attribute-label">Категория:</span>
|
||||
<span class="attribute-value"><?= htmlspecialchars($product['category_name'] ?? 'Без категории') ?></span>
|
||||
</div>
|
||||
<div class="attribute-row">
|
||||
<span class="attribute-label">На складе:</span>
|
||||
<span class="attribute-value"><?= $product['stock_quantity'] ?> шт.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="product__description">
|
||||
<?= nl2br(htmlspecialchars($product['description'] ?? 'Описание отсутствует')) ?>
|
||||
</p>
|
||||
|
||||
<?php if ($product['stock_quantity'] > 0): ?>
|
||||
<div class="product__purchase">
|
||||
<div class="product__quantity">
|
||||
<button class="product__qty-btn minus">-</button>
|
||||
<input type="number" class="product__qty-value" value="1" min="1" max="<?= $product['stock_quantity'] ?>">
|
||||
<button class="product__qty-btn plus">+</button>
|
||||
</div>
|
||||
|
||||
<div class="product__actions">
|
||||
<button class="btn primary-btn" onclick="addToCart(<?= $product['product_id'] ?>)">
|
||||
<i class="fas fa-shopping-cart"></i> В корзину
|
||||
</button>
|
||||
<button class="btn secondary-btn" onclick="buyNow(<?= $product['product_id'] ?>)">
|
||||
<i class="fas fa-bolt"></i> Купить сейчас
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="product__actions">
|
||||
<button class="btn secondary-btn" onclick="notifyWhenAvailable(<?= $product['product_id'] ?>)">
|
||||
<i class="fas fa-bell"></i> Уведомить о поступлении
|
||||
</button>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if (isset($_SESSION['isAdmin']) && $_SESSION['isAdmin']): ?>
|
||||
<div class="admin-actions" style="margin-top: 20px;">
|
||||
<a href="admin_panel.php?action=edit&id=<?= $product['product_id'] ?>"
|
||||
class="btn btn-warning">
|
||||
<i class="fas fa-edit"></i> Редактировать
|
||||
</a>
|
||||
<button onclick="deleteProduct(<?= $product['product_id'] ?>)"
|
||||
class="btn btn-danger">
|
||||
<i class="fas fa-trash"></i> Удалить
|
||||
</button>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if (!empty($similarProducts)): ?>
|
||||
<section class="similar-products">
|
||||
<h2>Похожие товары</h2>
|
||||
<div class="products-grid">
|
||||
<?php foreach ($similarProducts as $similar): ?>
|
||||
<div class="product-card">
|
||||
<div class="product-image">
|
||||
<img src="<?= htmlspecialchars($similar['image_url'] ?? 'img2/default.jpg') ?>"
|
||||
alt="<?= htmlspecialchars($similar['name']) ?>">
|
||||
</div>
|
||||
<div class="product-info">
|
||||
<h3><?= htmlspecialchars($similar['name']) ?></h3>
|
||||
<p class="product-price">
|
||||
<?= number_format($similar['price'], 0, '', ' ') ?> ₽
|
||||
</p>
|
||||
<a href="product_page.php?id=<?= $similar['product_id'] ?>"
|
||||
class="btn btn-primary">
|
||||
Подробнее
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</section>
|
||||
<?php endif; ?>
|
||||
</main>
|
||||
|
||||
<footer class="footer" id="footer">
|
||||
<div class="container footer__content">
|
||||
<div class="footer__col footer--logo">
|
||||
<div class="logo">AETERNA</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОКУПАТЕЛЮ</h5>
|
||||
<ul>
|
||||
<li><a href="/catalog.php">Каталог</a></li>
|
||||
<li><a href="services.php">Услуги</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОМОЩЬ</h5>
|
||||
<ul>
|
||||
<li><a href="delivery.php">Доставка и оплата</a></li>
|
||||
<li><a href="warranty.php">Гарантия и возврат</a></li>
|
||||
<li><a href="cite_mebel.php#faq">Ответы на вопросы</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>КОНТАКТЫ</h5>
|
||||
<p>aeterna@mail.ru</p>
|
||||
<p>+7(912)999-12-23</p>
|
||||
<div class="social-icons">
|
||||
<span class="icon"><i class="fab fa-telegram"></i></span>
|
||||
<span class="icon"><i class="fab fa-instagram"></i></span>
|
||||
<span class="icon"><i class="fab fa-vk"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПРИНИМАЕМ К ОПЛАТЕ</h5>
|
||||
<div class="payment-icons">
|
||||
<span class="pay-icon"><i class="fab fa-cc-visa"></i></span>
|
||||
<span class="pay-icon"><i class="fab fa-cc-mastercard"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="copyright">
|
||||
<p>© 2025 AETERNA. Все права защищены.</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
// Управление количеством
|
||||
$('.product__qty-btn.plus').click(function() {
|
||||
const $input = $('.product__qty-value');
|
||||
let value = parseInt($input.val());
|
||||
let max = parseInt($input.attr('max'));
|
||||
if (value < max) {
|
||||
$input.val(value + 1);
|
||||
}
|
||||
});
|
||||
|
||||
$('.product__qty-btn.minus').click(function() {
|
||||
const $input = $('.product__qty-value');
|
||||
let value = parseInt($input.val());
|
||||
if (value > 1) {
|
||||
$input.val(value - 1);
|
||||
}
|
||||
});
|
||||
|
||||
// Добавление в корзину
|
||||
window.addToCart = function(productId) {
|
||||
const quantity = $('.product__qty-value').val();
|
||||
|
||||
$.ajax({
|
||||
url: 'add_to_cart.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
product_id: productId,
|
||||
quantity: quantity
|
||||
},
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.success) {
|
||||
alert('Товар добавлен в корзину!');
|
||||
// Обновляем счетчик в шапке
|
||||
$('.cart-count').text(result.cart_count);
|
||||
} else {
|
||||
alert('Ошибка: ' + result.message);
|
||||
}
|
||||
} catch(e) {
|
||||
alert('Товар добавлен в корзину!');
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Покупка сейчас
|
||||
window.buyNow = function(productId) {
|
||||
const quantity = $('.product__qty-value').val();
|
||||
|
||||
$.ajax({
|
||||
url: 'add_to_cart.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
product_id: productId,
|
||||
quantity: quantity
|
||||
},
|
||||
success: function() {
|
||||
window.location.href = 'checkout.php';
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Уведомление о поступлении
|
||||
window.notifyWhenAvailable = function(productId) {
|
||||
const email = prompt('Введите ваш email для уведомления:');
|
||||
if (email) {
|
||||
$.ajax({
|
||||
url: 'notify_available.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
product_id: productId,
|
||||
email: email
|
||||
},
|
||||
success: function(response) {
|
||||
alert('Вы будете уведомлены о поступлении товара!');
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Удаление товара (админ)
|
||||
window.deleteProduct = function(productId) {
|
||||
if (confirm('Вы уверены, что хотите удалить этот товар?')) {
|
||||
$.ajax({
|
||||
url: 'catalog_admin_action.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
action: 'delete',
|
||||
product_id: productId
|
||||
},
|
||||
success: function() {
|
||||
window.location.href = 'catalog.php';
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
|
||||
header('Location: login.php?error=auth_required&redirect=' . urlencode($_SERVER['REQUEST_URI']));
|
||||
exit();
|
||||
}
|
||||
|
||||
if (!isset($_GET['id'])) {
|
||||
header('Location: catalog.php');
|
||||
exit();
|
||||
}
|
||||
|
||||
$product_id = intval($_GET['id']);
|
||||
|
||||
$db = Database::getInstance()->getConnection();
|
||||
|
||||
try {
|
||||
|
||||
$productStmt = $db->prepare("
|
||||
SELECT
|
||||
p.*,
|
||||
c.name as category_name,
|
||||
c.slug as category_slug
|
||||
FROM products p
|
||||
LEFT JOIN categories c ON p.category_id = c.category_id
|
||||
WHERE p.product_id = ? AND p.is_available = TRUE
|
||||
");
|
||||
$productStmt->execute([$product_id]);
|
||||
$product = $productStmt->fetch();
|
||||
|
||||
if (!$product) {
|
||||
header('Location: catalog.php?error=product_not_found');
|
||||
exit();
|
||||
}
|
||||
|
||||
$similarStmt = $db->prepare("
|
||||
SELECT * FROM products
|
||||
WHERE category_id = ?
|
||||
AND product_id != ?
|
||||
AND is_available = TRUE
|
||||
ORDER BY RANDOM()
|
||||
LIMIT 3
|
||||
");
|
||||
$similarStmt->execute([$product['category_id'], $product_id]);
|
||||
$similarProducts = $similarStmt->fetchAll();
|
||||
|
||||
$reviewsStmt = $db->prepare("
|
||||
SELECT rating, comment, created_at
|
||||
FROM reviews
|
||||
WHERE product_id = ?
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 5
|
||||
");
|
||||
$reviewsStmt->execute([$product_id]);
|
||||
$reviews = $reviewsStmt->fetchAll();
|
||||
|
||||
} catch (PDOException $e) {
|
||||
die("Ошибка базы данных: " . $e->getMessage());
|
||||
}
|
||||
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>AETERNA - <?= htmlspecialchars($product['name']) ?></title>
|
||||
<link rel="stylesheet/less" type="text/css" href="style_for_cite.less">
|
||||
<script src="https://cdn.jsdelivr.net/npm/less"></script>
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<style>
|
||||
.product-attributes {
|
||||
background: #f8f9fa;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
.attribute-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 10px 0;
|
||||
border-bottom: 1px solid #ddd;
|
||||
}
|
||||
.attribute-label {
|
||||
font-weight: bold;
|
||||
color: #453227;
|
||||
}
|
||||
.attribute-value {
|
||||
color: #617365;
|
||||
}
|
||||
.stock-status {
|
||||
font-weight: bold;
|
||||
padding: 5px 10px;
|
||||
border-radius: 4px;
|
||||
display: inline-block;
|
||||
}
|
||||
.in-stock {
|
||||
background: #d4edda;
|
||||
color: #155724;
|
||||
}
|
||||
.low-stock {
|
||||
background: #fff3cd;
|
||||
color: #856404;
|
||||
}
|
||||
.out-of-stock {
|
||||
background: #f8d7da;
|
||||
color: #721c24;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="header">
|
||||
<div class="header__top">
|
||||
<div class="container header__top-content">
|
||||
<div class="logo">AETERNA</div>
|
||||
|
||||
<div class="search-catalog">
|
||||
<div class="catalog-dropdown">
|
||||
Все категории <span>▼</span>
|
||||
<div class="catalog-dropdown__menu">
|
||||
<ul>
|
||||
<li><a href="#">Диваны</a></li>
|
||||
<li><a href="#">Кровати</a></li>
|
||||
<li><a href="#">Шкафы</a></li>
|
||||
<li><a href="#">Стулья</a></li>
|
||||
<li><a href="#">Столы</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="search-box">
|
||||
<input type="text" placeholder="Поиск товаров">
|
||||
<span class="search-icon"><i class="fas fa-search"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="header__icons--top">
|
||||
|
||||
<a href="checkout.php" class="icon"><i class="fas fa-shopping-cart"></i></a>
|
||||
<a href="register.php" class="icon"><i class="far fa-user"></i></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="header__bottom">
|
||||
<div class="container header__bottom-content">
|
||||
<div class="catalog-menu">
|
||||
<a href="/catalog.php" class="catalog-link active-catalog">
|
||||
<div class="catalog-icon">
|
||||
<span class="line"></span>
|
||||
<span class="line"></span>
|
||||
<span class="line"></span>
|
||||
</div>
|
||||
<span class="catalog-lines">☰</span>
|
||||
Каталог
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<nav class="nav">
|
||||
<ul class="nav-list">
|
||||
<li><a href="cite_mebel.php">Главная</a></li>
|
||||
<li><a href="services.php">Услуги</a></li>
|
||||
<li><a href="delivery.php">Доставка и оплата</a></li>
|
||||
<li><a href="warranty.php">Гарантия</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<div class="header-phone">+7(912)999-12-23</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="container">
|
||||
<div class="breadcrumbs">
|
||||
<a href="cite_mebel.php">Главная</a> •
|
||||
<a href="/catalog.php">Каталог</a> •
|
||||
<?php if ($product['category_name']): ?>
|
||||
<a href="/catalog.php?category=<?= $product['category_id'] ?>">
|
||||
<?= htmlspecialchars($product['category_name']) ?>
|
||||
</a> •
|
||||
<?php endif; ?>
|
||||
<span><?= htmlspecialchars($product['name']) ?></span>
|
||||
</div>
|
||||
|
||||
<div class="product__section">
|
||||
<div class="product__gallery">
|
||||
<div class="product__main-image">
|
||||
<img src="<?= htmlspecialchars($product['image_url'] ?? 'img1/default.jpg') ?>"
|
||||
alt="<?= htmlspecialchars($product['name']) ?>"
|
||||
id="mainImage">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="product__info">
|
||||
<h1><?= htmlspecialchars($product['name']) ?></h1>
|
||||
|
||||
<div class="product__rating">
|
||||
<div class="stars">
|
||||
<?php
|
||||
$rating = $product['rating'] ?? 0;
|
||||
$fullStars = floor($rating);
|
||||
$hasHalfStar = $rating - $fullStars >= 0.5;
|
||||
|
||||
for ($i = 1; $i <= 5; $i++) {
|
||||
if ($i <= $fullStars) {
|
||||
echo '<span class="star filled">★</span>';
|
||||
} elseif ($i == $fullStars + 1 && $hasHalfStar) {
|
||||
echo '<span class="star half">★</span>';
|
||||
} else {
|
||||
echo '<span class="star">☆</span>';
|
||||
}
|
||||
}
|
||||
?>
|
||||
</div>
|
||||
<span class="rating-value"><?= number_format($rating, 1) ?></span>
|
||||
<span class="reviews-count">(<?= $product['review_count'] ?> отзывов)</span>
|
||||
</div>
|
||||
|
||||
<div class="product__price">
|
||||
<span class="current-price">
|
||||
<?= number_format($product['price'], 0, '', ' ') ?> ₽
|
||||
</span>
|
||||
<?php if ($product['old_price'] && $product['old_price'] > $product['price']): ?>
|
||||
<span class="old-price">
|
||||
<?= number_format($product['old_price'], 0, '', ' ') ?> ₽
|
||||
</span>
|
||||
<span class="discount-badge">
|
||||
-<?= round(($product['old_price'] - $product['price']) / $product['old_price'] * 100) ?>%
|
||||
</span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div class="stock-status <?php
|
||||
if ($product['stock_quantity'] > 10) echo 'in-stock';
|
||||
elseif ($product['stock_quantity'] > 0) echo 'low-stock';
|
||||
else echo 'out-of-stock';
|
||||
?>">
|
||||
<?php
|
||||
if ($product['stock_quantity'] > 10) {
|
||||
echo '<i class="fas fa-check-circle"></i> В наличии';
|
||||
} elseif ($product['stock_quantity'] > 0) {
|
||||
echo '<i class="fas fa-exclamation-circle"></i> Осталось мало: ' . $product['stock_quantity'] . ' шт.';
|
||||
} else {
|
||||
echo '<i class="fas fa-times-circle"></i> Нет в наличии';
|
||||
}
|
||||
?>
|
||||
</div>
|
||||
|
||||
<div class="product-attributes">
|
||||
<div class="attribute-row">
|
||||
<span class="attribute-label">Артикул:</span>
|
||||
<span class="attribute-value"><?= $product['sku'] ?? 'N/A' ?></span>
|
||||
</div>
|
||||
<div class="attribute-row">
|
||||
<span class="attribute-label">Категория:</span>
|
||||
<span class="attribute-value"><?= htmlspecialchars($product['category_name'] ?? 'Без категории') ?></span>
|
||||
</div>
|
||||
<div class="attribute-row">
|
||||
<span class="attribute-label">На складе:</span>
|
||||
<span class="attribute-value"><?= $product['stock_quantity'] ?> шт.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="product__description">
|
||||
<?= nl2br(htmlspecialchars($product['description'] ?? 'Описание отсутствует')) ?>
|
||||
</p>
|
||||
|
||||
<?php if ($product['stock_quantity'] > 0): ?>
|
||||
<div class="product__purchase">
|
||||
<div class="product__quantity">
|
||||
<button class="product__qty-btn minus">-</button>
|
||||
<input type="number" class="product__qty-value" value="1" min="1" max="<?= $product['stock_quantity'] ?>">
|
||||
<button class="product__qty-btn plus">+</button>
|
||||
</div>
|
||||
|
||||
<div class="product__actions">
|
||||
<button class="btn primary-btn" onclick="addToCart(<?= $product['product_id'] ?>)">
|
||||
<i class="fas fa-shopping-cart"></i> В корзину
|
||||
</button>
|
||||
<button class="btn secondary-btn" onclick="buyNow(<?= $product['product_id'] ?>)">
|
||||
<i class="fas fa-bolt"></i> Купить сейчас
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="product__actions">
|
||||
<button class="btn secondary-btn" onclick="notifyWhenAvailable(<?= $product['product_id'] ?>)">
|
||||
<i class="fas fa-bell"></i> Уведомить о поступлении
|
||||
</button>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if (isset($_SESSION['isAdmin']) && $_SESSION['isAdmin']): ?>
|
||||
<div class="admin-actions" style="margin-top: 20px;">
|
||||
<a href="admin_panel.php?action=edit&id=<?= $product['product_id'] ?>"
|
||||
class="btn btn-warning">
|
||||
<i class="fas fa-edit"></i> Редактировать
|
||||
</a>
|
||||
<button onclick="deleteProduct(<?= $product['product_id'] ?>)"
|
||||
class="btn btn-danger">
|
||||
<i class="fas fa-trash"></i> Удалить
|
||||
</button>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if (!empty($similarProducts)): ?>
|
||||
<section class="similar-products">
|
||||
<h2>Похожие товары</h2>
|
||||
<div class="products-grid">
|
||||
<?php foreach ($similarProducts as $similar): ?>
|
||||
<div class="product-card">
|
||||
<div class="product-image">
|
||||
<img src="<?= htmlspecialchars($similar['image_url'] ?? 'img2/default.jpg') ?>"
|
||||
alt="<?= htmlspecialchars($similar['name']) ?>">
|
||||
</div>
|
||||
<div class="product-info">
|
||||
<h3><?= htmlspecialchars($similar['name']) ?></h3>
|
||||
<p class="product-price">
|
||||
<?= number_format($similar['price'], 0, '', ' ') ?> ₽
|
||||
</p>
|
||||
<a href="product_page.php?id=<?= $similar['product_id'] ?>"
|
||||
class="btn btn-primary">
|
||||
Подробнее
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</section>
|
||||
<?php endif; ?>
|
||||
</main>
|
||||
|
||||
<footer class="footer" id="footer">
|
||||
<div class="container footer__content">
|
||||
<div class="footer__col footer--logo">
|
||||
<div class="logo">AETERNA</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОКУПАТЕЛЮ</h5>
|
||||
<ul>
|
||||
<li><a href="/catalog.php">Каталог</a></li>
|
||||
<li><a href="services.php">Услуги</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОМОЩЬ</h5>
|
||||
<ul>
|
||||
<li><a href="delivery.php">Доставка и оплата</a></li>
|
||||
<li><a href="warranty.php">Гарантия и возврат</a></li>
|
||||
<li><a href="cite_mebel.php#faq">Ответы на вопросы</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>КОНТАКТЫ</h5>
|
||||
<p>aeterna@mail.ru</p>
|
||||
<p>+7(912)999-12-23</p>
|
||||
<div class="social-icons">
|
||||
<span class="icon"><i class="fab fa-telegram"></i></span>
|
||||
<span class="icon"><i class="fab fa-instagram"></i></span>
|
||||
<span class="icon"><i class="fab fa-vk"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПРИНИМАЕМ К ОПЛАТЕ</h5>
|
||||
<div class="payment-icons">
|
||||
<span class="pay-icon"><i class="fab fa-cc-visa"></i></span>
|
||||
<span class="pay-icon"><i class="fab fa-cc-mastercard"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="copyright">
|
||||
<p>© 2025 AETERNA. Все права защищены.</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
|
||||
$('.product__qty-btn.plus').click(function() {
|
||||
const $input = $('.product__qty-value');
|
||||
let value = parseInt($input.val());
|
||||
let max = parseInt($input.attr('max'));
|
||||
if (value < max) {
|
||||
$input.val(value + 1);
|
||||
}
|
||||
});
|
||||
|
||||
$('.product__qty-btn.minus').click(function() {
|
||||
const $input = $('.product__qty-value');
|
||||
let value = parseInt($input.val());
|
||||
if (value > 1) {
|
||||
$input.val(value - 1);
|
||||
}
|
||||
});
|
||||
|
||||
window.addToCart = function(productId) {
|
||||
const quantity = $('.product__qty-value').val();
|
||||
|
||||
$.ajax({
|
||||
url: 'add_to_cart.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
product_id: productId,
|
||||
quantity: quantity
|
||||
},
|
||||
success: function(response) {
|
||||
try {
|
||||
const result = JSON.parse(response);
|
||||
if (result.success) {
|
||||
alert('Товар добавлен в корзину!');
|
||||
|
||||
$('.cart-count').text(result.cart_count);
|
||||
} else {
|
||||
alert('Ошибка: ' + result.message);
|
||||
}
|
||||
} catch(e) {
|
||||
alert('Товар добавлен в корзину!');
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
window.buyNow = function(productId) {
|
||||
const quantity = $('.product__qty-value').val();
|
||||
|
||||
$.ajax({
|
||||
url: 'add_to_cart.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
product_id: productId,
|
||||
quantity: quantity
|
||||
},
|
||||
success: function() {
|
||||
window.location.href = 'checkout.php';
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
window.notifyWhenAvailable = function(productId) {
|
||||
const email = prompt('Введите ваш email для уведомления:');
|
||||
if (email) {
|
||||
$.ajax({
|
||||
url: 'notify_available.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
product_id: productId,
|
||||
email: email
|
||||
},
|
||||
success: function(response) {
|
||||
alert('Вы будете уведомлены о поступлении товара!');
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
window.deleteProduct = function(productId) {
|
||||
if (confirm('Вы уверены, что хотите удалить этот товар?')) {
|
||||
$.ajax({
|
||||
url: 'catalog_admin_action.php',
|
||||
method: 'POST',
|
||||
data: {
|
||||
action: 'delete',
|
||||
product_id: productId
|
||||
},
|
||||
success: function() {
|
||||
window.location.href = 'catalog.php';
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
1517
public/register.php
1517
public/register.php
File diff suppressed because it is too large
Load Diff
@@ -1,113 +1,112 @@
|
||||
<?php
|
||||
// В начале файла
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>AETERNA - Услуги</title>
|
||||
<link rel="stylesheet/less" type="text/css" href="style_for_cite.less">
|
||||
<script src="https://cdn.jsdelivr.net/npm/less"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<script src="check_auth.js"></script>
|
||||
<style>
|
||||
/* Стили для блокировки доступа */
|
||||
.link-disabled {
|
||||
cursor: not-allowed !important;
|
||||
opacity: 0.7 !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
.auth-required {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.auth-required::after {
|
||||
content: "🔒";
|
||||
position: absolute;
|
||||
top: -5px;
|
||||
right: -10px;
|
||||
font-size: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<?php include 'header_common.php'; ?>
|
||||
|
||||
|
||||
<main>
|
||||
<section class="services-section">
|
||||
<div class="container services__wrapper">
|
||||
<div class="services__top-row">
|
||||
<div class="service-card service-card--green">
|
||||
<h3 class="service-card__title">ДОСТАВКА</h3>
|
||||
<p class="service-card__text">Стоимость доставки зависит от таких факторов, как: вес, адрес, удаленность от города, дата</p>
|
||||
</div>
|
||||
<div class="service-card service-card--green">
|
||||
<h3 class="service-card__title">СБОРКА</h3>
|
||||
<p class="service-card__text">Стоимость сборки рассчитывается индивидуально, так как на цену влияет несколько факторов</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="service-card service-card--beige">
|
||||
<h3 class="service-card__title">ДИЗАЙН‑ПРОЕКТ</h3>
|
||||
<p class="service-card__text">Предоставляем услугу по составлению дизайн‑проекта. Учитываем индивидуальные пожелания каждого клиента. Работаем с интерьерами различной сложности.</p>
|
||||
<div class="image-placeholder"></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<footer class="footer" id="footer">
|
||||
<div class="container footer__content">
|
||||
<div class="footer__col footer--logo">
|
||||
<div class="logo">AETERNA</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОКУПАТЕЛЮ</h5>
|
||||
<ul>
|
||||
<li><a href="/catalog.php">Каталог</a></li>
|
||||
<li><a href="услуги.html">Услуги</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОМОЩЬ</h5>
|
||||
<ul>
|
||||
<li><a href="Доставка.html">Доставка и оплата</a></li>
|
||||
<li><a href="Гарантия.html">Гарантия и возврат</a></li>
|
||||
<li><a href="cite_mebel.html#faq">Ответы на вопросы</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>КОНТАКТЫ</h5>
|
||||
<p>aeterna@mail.ru</p>
|
||||
<p>+7(912)999-12-23</p>
|
||||
<div class="social-icons">
|
||||
<span class="icon"><i class="fab fa-telegram"></i></span>
|
||||
<span class="icon"><i class="fab fa-instagram"></i></span>
|
||||
<span class="icon"><i class="fab fa-vk"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПРИНИМАЕМ К ОПЛАТЕ</h5>
|
||||
<div class="payment-icons">
|
||||
<span class="pay-icon"><i class="fab fa-cc-visa"></i></span>
|
||||
<span class="pay-icon"><i class="fab fa-cc-mastercard"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="copyright">
|
||||
<p>© 2025 AETERNA. Все права защищены.</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
</body>
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>AETERNA - Услуги</title>
|
||||
<link rel="stylesheet/less" type="text/css" href="style_for_cite.less">
|
||||
<script src="https://cdn.jsdelivr.net/npm/less"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<script src="check_auth.js"></script>
|
||||
<style>
|
||||
|
||||
.link-disabled {
|
||||
cursor: not-allowed !important;
|
||||
opacity: 0.7 !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
.auth-required {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.auth-required::after {
|
||||
content: "🔒";
|
||||
position: absolute;
|
||||
top: -5px;
|
||||
right: -10px;
|
||||
font-size: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<?php include 'header_common.php'; ?>
|
||||
|
||||
<main>
|
||||
<section class="services-section">
|
||||
<div class="container services__wrapper">
|
||||
<div class="services__top-row">
|
||||
<div class="service-card service-card--green">
|
||||
<h3 class="service-card__title">ДОСТАВКА</h3>
|
||||
<p class="service-card__text">Стоимость доставки зависит от таких факторов, как: вес, адрес, удаленность от города, дата</p>
|
||||
</div>
|
||||
<div class="service-card service-card--green">
|
||||
<h3 class="service-card__title">СБОРКА</h3>
|
||||
<p class="service-card__text">Стоимость сборки рассчитывается индивидуально, так как на цену влияет несколько факторов</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="service-card service-card--beige">
|
||||
<h3 class="service-card__title">ДИЗАЙН‑ПРОЕКТ</h3>
|
||||
<p class="service-card__text">Предоставляем услугу по составлению дизайн‑проекта. Учитываем индивидуальные пожелания каждого клиента. Работаем с интерьерами различной сложности.</p>
|
||||
<div class="image-placeholder"></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<footer class="footer" id="footer">
|
||||
<div class="container footer__content">
|
||||
<div class="footer__col footer--logo">
|
||||
<div class="logo">AETERNA</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОКУПАТЕЛЮ</h5>
|
||||
<ul>
|
||||
<li><a href="/catalog.php">Каталог</a></li>
|
||||
<li><a href="услуги.html">Услуги</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОМОЩЬ</h5>
|
||||
<ul>
|
||||
<li><a href="Доставка.html">Доставка и оплата</a></li>
|
||||
<li><a href="Гарантия.html">Гарантия и возврат</a></li>
|
||||
<li><a href="cite_mebel.html#faq">Ответы на вопросы</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>КОНТАКТЫ</h5>
|
||||
<p>aeterna@mail.ru</p>
|
||||
<p>+7(912)999-12-23</p>
|
||||
<div class="social-icons">
|
||||
<span class="icon"><i class="fab fa-telegram"></i></span>
|
||||
<span class="icon"><i class="fab fa-instagram"></i></span>
|
||||
<span class="icon"><i class="fab fa-vk"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПРИНИМАЕМ К ОПЛАТЕ</h5>
|
||||
<div class="payment-icons">
|
||||
<span class="pay-icon"><i class="fab fa-cc-visa"></i></span>
|
||||
<span class="pay-icon"><i class="fab fa-cc-mastercard"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="copyright">
|
||||
<p>© 2025 AETERNA. Все права защищены.</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,206 +1,205 @@
|
||||
<?php
|
||||
// В начале файла
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>AETERNA - Гарантия</title>
|
||||
<link rel="stylesheet/less" type="text/css" href="style_for_cite.less">
|
||||
<script src="https://cdn.jsdelivr.net/npm/less"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<script src="check_auth.js"></script>
|
||||
<style>
|
||||
/* Стили для блокировки доступа */
|
||||
.link-disabled {
|
||||
cursor: not-allowed !important;
|
||||
opacity: 0.7 !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
.auth-required {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.auth-required::after {
|
||||
content: "🔒";
|
||||
position: absolute;
|
||||
top: -5px;
|
||||
right: -10px;
|
||||
font-size: 10px;
|
||||
}
|
||||
</style>
|
||||
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<?php include 'header_common.php'; ?>
|
||||
|
||||
|
||||
<main class="catalog-main">
|
||||
<div class="container">
|
||||
<div class="breadcrumbs">
|
||||
<a href="cite_mebel.php">Главная</a> • <span class="current-page">Гарантия</span>
|
||||
</div>
|
||||
|
||||
<div class="warranty-content">
|
||||
<h1>ГАРАНТИЙНЫЕ ОБЯЗАТЕЛЬСТВА</h1>
|
||||
|
||||
<div class="warranty-overview">
|
||||
<div class="warranty-card">
|
||||
<div class="warranty-icon">
|
||||
<i class="fas fa-couch"></i>
|
||||
</div>
|
||||
<h3>Мягкая мебель</h3>
|
||||
<div class="warranty-period">18 месяцев</div>
|
||||
</div>
|
||||
|
||||
<div class="warranty-card">
|
||||
<div class="warranty-icon">
|
||||
<i class="fas fa-archive"></i>
|
||||
</div>
|
||||
<h3>Корпусная мебель</h3>
|
||||
<div class="warranty-period">24 месяца</div>
|
||||
</div>
|
||||
|
||||
<div class="warranty-card">
|
||||
<div class="warranty-icon">
|
||||
<i class="fas fa-lightbulb"></i>
|
||||
</div>
|
||||
<h3>Элементы освещения</h3>
|
||||
<div class="warranty-period">12 месяцев</div>
|
||||
</div>
|
||||
|
||||
<div class="warranty-card">
|
||||
<div class="warranty-icon">
|
||||
<i class="fas fa-cogs"></i>
|
||||
</div>
|
||||
<h3>Фурнитура и механизмы</h3>
|
||||
<div class="warranty-period">36 месяцев</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="coverage-section">
|
||||
<div class="coverage-covered">
|
||||
<h2>Что покрывается гарантией</h2>
|
||||
<div class="coverage-list">
|
||||
<div class="coverage-item covered">
|
||||
<i class="fas fa-check-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Производственные дефекты</h4>
|
||||
<p>Трещины, сколы, брак материалов</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="coverage-item covered">
|
||||
<i class="fas fa-check-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Неисправности механизмов</h4>
|
||||
<p>Трансформации, выдвижные системы</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="coverage-item covered">
|
||||
<i class="fas fa-check-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Проблемы с фурнитурой</h4>
|
||||
<p>Ручки, петли, направляющие</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="coverage-item covered">
|
||||
<i class="fas fa-check-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Дефекты покрытия</h4>
|
||||
<p>Отслоение шпона, краски, ламинации</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="coverage-not-covered">
|
||||
<h2>Что не покрывается гарантией</h2>
|
||||
<div class="coverage-list">
|
||||
<div class="coverage-item not-covered">
|
||||
<i class="fas fa-times-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Механические повреждения</h4>
|
||||
<p>Царапины, вмятины от неправильной эксплуатации</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="coverage-item not-covered">
|
||||
<i class="fas fa-times-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Следы износа</h4>
|
||||
<p>Естественное старение материалов</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="coverage-item not-covered">
|
||||
<i class="fas fa-times-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Неправильная сборка</h4>
|
||||
<p>Последствия самостоятельного ремонта</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="coverage-item not-covered">
|
||||
<i class="fas fa-times-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Внешние воздействия</h4>
|
||||
<p>Повреждения от жидкостей, солнечных лучей</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="footer" id="footer">
|
||||
<div class="container footer__content">
|
||||
<div class="footer__col footer--logo">
|
||||
<div class="logo">AETERNA</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОКУПАТЕЛЮ</h5>
|
||||
<ul>
|
||||
<li><a href="/catalog.php">Каталог</a></li>
|
||||
<li><a href="services.php">Услуги</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОМОЩЬ</h5>
|
||||
<ul>
|
||||
<li><a href="delivery.php">Доставка и оплата</a></li>
|
||||
<li><a href="warranty.php">Гарантия и возврат</a></li>
|
||||
<li><a href="cite_mebel.php#faq">Ответы на вопросы</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>КОНТАКТЫ</h5>
|
||||
<p>aeterna@mail.ru</p>
|
||||
<p>+7(912)999-12-23</p>
|
||||
<div class="social-icons">
|
||||
<span class="icon"><i class="fab fa-telegram"></i></span>
|
||||
<span class="icon"><i class="fab fa-instagram"></i></span>
|
||||
<span class="icon"><i class="fab fa-vk"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПРИНИМАЕМ К ОПЛАТЕ</h5>
|
||||
<div class="payment-icons">
|
||||
<span class="pay-icon"><i class="fab fa-cc-visa"></i></span>
|
||||
<span class="pay-icon"><i class="fab fa-cc-mastercard"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="copyright">
|
||||
<p>© 2025 AETERNA. Все права защищены.</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
</body>
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>AETERNA - Гарантия</title>
|
||||
<link rel="stylesheet/less" type="text/css" href="style_for_cite.less">
|
||||
<script src="https://cdn.jsdelivr.net/npm/less"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
|
||||
<script src="check_auth.js"></script>
|
||||
<style>
|
||||
|
||||
.link-disabled {
|
||||
cursor: not-allowed !important;
|
||||
opacity: 0.7 !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
.auth-required {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.auth-required::after {
|
||||
content: "🔒";
|
||||
position: absolute;
|
||||
top: -5px;
|
||||
right: -10px;
|
||||
font-size: 10px;
|
||||
}
|
||||
</style>
|
||||
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<?php include 'header_common.php'; ?>
|
||||
|
||||
<main class="catalog-main">
|
||||
<div class="container">
|
||||
<div class="breadcrumbs">
|
||||
<a href="cite_mebel.php">Главная</a> • <span class="current-page">Гарантия</span>
|
||||
</div>
|
||||
|
||||
<div class="warranty-content">
|
||||
<h1>ГАРАНТИЙНЫЕ ОБЯЗАТЕЛЬСТВА</h1>
|
||||
|
||||
<div class="warranty-overview">
|
||||
<div class="warranty-card">
|
||||
<div class="warranty-icon">
|
||||
<i class="fas fa-couch"></i>
|
||||
</div>
|
||||
<h3>Мягкая мебель</h3>
|
||||
<div class="warranty-period">18 месяцев</div>
|
||||
</div>
|
||||
|
||||
<div class="warranty-card">
|
||||
<div class="warranty-icon">
|
||||
<i class="fas fa-archive"></i>
|
||||
</div>
|
||||
<h3>Корпусная мебель</h3>
|
||||
<div class="warranty-period">24 месяца</div>
|
||||
</div>
|
||||
|
||||
<div class="warranty-card">
|
||||
<div class="warranty-icon">
|
||||
<i class="fas fa-lightbulb"></i>
|
||||
</div>
|
||||
<h3>Элементы освещения</h3>
|
||||
<div class="warranty-period">12 месяцев</div>
|
||||
</div>
|
||||
|
||||
<div class="warranty-card">
|
||||
<div class="warranty-icon">
|
||||
<i class="fas fa-cogs"></i>
|
||||
</div>
|
||||
<h3>Фурнитура и механизмы</h3>
|
||||
<div class="warranty-period">36 месяцев</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="coverage-section">
|
||||
<div class="coverage-covered">
|
||||
<h2>Что покрывается гарантией</h2>
|
||||
<div class="coverage-list">
|
||||
<div class="coverage-item covered">
|
||||
<i class="fas fa-check-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Производственные дефекты</h4>
|
||||
<p>Трещины, сколы, брак материалов</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="coverage-item covered">
|
||||
<i class="fas fa-check-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Неисправности механизмов</h4>
|
||||
<p>Трансформации, выдвижные системы</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="coverage-item covered">
|
||||
<i class="fas fa-check-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Проблемы с фурнитурой</h4>
|
||||
<p>Ручки, петли, направляющие</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="coverage-item covered">
|
||||
<i class="fas fa-check-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Дефекты покрытия</h4>
|
||||
<p>Отслоение шпона, краски, ламинации</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="coverage-not-covered">
|
||||
<h2>Что не покрывается гарантией</h2>
|
||||
<div class="coverage-list">
|
||||
<div class="coverage-item not-covered">
|
||||
<i class="fas fa-times-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Механические повреждения</h4>
|
||||
<p>Царапины, вмятины от неправильной эксплуатации</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="coverage-item not-covered">
|
||||
<i class="fas fa-times-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Следы износа</h4>
|
||||
<p>Естественное старение материалов</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="coverage-item not-covered">
|
||||
<i class="fas fa-times-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Неправильная сборка</h4>
|
||||
<p>Последствия самостоятельного ремонта</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="coverage-item not-covered">
|
||||
<i class="fas fa-times-circle"></i>
|
||||
<div class="coverage-text">
|
||||
<h4>Внешние воздействия</h4>
|
||||
<p>Повреждения от жидкостей, солнечных лучей</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="footer" id="footer">
|
||||
<div class="container footer__content">
|
||||
<div class="footer__col footer--logo">
|
||||
<div class="logo">AETERNA</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОКУПАТЕЛЮ</h5>
|
||||
<ul>
|
||||
<li><a href="/catalog.php">Каталог</a></li>
|
||||
<li><a href="services.php">Услуги</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПОМОЩЬ</h5>
|
||||
<ul>
|
||||
<li><a href="delivery.php">Доставка и оплата</a></li>
|
||||
<li><a href="warranty.php">Гарантия и возврат</a></li>
|
||||
<li><a href="cite_mebel.php#faq">Ответы на вопросы</a></li>
|
||||
<li><a href="#footer">Контакты</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>КОНТАКТЫ</h5>
|
||||
<p>aeterna@mail.ru</p>
|
||||
<p>+7(912)999-12-23</p>
|
||||
<div class="social-icons">
|
||||
<span class="icon"><i class="fab fa-telegram"></i></span>
|
||||
<span class="icon"><i class="fab fa-instagram"></i></span>
|
||||
<span class="icon"><i class="fab fa-vk"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer__col">
|
||||
<h5>ПРИНИМАЕМ К ОПЛАТЕ</h5>
|
||||
<div class="payment-icons">
|
||||
<span class="pay-icon"><i class="fab fa-cc-visa"></i></span>
|
||||
<span class="pay-icon"><i class="fab fa-cc-mastercard"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="copyright">
|
||||
<p>© 2025 AETERNA. Все права защищены.</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,142 +1,137 @@
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
/* Стили для сообщений внизу страницы */
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Дополнительные стили для формы регистрации */
|
||||
.input-group {
|
||||
position: relative;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.profile-form input.error {
|
||||
border-color: #ff0000;
|
||||
background-color: #fff5f5;
|
||||
}
|
||||
|
||||
.privacy-checkbox {
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.privacy-checkbox label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.privacy-checkbox input[type="checkbox"] {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Исправление отступов для страницы регистрации */
|
||||
.profile-page-main {
|
||||
padding: 40px 0;
|
||||
min-height: calc(100vh - 200px);
|
||||
}
|
||||
|
||||
/* Убедимся, что контейнер не перекрывает шапку и футер */
|
||||
.profile-container {
|
||||
margin: 0 auto;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.input-hint {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
/* Стили для страницы входа */
|
||||
.form-options {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.remember-me {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
}
|
||||
|
||||
.remember-me input[type="checkbox"] {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.forgot-password {
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.forgot-password:hover {
|
||||
color: #617365;
|
||||
text-decoration: none;
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.input-group {
|
||||
position: relative;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.profile-form input.error {
|
||||
border-color: #ff0000;
|
||||
background-color: #fff5f5;
|
||||
}
|
||||
|
||||
.privacy-checkbox {
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.privacy-checkbox label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.privacy-checkbox input[type="checkbox"] {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.profile-page-main {
|
||||
padding: 40px 0;
|
||||
min-height: calc(100vh - 200px);
|
||||
}
|
||||
|
||||
.profile-container {
|
||||
margin: 0 auto;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.input-hint {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.form-options {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.remember-me {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
}
|
||||
|
||||
.remember-me input[type="checkbox"] {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.forgot-password {
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.forgot-password:hover {
|
||||
color: #617365;
|
||||
text-decoration: none;
|
||||
}
|
||||
@@ -1,142 +1,137 @@
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
/* Стили для сообщений внизу страницы */
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Дополнительные стили для формы регистрации */
|
||||
.input-group {
|
||||
position: relative;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.profile-form input.error {
|
||||
border-color: #ff0000;
|
||||
background-color: #fff5f5;
|
||||
}
|
||||
|
||||
.privacy-checkbox {
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.privacy-checkbox label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.privacy-checkbox input[type="checkbox"] {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Исправление отступов для страницы регистрации */
|
||||
.profile-page-main {
|
||||
padding: 40px 0;
|
||||
min-height: calc(100vh - 200px);
|
||||
}
|
||||
|
||||
/* Убедимся, что контейнер не перекрывает шапку и футер */
|
||||
.profile-container {
|
||||
margin: 0 auto;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.input-hint {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
/* Стили для страницы входа */
|
||||
.form-options {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.remember-me {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
}
|
||||
|
||||
.remember-me input[type="checkbox"] {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.forgot-password {
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.forgot-password:hover {
|
||||
color: #617365;
|
||||
text-decoration: none;
|
||||
.error-message {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.form__input.error {
|
||||
border-color: #ff0000;
|
||||
}
|
||||
|
||||
.form__group {
|
||||
position: relative;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.page-messages {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1000;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 15px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
border: 1px solid #ffcdd2;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e8f5e9;
|
||||
color: #453227;
|
||||
border: 1px solid #c8e6c9;
|
||||
}
|
||||
|
||||
.message.warning {
|
||||
background-color: #fff3e0;
|
||||
color: #ef6c00;
|
||||
border: 1px solid #ffe0b2;
|
||||
}
|
||||
|
||||
.privacy-error {
|
||||
color: #ff0000;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.input-group {
|
||||
position: relative;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.profile-form input.error {
|
||||
border-color: #ff0000;
|
||||
background-color: #fff5f5;
|
||||
}
|
||||
|
||||
.privacy-checkbox {
|
||||
margin: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.privacy-checkbox label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.privacy-checkbox input[type="checkbox"] {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.profile-page-main {
|
||||
padding: 40px 0;
|
||||
min-height: calc(100vh - 200px);
|
||||
}
|
||||
|
||||
.profile-container {
|
||||
margin: 0 auto;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.input-hint {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.form-options {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.remember-me {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
}
|
||||
|
||||
.remember-me input[type="checkbox"] {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.forgot-password {
|
||||
font-size: 14px;
|
||||
color: #453227;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.forgot-password:hover {
|
||||
color: #617365;
|
||||
text-decoration: none;
|
||||
}
|
||||
Reference in New Issue
Block a user