<?php
require_once 'config.php';

if(!isLoggedIn()) {
    header("Location: login.php");
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$_SESSION['user_id']]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

$statuses = [
    'new' => '🆕 Новый',
    'confirmed' => '✅ Подтверждён',
    'delivered' => '🚚 Доставлен',
    'cancelled' => '❌ Отменён'
];

// Получаем товары для каждого заказа
foreach($orders as &$order) {
    $stmt = $pdo->prepare("SELECT * FROM order_items WHERE order_id = ?");
    $stmt->execute([$order['id']]);
    $order['items'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Мои заказы - Интернет-магазин</title>
    <meta name="description" content="Список ваших заказов">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Arial, sans-serif; background: #f0fdf4; }
        header, footer { background: #0f172a; color: #f8fafc; padding: 1rem; text-align: center; }
        nav a { color: #f8fafc; margin: 0 15px; text-decoration: none; }
        nav a:hover { color: #14b8a6; }
        main { max-width: 1100px; margin: 30px auto; padding: 20px; background: #fff; border-radius: 20px; min-height: 60vh; }
        .order-card { background: #f8fafc; border-radius: 16px; padding: 20px; margin-bottom: 20px; }
        .order-header { display: flex; justify-content: space-between; flex-wrap: wrap; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid #e2e8f0; }
        .order-number { font-weight: bold; font-size: 1.1rem; color: #0f172a; }
        .order-status { font-weight: bold; }
        .status-new { color: #f39c12; }
        .status-confirmed { color: #27ae60; }
        .status-delivered { color: #3498db; }
        .status-cancelled { color: #e74c3c; }
        .order-items { margin: 15px 0; }
        .order-item { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px dashed #e2e8f0; }
        .order-total { text-align: right; font-weight: bold; margin-top: 10px; }
        .btn { display: inline-block; background: #0f766e; color: #fff; padding: 10px 20px; text-decoration: none; border-radius: 8px; margin-top: 20px; }
        h1 { margin-bottom: 20px; color: #0f172a; }
        .empty { text-align: center; padding: 50px; }
    </style>
</head>
<body>
<header>
    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap;">
        <h1 style="margin: 0;">🛍️ Интернет-магазин</h1>
        <nav>
            <a href="index.php">📦 Каталог</a>
            <a href="cart.php">🛒 Корзина</a>
            <a href="my_orders.php">📋 Мои заказы</a>
            <a href="logout.php">🚪 Выйти (<?= h($_SESSION['username']) ?>)</a>
        </nav>
    </div>
</header>

<main>
    <h1>📋 Мои заказы</h1>
    
    <?php if(count($orders) > 0): ?>
        <?php foreach($orders as $order): ?>
            <div class="order-card">
                <div class="order-header">
                    <span class="order-number">Заказ №<?= h($order['order_number']) ?></span>
                    <span class="order-status status-<?= $order['status'] ?>"><?= $statuses[$order['status']] ?></span>
                    <span><?= date('d.m.Y H:i', strtotime($order['created_at'])) ?></span>
                </div>
                <div class="order-items">
                    <?php foreach($order['items'] as $item): ?>
                        <div class="order-item">
                            <span><?= h($item['product_name']) ?> × <?= $item['quantity'] ?> шт.</span>
                            <span><?= number_format($item['price'] * $item['quantity'], 2) ?> ₽</span>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="order-total">
                    Итого: <?= number_format($order['total_amount'], 2) ?> ₽
                </div>
                <div class="order-address">
                    📍 Адрес доставки: <?= h($order['delivery_address']) ?>
                </div>
                <?php if($order['delivery_date']): ?>
                    <div class="order-delivery">
                        📅 Желаемая дата: <?= date('d.m.Y', strtotime($order['delivery_date'])) ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="empty">
            <p>😕 У вас пока нет заказов.</p>
            <a href="index.php" class="btn">Перейти в каталог</a>
        </div>
    <?php endif; ?>
    
    <a href="index.php" class="btn">← В каталог</a>
</main>

<footer>
    <p>&copy; 2025 Интернет-магазин. Лучшие товары по лучшим ценам.</p>
</footer>
</body>
</html>