<?php
session_start();

require_once "../../includes/db_connect.php";

$is_logged_in = isset($_SESSION['user_id']);

$food_item = null;
$error_message = "";
$food_id_to_display = 0; // 장바구니 담기 등에 사용될 food_id

// 2. URL에서 food_id 가져오기
if (isset($_GET['food_id'])) {
    $food_id_to_display = (int)$_GET['food_id'];

    if ($food_id_to_display > 0) {
        // 3. DB에서 해당 food_id의 음식 정보 조회
        $sql_food = "SELECT food_id, name, description, price, image_url FROM Foods WHERE food_id = ?";
        
        if ($stmt_food = $conn->prepare($sql_food)) {
            $stmt_food->bind_param("i", $food_id_to_display);
            $stmt_food->execute();
            $result_food = $stmt_food->get_result();

            if ($result_food->num_rows === 1) {
                $food_item = $result_food->fetch_assoc();
            } else {
                $error_message = "해당 음식을 찾을 수 없습니다. (ID: " . htmlspecialchars($food_id_to_display) . ")";
            }
            $stmt_food->close();
        } else {
            $error_message = "데이터를 불러오는 중 오류가 발생했습니다. (DB 준비 오류)";
        }
    } else {
        $error_message = "유효하지 않은 음식 ID입니다.";
    }
} else {
    $error_message = "음식 ID가 제공되지 않았습니다.";
}

// 4. 화면에 표시할 값들 설정 (데이터가 없거나 오류 시 기본값 사용)
$page_title = $food_item ? htmlspecialchars($food_item['name']) . " 상세" : "음식 상세";
$display_food_name = $food_item ? htmlspecialchars($food_item['name']) : "음식 정보 없음";
$display_food_image_url = $food_item && !empty($food_item['image_url']) ? htmlspecialchars($food_item['image_url']) : '../assets/images/default_food.png'; // 기본 이미지 경로로 수정
$display_food_description = $food_item && !empty($food_item['description']) ? nl2br(htmlspecialchars($food_item['description'])) : "상세 설명이 없습니다.";
$display_food_price = $food_item ? "₩" . number_format($food_item['price']) : "가격 정보 없음";

$cart_item_count = 0;
if (isset($_SESSION['cart'])) {
    $cart_item_count = count($_SESSION['cart']);
}

?>
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        html, body {
            height: 100%;
            font-family: 'Noto Sans KR', sans-serif;
            margin: 0;
            background-color: #f4f4f4;
            color: #333;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .container {
            width: 400px;
            max-width: 400px;
            height: 100%;
            background-color: #fff;
            display: flex;
            flex-direction: column;
            border-left: 1px solid #eee;
            border-right: 1px solid #eee;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 15px;
            height: 70px;
            box-sizing: border-box;
            border-bottom: 1px solid #ddd;
            width: 100%;
            background-color: #fff;
            flex-shrink: 0;
        }

        .page-header .back-button,
        .page-header .cart-button {
            background: none;
            border: none;
            color: #555;
            cursor: pointer;
            padding: 5px;
            display: flex;
            align-items: center;
            font-size: 1.5em;
        }

        .page-header .page-title {
            flex-grow: 1;
            font-size: 1.2em;
            font-weight: 700;
            margin: 0;
            text-align: center;
            color: #333;
        }

        .page-header .cart-button {
            position: relative;
        }

        .cart-badge {
            position: absolute;
            top: -5px;
            right: -7px;
            background-color: #007bff;
            color: white;
            border-radius: 50%;
            padding: 2px 5px;
            font-size: 0.6rem;
            font-weight: bold;
            display: <?php echo ($cart_item_count > 0) ? 'inline-block' : 'none'; ?>;
        }

        .food-details {
            flex: 1;
            overflow-y: auto;
            padding: 0;
            max-width: 400px;
            width: 100%;
        }

        .food-image-section {
            width: 100%;
            overflow: hidden;
            background-color: #eee;
        }

        .food-image-section img {
            width: 100%;
            height: 360px;
            object-fit: cover;
            display: block;
        }

        .food-info {
            padding: 20px 15px;
            border-bottom: 1px solid #eee;
        }

        .food-info .food-name {
            font-size: 1.8rem;
            font-weight: 700;
            margin-top: 0;
            margin-bottom: 10px;
            color: #2c3e50;
        }
        
        .food-description-section {
            padding: 20px 15px;
            font-size: 1.6em;
            line-height: 1.6;
            color: #555;
            margin-bottom: 0;
        }
        .food-description-section:last-child {
             border-bottom: none;
        }

        .order-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            border-top: 1px solid #ddd;
            background-color: #fff;
            width: 100%;
            box-sizing: border-box;
            flex-shrink: 0;
            position: sticky;
            bottom: 0;
        }

        .price-section {
            display: flex;
            align-items: center;
        }

        .price-label {
            font-size: 0.9em;
            color: #777;
            margin-right: 8px;
        }

        .price-value {
            font-size: 1.4rem;
            font-weight: 700;
            color: #e74c3c;
        }

        .order-button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 12px 25px;
            font-size: 1em;
            font-weight: 700;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        .order-button:hover {
            background-color: #0056b3;
        }
        .error-message-container {
            padding: 20px;
            text-align: center;
            color: #721c24;
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            margin: 20px;
            border-radius: 5px;
        }
    </style>
</head>

<body>
    <div class="container">
        <header class="page-header">
            <button class="back-button" aria-label="뒤로가기" onclick="history.back();">
                <i class="fas fa-arrow-left"></i>
            </button>
            <button class="cart-button" aria-label="장바구니" onclick="location.href='../order/cart.php';"> <i class="fas fa-shopping-cart"></i>
                <span class="cart-badge" id="cartBadge"><?php echo $cart_item_count; ?></span>
            </button>
        </header>

        <?php if (!empty($error_message)): ?>
            <div class="error-message-container">
                <p><?php echo $error_message; ?></p>
                <button onclick="location.href='menulist.php';">메뉴 목록으로 돌아가기</button> </div>
        <?php elseif ($food_item): ?>
            <main class="food-details">
                <section class="food-image-section">
                    <img src="<?php echo $display_food_image_url; ?>" alt="<?php echo $display_food_name; ?> 사진" id="foodImage">
                </section>

                <section class="food-info">
                    <h2 class="food-name" id="foodName"><?php echo $display_food_name; ?></h2>
                    </section>

                <section class="food-description-section">
                        <?php echo $display_food_description; ?>
                </section>
            </main>

            <footer class="order-bar">
                <div class="price-section">
                    <span class="price-label">가격:</span>
                    <span class="price-value" id="foodPrice"><?php echo $display_food_price; ?></span>
                </div>
                <form id="addToCartForm" action="../../auth/add_to_cart.php" method="POST" style="display: inline;"> 
                    <input type="hidden" name="food_id" value="<?php echo $food_item['food_id']; ?>">
                    <input type="hidden" name="quantity" value="1"> <button type="submit" class="order-button" id="orderButton" onclick="handleAddToCart()">
                        장바구니에 담기
                    </button>
                </form>
            </footer>
        <?php endif; ?>
    </div>

     <?php
    // 모든 DB 작업이 끝난 후 연결 종료
    if (isset($conn) && $conn instanceof mysqli) {
        $conn->close();
    }
    ?>
    <script>
    function handleAddToCart() {
        const isLoggedIn = <?php echo json_encode($is_logged_in); ?>;

        if (isLoggedIn) {
            document.getElementById('addToCartForm').submit();
        } else {
            alert("장바구니를 사용하려면 로그인이 필요합니다.");
        }
    }
    </script>
</body>
</html>