View file test.4imas.ru/ajax/apply_discount.php

File size: 2.18Kb
<?php
// ajax/apply_discount.php
require '../config/bootstrap.php';
require '../config/auth.php';

// Доступ только для авторизованных пользователей
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success'=>false, 'error'=>'Необходимо войти в систему']);
    exit;
}

// Получаем JSON данные
$data = json_decode(file_get_contents('php://input'), true);

// Проверка CSRF
if (empty($data['csrf']) || $data['csrf'] !== ($_SESSION['csrf'] ?? '')) {
    http_response_code(403);
    echo json_encode(['success'=>false, 'error'=>'Неверный CSRF токен']);
    exit;
}

// Проверка корзины
$cart = $_SESSION['cart'] ?? [];
if (empty($cart)) {
    echo json_encode(['success'=>false, 'error'=>'Корзина пуста']);
    exit;
}

// Получаем код скидки
$discount_code = trim($data['discount'] ?? '');
if (!$discount_code) {
    echo json_encode(['success'=>false, 'error'=>'Введите код скидки']);
    exit;
}

// Проверяем скидочную карту
$stmt = $pdo->prepare("SELECT percent, active FROM discounts WHERE code = ? LIMIT 1");
$stmt->execute([$discount_code]);
$discount = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$discount || !$discount['active']) {
    echo json_encode(['success'=>false, 'error'=>'Неверный или неактивный код скидки']);
    exit;
}

// Рассчитываем итоговую сумму с учётом скидки
$total = 0;
foreach ($cart as $item) {
    $stmt = $pdo->prepare("SELECT price FROM formats WHERE name = ? LIMIT 1");
    $stmt->execute([$item['format']]);
    $format = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$format) continue;
    $price = $format['price'] * $item['quantity'];
    $total += $price;
}

$discounted_total = $total * (1 - $discount['percent'] / 100);

echo json_encode([
    'success' => true,
    'discount_percent' => $discount['percent'],
    'original_total' => $total,
    'discounted_total' => round($discounted_total, 2),
    'discount_code' => $discount_code
]);