<?php
session_start();
require_once "../../includes/db_connect.php";

// 1. URL 파라미터에서 restaurant_id 가져오기 (없으면 기본값 1 사용)
$restaurant_id_to_display = isset($_GET['restaurant_id']) ? (int)$_GET['restaurant_id'] : 1;

$restaurant_name_from_db = "가게 정보 없음";
$restaurant_image_url_from_db = "../../assets/images/default_image.png"; // 기본 이미지 경로

$overall_average_rating = 0.0;
$total_review_count = 0;

$recommended_menu_items = []; // 추천 메뉴 (Upvote = TRUE)
$all_menu_items = [];       // 전체 메뉴 (Upvote 상관없이)

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

// 2. 가게 기본 정보 조회
$sql_restaurant = "SELECT name, image_url FROM Restaurants WHERE restaurant_id = ?";
if ($stmt_restaurant = $conn->prepare($sql_restaurant)) {
    $stmt_restaurant->bind_param("i", $restaurant_id_to_display);
    $stmt_restaurant->execute();
    $result_restaurant = $stmt_restaurant->get_result();
    if ($row_restaurant = $result_restaurant->fetch_assoc()) {
        $restaurant_name_from_db = htmlspecialchars($row_restaurant['name']);
        if (!empty($row_restaurant['image_url'])) {
            $restaurant_image_url_from_db = htmlspecialchars($row_restaurant['image_url']);
        }
    } else {
        // 해당 ID의 가게가 없을 경우 사용자에게 알림
        $restaurant_name_from_db = "가게 정보를 찾을 수 없습니다 (ID: " . $restaurant_id_to_display . ")";
        // 이 경우, 아래 메뉴 조회 등은 의미가 없으므로 추가적인 오류 처리나 리디렉션 고려 가능
    }
    $stmt_restaurant->close();
} else {
    error_log("menulist.php: 가게 정보 SQL 준비 실패: " . $conn->error);
}

// 3. 가게 전체 평균 별점 및 총 리뷰 수 계산 (기존 로직 유지)
$sql_store_overall_rating = "SELECT
                                COALESCE(AVG(rating), 0) AS store_avg_rating,
                                COUNT(review_id) AS store_total_reviews
                             FROM Reviews
                             WHERE restaurant_id = ?";
if ($stmt_store_overall = $conn->prepare($sql_store_overall_rating)) {
    $stmt_store_overall->bind_param("i", $restaurant_id_to_display);
    $stmt_store_overall->execute();
    $result_store_overall = $stmt_store_overall->get_result();
    if ($row_overall = $result_store_overall->fetch_assoc()) {
        $overall_average_rating = (float)$row_overall['store_avg_rating'];
        $total_review_count = (int)$row_overall['store_total_reviews'];
    }
    $stmt_store_overall->close();
} else {
    error_log("menulist.php: 가게 전체 평점 SQL 준비 실패 (restaurant_id: {$restaurant_id_to_display}): " . $conn->error);
}

// 4. 추천 메뉴 조회 (Upvote = TRUE)
$sql_recommended_menu = "SELECT
                            f.food_id, f.name AS food_name, f.description AS food_description,
                            f.price AS food_price, f.image_url AS food_image_url
                         FROM Foods f
                         WHERE f.restaurant_id = ? AND f.Upvote = 1 -- 또는 f.Upvote = 1 (DB 스키마에 따라)
                         ORDER BY f.food_id ASC"; // 또는 다른 추천 정렬 기준
if ($stmt_recommended = $conn->prepare($sql_recommended_menu)) {
    $stmt_recommended->bind_param("i", $restaurant_id_to_display);
    $stmt_recommended->execute();
    $result_recommended = $stmt_recommended->get_result();
    while ($row = $result_recommended->fetch_assoc()) {
        $recommended_menu_items[] = $row;
    }
    $stmt_recommended->close();
} else {
    error_log("menulist.php: 추천 메뉴 SQL 준비 실패: " . $conn->error);
}

