<?php
require_once "../../includes/db_connect.php";
require_once "../../includes/islogin.php";

if (!isset($_SESSION['user_id'])) {
    $grouped_ongoing_orders = [];
    $grouped_past_orders = [];
    exit;
} else {
    $current_user_id = $_SESSION['user_id'];
    $temp_orders_data = [];

    $sql = "SELECT
                o.order_id,
                o.order_time,
                o.status AS order_status,
                o.total_price AS order_total_price,
                o.user_id,
                r.restaurant_id,
                r.name AS restaurant_name,
                oi.order_item_id,
                oi.quantity,
                oi.price AS item_price,
                f.food_id,
                f.name AS food_name,
                f.image_url AS food_image_url,
                (SELECT COUNT(*) FROM Reviews rv_order 
                 WHERE rv_order.order_id = o.order_id 
                 AND rv_order.user_id = o.user_id 
                 AND rv_order.order_item_id IS NULL 
                 AND rv_order.food_id IS NULL) > 0 
                 AS order_overall_review_exists
            FROM Orders o
            JOIN OrderItems oi ON o.order_id = oi.order_id
            JOIN Foods f ON oi.food_id = f.food_id
            JOIN Restaurants r ON f.restaurant_id = r.restaurant_id
            WHERE o.user_id = ?
            ORDER BY o.order_time DESC, o.order_id DESC, oi.order_item_id ASC";

    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $current_user_id);
        $stmt->execute();
        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {
            $temp_orders_data[] = $row;
        }
        $stmt->close();
    }

    $grouped_all_orders = [];
    foreach ($temp_orders_data as $item_data) {
        $order_id = $item_data['order_id'];
        if (!isset($grouped_all_orders[$order_id])) {
            $grouped_all_orders[$order_id] = [
                'order_id' => $item_data['order_id'],
                'restaurant_name' => $item_data['restaurant_name'],
                'restaurant_id' => $item_data['restaurant_id'],
                'order_time' => $item_data['order_time'],
                'order_status' => $item_data['order_status'],
                'order_total_price' => $item_data['order_total_price'],
                'order_overall_review_exists' => $item_data['order_overall_review_exists'],
                'items' => []
            ];
        }
        $grouped_all_orders[$order_id]['items'][] = $item_data;
    }

    $grouped_ongoing_orders = array_filter($grouped_all_orders, fn($order) => $order['order_status'] === 'ordered');
    $grouped_past_orders = array_filter($grouped_all_orders, fn($order) => $order['order_status'] === 'completed');
}
?>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>주문 내역</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        html, body {
            height: 100%;
            margin: 0;
            font-family: sans-serif;
            background-color: #f4f4f4;
        }
        .container {
            height: 100%;
            max-width: 400px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            background-color: white;
            border: 1px solid #e0e0e0;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .header {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0 15px;
            height: 70px;
            box-sizing: border-box;
            border-bottom: 1px solid #ddd;
        }
        .header h1 {
            flex-grow: 1;
            font-size: 1.2em;
            margin: 0;
            text-align: center;
        }
        .cart-link {
            text-decoration: none;
            color: inherit;
            display: flex;
            align-items: center;
        }
        .cart-icon {
            font-size: 1.5em;
            color: #555;
            cursor: pointer;
        }
        .content {
            flex: 1;
            overflow-y: auto;
            padding: 15px;
        }
        .order-section {
            margin-bottom: 10px;
        }
        .order-section h2 {
            font-size: 1em;
            margin: 0 0 10px 0;
            padding-left: 5px;
            color: #555;
        }
        .order-group-box {
            border: 1px solid #ddd;
            border-radius: 8px;
            background-color: #fff;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }
        .order-group-header {
            padding: 10px 15px;
            background-color: #f8f9fa;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.9em;
        }
        .order-group-header h3 {
            margin: 0;
            font-size: 1.1em;
            color: #333;
        }
        .order-group-header .order-meta span {
            margin-left: 10px;
        }
        .order-items-list {
            padding: 0 15px;
        }
        .order-item {
            display: flex;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        .order-item:last-child {
            border-bottom: none;
        }
        .order-item img {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            margin-right: 10px;
            object-fit: cover;
            background-color: #eee;
        }
        .order-details {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        .order-details .item-info {
            font-size: 0.9em;
            margin: 0 0 4px 0;
            color: #333;
        }
        .order-details .item-sub-info {
            font-size: 0.8em;
            color: #777;
        }
        .item-actions {
            margin: 10px 15px 15px;
            display: flex;
            gap: 8px;
        }
        .item-actions button {
            flex: 1;
            padding: 8px 10px;
            border: 1px solid #007bff;
            border-radius: 5px;
            background-color: #e9f3ff;
            color: #007bff;
            font-size: 0.85em;
            cursor: pointer;
            transition: background-color 0.2s, color 0.2s;
        }
        .item-actions button:hover {
            background-color: #007bff;
            color: white;
        }
        .item-actions button.disabled {
            background-color: #e9ecef;
            color: #6c757d;
            border-color: #ced4da;
            cursor: not-allowed;
        }
        .bottom-nav {
            display: flex;
            justify-content: space-around;
            align-items: center;
            padding: 10px 0;
            border-top: 1px solid #eee;
            background-color: white;
            flex-shrink: 0;
        }
        .bottom-nav a {
            color: #555;
            font-size: 1.5em;
            text-decoration: none;
            padding: 5px 10px;
        }
        .bottom-nav a.active,
        .bottom-nav a:hover {
            color: #007bff;
        }
    </style>
</head>
<body>
    <div class="container">
        <header class="header">
            <h1>주문 내역</h1>
            <a href="cart.php" class="cart-link"><i class="fas fa-shopping-cart cart-icon"></i></a>
        </header>

        <div class="content">
            <?php if (!isset($_SESSION['user_id'])): ?>
                <p style="text-align:center; padding: 20px; color: #777;">로그인이 필요합니다.</p>
            <?php else: ?>
                <?php if (!empty($grouped_ongoing_orders)): ?>
                    <div class="order-section">
                        <h2>진행중인 주문</h2>
                        <?php foreach ($grouped_ongoing_orders as $order): ?>
                            <div class="order-group-box">
                                <div class="order-group-header">
                                    <h3><?= htmlspecialchars($order['restaurant_name']) ?></h3>
                                    <div class="order-meta">
                                        <span><?= date("y.m.d", strtotime($order['order_time'])) ?></span>
                                        <span>총 <?= number_format($order['order_total_price']) ?>원</span>
                                    </div>
                                </div>
                                <div class="order-items-list">
                                    <?php foreach ($order['items'] as $item): ?>
                                        <div class="order-item">
                                            <img src="<?= htmlspecialchars($item['food_image_url']) ?>" alt="음식 이미지">
                                            <div class="order-details">
                                                <p class="item-info"><?= htmlspecialchars($item['food_name']) ?></p>
                                                <p class="item-sub-info">수량: <?= $item['quantity'] ?>개 / 금액: <?= number_format($item['item_price'] * $item['quantity']) ?>원</p>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <?php if (!empty($grouped_past_orders)): ?>
                    <div class="order-section">
                        <h2>지난 주문 내역</h2>
                        <?php foreach ($grouped_past_orders as $order): ?>
                            <div class="order-group-box">
                                <div class="order-group-header">
                                    <h3><?= htmlspecialchars($order['restaurant_name']) ?></h3>
                                    <div class="order-meta">
                                        <span><?= date("y.m.d", strtotime($order['order_time'])) ?></span>
                                        <span>총 <?= number_format($order['order_total_price']) ?>원</span>
                                    </div>
                                </div>
                                <div class="order-items-list">
                                    <?php 
                                    $last_item = end($order['items']);
                                    foreach ($order['items'] as $item): ?>
                                        <div class="order-item">
                                            <img src="<?= htmlspecialchars($item['food_image_url']) ?>" alt="음식 이미지">
                                            <div class="order-details">
                                                <p class="item-info"><?= htmlspecialchars($item['food_name']) ?></p>
                                                <p class="item-sub-info">수량: <?= $item['quantity'] ?>개 / 금액: <?= number_format($item['item_price'] * $item['quantity']) ?>원</p>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <div class="item-actions">
                                    <button onclick="location.href='cart.php?food_id=<?= $last_item['food_id'] ?>&quantity=<?= $last_item['quantity'] ?>'">재주문</button>
                                    <?php if (!$order['order_overall_review_exists']): ?>
                                        <button onclick="location.href='../review/makereview.php?order_id=<?= $order['order_id'] ?>&restaurant_id=<?= $order['restaurant_id'] ?>'">리뷰작성</button>
                                    <?php else: ?>
                                        <button class="disabled" disabled>리뷰완료</button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <?php if (empty($grouped_ongoing_orders) && empty($grouped_past_orders)): ?>
                    <p style="text-align:center; padding: 20px; color: #777;">주문 내역이 없습니다.</p>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <nav class="bottom-nav">
            <a href="../../main.php"><i class="fas fa-home"></i></a>
            <a href="../user/dibs.php"><i class="fas fa-heart"></i></a>
            <a href="orderlist.php" class="active"><i class="fas fa-receipt"></i></a>
            <a href="../../auth/redirect-mypage.php"><i class="fas fa-user"></i></a>
        </nav>
    </div>
    <?php if (isset($conn) && $conn instanceof mysqli) { $conn->close(); } ?>
</body>
</html>
