<?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();
}
?>