// 5. 전체 음식 메뉴 조회 (Upvote 값과 상관없이 모두)
$sql_all_menu = "SELECT
                    f.food_id, f.name AS food_name, f.description AS food_description,
                    f.price AS food_price, f.image_url AS food_image_url, f.Upvote
                 FROM Foods f
                 WHERE f.restaurant_id = ?
                 ORDER BY f.food_id ASC"; // 또는 다른 정렬 기준 (예: 추천 메뉴 먼저 등)
if ($stmt_all_menu = $conn->prepare($sql_all_menu)) {
    $stmt_all_menu->bind_param("i", $restaurant_id_to_display);
    $stmt_all_menu->execute();
    $result_all_menu = $stmt_all_menu->get_result();
    while ($row = $result_all_menu->fetch_assoc()) {
        $all_menu_items[] = $row;
    }
    $stmt_all_menu->close();
} else {
    error_log("menulist.php: 전체 메뉴 SQL 준비 실패: " . $conn->error);
}
?>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><?php echo $restaurant_name_from_db; ?> - 메뉴</title>
    <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%; margin: 0; font-family: sans-serif; }
        .app-container { max-width: 400px; height: 100%; margin: 0 auto; display: flex; flex-direction: column; background-color: #fff; border-left: 1px solid #eee; border-right: 1px solid #eee; }
        .main-content { flex: 1; overflow-y: auto; }
        .header { display: flex; justify-content: space-between; align-items: center; padding: 10px 15px; border-bottom: 1px solid #ddd; position: sticky; top: 0; background-color: #fff; z-index: 100; }
        .back-button { text-decoration: none; color: #333; font-size: 1.5em; }
        .cart-link { text-decoration: none; color: inherit; }
        .cart-icon { font-size: 1.5em; color: #555; }

        .store-info { padding: 15px; }
        .store-info img { width: 100%; height: 180px; object-fit: cover; border-radius: 8px; margin-bottom: 10px; background-color: #f0f0f0; }
        .store-info-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
        .store-info-row h2 { margin: 0; font-size: 1.4em; color: #333; }
        .favorite-icon { cursor: pointer; font-size: 1.5em; color: #ccc; }
        .favorite-icon.liked { color: #e74c3c; }

        .store-rating { display: flex; justify-content: space-between; align-items: center; padding: 0 15px 15px; border-bottom: 1px solid #f0f0f0; margin-bottom: 10px;}
        .store-rating .left { font-size: 0.95em; color: #555; }
        .store-rating .left .fa-star { color: #f1c40f; margin-right: 4px; }
        .store-rating .left a { color: inherit; text-decoration: none;}
        .store-rating .right button { background: #f0f0f0; border: 1px solid #ddd; padding: 6px 12px; border-radius: 5px; cursor: pointer; font-size: 0.85em; color: #333; }

        .section-title { padding: 10px 15px; font-weight: bold; font-size: 1.1em; background-color: #f9f9f9; border-top: 1px solid #eee; border-bottom: 1px solid #eee; margin-top: -1px; }
        
        .menu-item-link { display: block; text-decoration: none; color: inherit; }
        .menu-item { display: flex; padding: 15px; border-bottom: 1px solid #f0f0f0; align-items: center; }
        .menu-item:last-child { border-bottom: none; }
        .menu-image img { width: 80px; height: 80px; object-fit: cover; border-radius: 8px; margin-right: 15px; background-color: #eee; }
        
        .menu-info { flex: 1; }
        .menu-info h4 { margin: 0 0 5px; font-size: 1.05em; color: #333; }
        .menu-info .price { margin-bottom: 5px; font-size: 0.95em; color: #111; font-weight: 500;}
        .menu-info .description { font-size: 0.85em; color: #666; line-height: 1.4; }
        .recommended-tag {
            background-color: #ffc107; color: white; font-size: 0.7em; padding: 2px 5px; 
            border-radius: 3px; margin-left: 5px; vertical-align: middle;
        }
        
        .no-menu { padding: 20px 15px; text-align: center; color: #777; }

        .bottom-nav { display: flex; justify-content: space-around; align-items: center; padding: 10px 0; border-top: 1px solid #ddd; background-color: white; flex-shrink: 0; }
        .bottom-nav a { color: #555; font-size: 1.5em; text-decoration: none; padding: 10px 15px; }
        .bottom-nav a.active, .bottom-nav a:hover { color: #007bff; }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="main-content">
            <div class="header">
                <a href="javascript:history.back();" class="back-button"><i class="fas fa-arrow-left"></i></a>
                <a href="../order/cart.php" class="cart-link"><i class="fas fa-shopping-cart cart-icon"></i></a>
            </div>

            <div class="store-info">
                <img src="<?php echo $restaurant_image_url_from_db; ?>" alt="<?php echo $restaurant_name_from_db; ?> 대표사진" />
                <div class="store-info-row">
                    <h2><?php echo $restaurant_name_from_db; ?></h2>
                    <span class="favorite-icon" data-restaurant-id="<?php echo $restaurant_id_to_display; ?>">
                        <i class="far fa-heart"></i>
                    </span>
                </div>
            </div>

            <div class="store-rating">
                <div class="left">
                    <a href="../review/review.php?restaurant_id=<?php echo $restaurant_id_to_display; ?>">
                        <i class="fas fa-star"></i>
                        <?php echo number_format($overall_average_rating, 1); ?> 
                        <span style="color: #888;">(<?php echo $total_review_count; ?>)</span>
                    </a>
                </div>
                <div class="right">
                     <button onclick="location.href='../store/store_detail.php?restaurant_id=<?php echo $restaurant_id_to_display; ?>'">가게정보</button>
                </div>
            </div>

            <?php if (!empty($recommended_menu_items)): ?>
            <div class="section-title">추천 메뉴</div>
                <?php foreach ($recommended_menu_items as $item): ?>
                    <a href="menu_detail.php?restaurant_id=<?php echo $restaurant_id_to_display; ?>&food_id=<?php echo $item['food_id']; ?>" class="menu-item-link">
                        <div class="menu-item"> 
                            <div class="menu-image">
                                <img src="<?php echo htmlspecialchars(!empty($item['food_image_url']) ? $item['food_image_url'] : '../../assets/images/비빔밥.png'); ?>" alt="<?php echo htmlspecialchars($item['food_name']); ?>" />
                            </div>
                            <div class="menu-info">
                                <h4><?php echo htmlspecialchars($item['food_name']); ?></h4>
                                <div class="price">₩<?php echo number_format($item['food_price']); ?></div>
                                <div class="description"><?php echo nl2br(htmlspecialchars($item['food_description'])); ?></div>
                            </div>
                        </div>
                    </a>
                <?php endforeach; ?>
            <?php endif; ?>

            <div class="section-title">음식 메뉴</div>
            <?php if (!empty($all_menu_items)): ?>
                <?php foreach ($all_menu_items as $item): ?>
                    <a href="menu_detail.php?restaurant_id=<?php echo $restaurant_id_to_display; ?>&food_id=<?php echo $item['food_id']; ?>" class="menu-item-link">
                        <div class="menu-item"> 
                            <div class="menu-image">
                                <img src="<?php echo htmlspecialchars(!empty($item['food_image_url']) ? $item['food_image_url'] : '../../assets/images/비빔밥.png'); ?>" alt="<?php echo htmlspecialchars($item['food_name']); ?>" />
                            </div>
                            <div class="menu-info">
                                <h4>
                                    <?php echo htmlspecialchars($item['food_name']); ?>
                                    <?php if ($item['Upvote']): // Upvote가 TRUE이면 추천 태그 표시 ?>
                                        <span class="recommended-tag">추천</span>
                                    <?php endif; ?>
                                </h4>
                                <div class="price">₩<?php echo number_format($item['food_price']); ?></div>
                                <div class="description"><?php echo nl2br(htmlspecialchars($item['food_description'])); ?></div>
                            </div>
                        </div>
                    </a>
                <?php endforeach; ?>
            <?php else: ?>
                <p class="no-menu">메뉴가 없습니다.</p>
            <?php endif; ?>
        </div> 

        <nav class="bottom-nav">
             <a href="../../main.php" <?php echo (basename($_SERVER['PHP_SELF']) == 'main.php' ? 'class="active"' : ''); ?>><i class="fas fa-home"></i></a>
            <a href="../user/dibs.php" <?php echo (basename($_SERVER['PHP_SELF']) == 'dibs.php' ? 'class="active"' : ''); ?>><i class="fas fa-heart"></i></a>
            <a href="../order/orderlist.php" <?php echo (basename($_SERVER['PHP_SELF']) == 'orderlist.php' ? 'class="active"' : ''); ?>><i class="fas fa-receipt"></i></a>
            <a href="../../auth/redirect-mypage.php" <?php echo (basename($_SERVER['PHP_SELF']) == 'mypage.php' ? 'class="active"' : ''); ?>><i class="fas fa-user"></i></a>
        </nav>
    </div> 

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
    $(document).ready(function () {
        const isLoggedIn = <?php echo json_encode($is_logged_in); ?>;
        const loginPageUrl = '../../auth/login.php'; 
        const initialRestaurantId = $('.favorite-icon').data('restaurant-id');

        if (isLoggedIn && initialRestaurantId) {
            checkFavoriteStatus(initialRestaurantId);
        }

        $('.favorite-icon').on('click', function () {
            if (!isLoggedIn) {
                alert('찜 기능을 사용하려면 로그인이 필요합니다. 로그인 페이지로 이동합니다.');
                const currentPageUrl = window.location.href;
                window.location.href = loginPageUrl + '?redirect=' + encodeURIComponent(currentPageUrl);
                return;
            }

            const restaurantId = $(this).data('restaurant-id');
            const icon = $(this).find('i');
            const spanElement = $(this);

            $.ajax({
                url: '../../auth/toggle_favorite.php',
                type: 'POST',
                data: { restaurant_id: restaurantId },
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        if (response.isFavorited) {
                            icon.removeClass('far').addClass('fas');
                            spanElement.addClass('liked');
                        } else {
                            icon.removeClass('fas').addClass('far');
                            spanElement.removeClass('liked');
                        }
                    } else {
                        alert('찜 처리 중 오류: ' + (response.message || '알 수 없는 오류'));
                    }
                },
                error: function (xhr) {
                    console.error("찜 토글 AJAX Error:", xhr.responseText);
                    alert('서버와 통신 중 오류가 발생했습니다.');
                }
            });
        });

        function checkFavoriteStatus(restaurantId) {
            if (!isLoggedIn) return;
            $.ajax({
                url: '../../auth/check_favorite_status.php',
                type: 'GET',
                data: { restaurant_id: restaurantId },
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.isFavorited) {
                        const icon = $('.favorite-icon[data-restaurant-id="' + restaurantId + '"]').find('i');
                        const spanElement = $('.favorite-icon[data-restaurant-id="' + restaurantId + '"]');
                        icon.removeClass('far').addClass('fas');
                        spanElement.addClass('liked');
                    } else if (!response.success) {
                         console.log('찜 상태 확인 실패: ' + (response.message || '알 수 없는 오류'));
                    }
                },
                error: function(xhr) {
                    console.error('찜 상태 확인 AJAX Error:', xhr.responseText);
                }
            });
        }
    });
    </script>
</body>
</html>
<?php
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>