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

File size: 4.87Kb
<?php

session_start();
require '../config/bootstrap.php';

header('Content-Type: application/json');

if (!is_logged_in()) {
    echo json_encode(['success' => false, 'error' => 'Необходимо войти в систему']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Метод не поддерживается']);
    exit;
}

$csrf = $_POST['csrf'] ?? '';
$discount_code = trim($_POST['discount_code'] ?? '');
$remove_discount = isset($_POST['remove_discount']) && $_POST['remove_discount'] === '1';

error_log('Checkout request - CSRF: ' . ($csrf ? 'present' : 'missing'));
error_log('Checkout request - Discount code: ' . ($discount_code ?: 'empty'));

if (empty($csrf) || !check_csrf($csrf)) {
    echo json_encode(['success' => false, 'error' => 'Ошибка безопасности (CSRF)']);
    exit;
}

try {
    global $pdo;

    $fullname = trim($_POST['fullname'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $comment = trim($_POST['comment'] ?? '');

    if (empty($fullname)) {
        echo json_encode(['success' => false, 'error' => 'Введите ФИО']);
        exit;
    }
    
    if (empty($phone)) {
        echo json_encode(['success' => false, 'error' => 'Введите телефон']);
        exit;
    }
    
    if (empty($address)) {
        echo json_encode(['success' => false, 'error' => 'Введите адрес доставки']);
        exit;
    }

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

    $discount_id = null;
    $discount_percent = 0;
    
    if (!empty($discount_code)) {
        $stmt = $pdo->prepare("SELECT id, code, percent, expires_at FROM discounts WHERE code = ?");
        $stmt->execute([$discount_code]);
        $discount = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($discount) {

            if ($discount['expires_at']) {
                $expires_at = new DateTime($discount['expires_at']);
                $now = new DateTime();
                if ($expires_at >= $now) {
                    $discount_id = $discount['id'];
                    $discount_percent = $discount['percent'];
                }
            } else {
                $discount_id = $discount['id'];
                $discount_percent = $discount['percent'];
            }
        }
    }

    $subtotal = 0;
    foreach ($_SESSION['cart'] as $item) {
        $subtotal += ($item['price'] ?? 0) * ($item['quantity'] ?? 1);
    }
    
    $discount_amount = $subtotal * ($discount_percent / 100);
    $final_total = $subtotal - $discount_amount;
    $pdo->beginTransaction();
    
    try {
        $stmt = $pdo->prepare("
            INSERT INTO orders (user_id, fullname, phone, address, comment, 
                              subtotal, discount_id, discount_percent, discount_amount, total, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Новый')
        ");
        
        $stmt->execute([
            $_SESSION['user_id'],
            $fullname,
            $phone,
            $address,
            $comment,
            $subtotal,
            $discount_id,
            $discount_percent,
            $discount_amount,
            $final_total
        ]);
        
        $order_id = $pdo->lastInsertId();
        $stmt = $pdo->prepare("
            INSERT INTO order_items (order_id, photo_id, format_id, format_name, price, quantity)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        foreach ($_SESSION['cart'] as $item) {
            $stmt->execute([
                $order_id,
                $item['photo_id'] ?? null,
                $item['format_id'] ?? null,
                $item['format_name'] ?? '',
                $item['price'] ?? 0,
                $item['quantity'] ?? 1
            ]);
        }

        $pdo->commit();

        unset($_SESSION['cart']);
        unset($_SESSION['discount']);
        
        echo json_encode([
            'success' => true,
            'order_id' => $order_id,
            'message' => 'Заказ успешно оформлен!',
            'total' => number_format($final_total, 2) . ' ₽'
        ]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
    
} catch (PDOException $e) {
    error_log('Checkout database error: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Ошибка базы данных: ' . $e->getMessage()]);
    exit;
} catch (Exception $e) {
    error_log('Checkout error: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Ошибка при оформлении заказа: ' . $e->getMessage()]);
    exit;
}
?>