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

$restaurant_id_filter = null;
if (isset($_GET['restaurant_id']) && filter_var($_GET['restaurant_id'], FILTER_VALIDATE_INT)) {
    $restaurant_id_filter = (int)$_GET['restaurant_id'];
}

$reviews_data = [];
$restaurant_name_for_title = "";
$current_logged_in_user_id = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0; // 현재 로그인한 사용자 ID

if ($restaurant_id_filter) {
    // 가게 이름 가져오기
    $sql_restaurant_name = "SELECT name FROM Restaurants WHERE restaurant_id = ?";
    if ($stmt_restaurant_name = $conn->prepare($sql_restaurant_name)) {
        $stmt_restaurant_name->bind_param("i", $restaurant_id_filter);
        $stmt_restaurant_name->execute();
        $result_restaurant_name = $stmt_restaurant_name->get_result();
        if ($row_restaurant_name = $result_restaurant_name->fetch_assoc()) {
            $restaurant_name_for_title = htmlspecialchars($row_restaurant_name['name']);
        }
        $stmt_restaurant_name->close();
    }

    // 특정 가게의 리뷰 정보 + 좋아요 정보 가져오기
    $sql_reviews = "SELECT
                        r.review_id, r.user_id, r.restaurant_id, r.order_id,
                        u.username,
                        r.rating AS review_rating, r.comment, r.photo_url AS review_photo_url,
                        r.created_at,
                        (SELECT COUNT(*) FROM Reviews WHERE user_id = r.user_id) AS total_user_reviews,
                        (SELECT AVG(rating) FROM Reviews WHERE user_id = r.user_id) AS avg_user_rating,
                        (SELECT COUNT(*) FROM ReviewLikes WHERE review_id = r.review_id) AS like_count,
                        EXISTS(SELECT 1 FROM ReviewLikes WHERE review_id = r.review_id AND user_id = ?) AS user_has_liked
                    FROM Reviews r
                    JOIN Users u ON r.user_id = u.user_id
                    WHERE r.restaurant_id = ?
                    ORDER BY r.created_at DESC";

    if ($stmt_reviews = $conn->prepare($sql_reviews)) {
        $stmt_reviews->bind_param("ii", $current_logged_in_user_id, $restaurant_id_filter);
        $stmt_reviews->execute();
        $result_reviews = $stmt_reviews->get_result();

        if ($result_reviews) {
            while ($review_row = $result_reviews->fetch_assoc()) {
                $reviews_data[] = $review_row;
            }
            $result_reviews->free();
        } else {
            error_log("리뷰 데이터 조회 실패: " . $conn->error);
        }
        $stmt_reviews->close();
    } else {
        error_log("리뷰 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_for_title ? htmlspecialchars($restaurant_name_for_title) . ' - ' : ''; ?>리뷰
    </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: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: #f4f4f4;
        }

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

        .main-content {
            flex: 1;
            overflow-y: auto;
        }

        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px 15px;
            border-bottom: 1px solid #e0e0e0;
            background-color: #fff;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .header h2 {
            margin: 0;
            font-size: 1.1em;
            font-weight: 600;
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
        }

        .back-button {
            text-decoration: none;
            color: #333;
            font-size: 1.2em;
        }

        .header .placeholder {
            width: 24px;
        }

        .review-list {
            padding: 15px;
        }

        .review-item-container {
            border: 1px solid #e9e9e9;
            border-radius: 8px;
            margin-bottom: 15px;
            background-color: #fff;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
        }

        .review-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding: 12px 15px;
            border-bottom: 1px solid #f0f0f0;
        }

        .left-section {
            display: flex;
            align-items: flex-start;
        }

        .profile-img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 10px;
            background-color: #eee;
        }

        .user-info {
            font-size: 0.9em;
            line-height: 1.5;
            color: #555;
        }

        .user-info strong {
            font-weight: 600;
            color: #000;
            font-size: 1.05em;
        }

        .user-info .user-stats {
            font-size: 0.85em;
            color: #777;
            margin-top: 2px;
            align-items: center;
            gap: 5px;
        }

        /* 신고하기 버튼 위해 flex 추가 */
        .stars {
            color: #f1c40f;
            font-size: 0.9em;
            display: inline-block;
            margin-right: 4px;
        }

        .review-time {
            font-size: 0.75em;
            color: #888;
            white-space: nowrap;
            padding-top: 2px;
        }

        .review-card-content {
            padding: 12px 15px;
        }

        .review-content {
            font-size: 0.95em;
            line-height: 1.6;
            color: #333;
            white-space: pre-line;
            margin-bottom: 10px;
        }

        .review-image {
            width: 100%;
            max-height: 250px;
            object-fit: cover;
            border-radius: 6px;
            margin-bottom: 10px;
            background-color: #f0f0f0;
        }

        .menu-tags-container {
            margin-top: 10px;
            margin-bottom: 10px;
        }

        .menu-name-tag {
            font-size: 0.8em;
            color: #007bff;
            background-color: #e9f3ff;
            padding: 4px 8px;
            display: inline-block;
            border-radius: 4px;
            margin-right: 5px;
            margin-bottom: 5px;
        }

        .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;
            transition: color 0.2s;
        }

        .bottom-nav a:hover,
        .bottom-nav a.active {
            color: #007bff;
        }

        .no-reviews-message {
            text-align: center;
            padding: 30px;
            color: #777;
        }

        .report-button {
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            color: #6c757d;
            padding: 2px 6px;
            font-size: 0.7em;
            border-radius: 3px;
            cursor: pointer;
            text-decoration: none;
            margin-left: 8px;
        }

        .report-button:hover {
            background-color: #e2e6ea;
        }

        .like-section {
            margin-top: 10px;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .like-button {
            background: none;
            border: none;
            padding: 5px;
            cursor: pointer;
            font-size: 1.2em;
            color: #ccc;
        }

        .like-button.liked {
            color: #007bff;
        }

        .like-count {
            font-size: 0.9em;
            color: #555;
        }
    </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>
                <h2>
                    <?php echo $restaurant_name_for_title ? htmlspecialchars($restaurant_name_for_title) . ' 리뷰' : '리뷰'; ?>
                </h2>
                <div class="placeholder"></div>
            </div>

            <div class="review-list">
                <?php
                if (!$restaurant_id_filter) {
                    echo "<p class='no-reviews-message'>가게 정보가 올바르지 않습니다.</p>";
                } elseif (!empty($reviews_data)) {
                    foreach ($reviews_data as $review) {
                        $profile_image = '../assets/images/기본프로필.png';
                        $created_at_formatted = date("Y.m.d", strtotime($review['created_at']));
                        $avg_rating_formatted = number_format((float)$review['avg_user_rating'], 1);
                        $user_has_liked = (bool)$review['user_has_liked'];
                ?>
                <div class="review-item-container">
                    <div class="review-header">
                        <div class="left-section">
                            <img src="<?php echo $profile_image; ?>" alt="프로필" class="profile-img" />
                            <div class="user-info">
                                <strong>
                                    <?php echo htmlspecialchars($review['username']); ?>
                                </strong><br />
                                <div class="rating-and-stats-line">
                                    <div class="stars"
                                        data-rating="<?php echo htmlspecialchars($review['review_rating']); ?>"></div>
                                    <span class="user-stats">
                                        <span class="user-stats-text">
                                            리뷰
                                            <?php echo htmlspecialchars($review['total_user_reviews']); ?> &nbsp;·&nbsp;
                                            평균 ★
                                            <?php echo htmlspecialchars($avg_rating_formatted); ?>
                                        </span>
                                        <?php
                                            if ($current_logged_in_user_id > 0) :
                                                $review_page_uri_for_report = htmlspecialchars($_SERVER['REQUEST_URI']);
                                                $declaration_link = "declaration.php?review_id=" . $review['review_id'] . "&reported_user_id=" . $review['user_id'] . "&return_url=" . urlencode($review_page_uri_for_report);
                                            ?>
                                        <a href="<?php echo $declaration_link; ?>" class="report-button">신고</a>
                                        <?php else :
                                                $login_page_url_for_report = '../../auth/login.php'; // 실제 로그인 페이지 경로
                                                $redirect_after_login_for_report = urlencode($_SERVER['REQUEST_URI']); 
                                                $login_link_for_report = $login_page_url_for_report . '?redirect=' . $redirect_after_login_for_report;
                                            ?>
                                        <button type="button" class="report-button"
                                            onclick="handleReportClick('<?php echo $login_link_for_report; ?>')">신고</button>
                                        <?php endif; ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div class="review-time">
                            <?php echo $created_at_formatted; ?>
                        </div>
                    </div>
                    <div class="review-card-content">
                        <div class="review-content">
                            <?php echo nl2br(htmlspecialchars($review['comment'])); ?>
                        </div>
                        <?php if (!empty($review['review_photo_url'])) : ?>
                        <img src="<?php echo htmlspecialchars($review['review_photo_url']); ?>" alt="리뷰 사진"
                            class="review-image" />
                        <?php endif; ?>

                        <?php
                            $ordered_menus_for_this_review = [];
                            if (!empty($review['order_id'])) {
                                $sql_ordered_items = "SELECT f.name AS food_name FROM OrderItems oi JOIN Foods f ON oi.food_id = f.food_id WHERE oi.order_id = ?";
                                if ($stmt_ordered_items = $conn->prepare($sql_ordered_items)) {
                                    $stmt_ordered_items->bind_param("i", $review['order_id']);
                                    $stmt_ordered_items->execute();
                                    $result_items = $stmt_ordered_items->get_result();
                                    while ($item_row = $result_items->fetch_assoc()) {
                                        $ordered_menus_for_this_review[] = htmlspecialchars($item_row['food_name']);
                                    }
                                    $stmt_ordered_items->close();
                                }
                            }
                            ?>
                        <?php if (!empty($ordered_menus_for_this_review)) : ?>
                        <div class="menu-tags-container">
                            <?php foreach ($ordered_menus_for_this_review as $menu_name_display): ?>
                            <span class="menu-name-tag">
                                <?php echo $menu_name_display; ?>
                            </span>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>

                        <div class="like-section">
                            <button class="like-button <?php echo $user_has_liked ? 'liked' : ''; ?>"
                                data-review-id="<?php echo $review['review_id']; ?>">
                                <i class="<?php echo $user_has_liked ? 'fas' : 'far'; ?> fa-thumbs-up"></i>
                            </button>
                            <span class="like-count" id="like-count-<?php echo $review['review_id']; ?>">
                                <?php echo htmlspecialchars($review['like_count']); ?>
                            </span>
                        </div>
                    </div>
                </div>
                <?php
                    }
                } else {
                    echo "<p class='no-reviews-message'>작성된 리뷰가 없습니다.</p>";
                }
                ?>
            </div>
        </div>

        <nav class="bottom-nav">
            <a href="../../main.php" <?php echo (strpos($_SERVER['PHP_SELF'], 'main.php' ) !==false ? 'class="active"'
                : '' ); ?>><i class="fas fa-home"></i></a>
            <a href="../user/dibs.php" <?php echo (strpos($_SERVER['PHP_SELF'], 'dibs.php' ) !==false ? 'class="active"'
                : '' ); ?>><i class="fas fa-heart"></i></a>
            <a href="../order/orderlist.php" <?php echo (strpos($_SERVER['PHP_SELF'], 'orderlist.php' ) !==false
                ? 'class="active"' : '' ); ?>><i class="fas fa-receipt"></i></a>
            <a href="../../auth/redirect-mypage.php" <?php echo (strpos($_SERVER['PHP_SELF'], 'mypage.php' ) !==false
                ? '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>
        function renderStars(container, rating) {
            if (container && typeof rating === 'number') {
                const fullStar = '<i class="fas fa-star"></i>';
                const halfStar = '<i class="fas fa-star-half-alt"></i>';
                const emptyStar = '<i class="far fa-star"></i>';
                let html = '';
                for (let i = 1; i <= 5; i++) {
                    if (rating >= i) { html += fullStar; }
                    else if (rating >= i - 0.5) { html += halfStar; }
                    else { html += emptyStar; }
                }
                container.innerHTML = html;
            }
        }

        document.addEventListener("DOMContentLoaded", () => {
            document.querySelectorAll(".stars").forEach(el => {
                const rating = parseFloat(el.dataset.rating);
                if (!isNaN(rating)) { renderStars(el, rating); }
            });

            const isLoggedIn = <?php echo json_encode($current_logged_in_user_id > 0); ?>;
            const loginPageUrl = '../../auth/login.php';

            // 좋아요 버튼 로직
            $('.like-button').on('click', function () {
                if (!isLoggedIn) {
                    alert('로그인한 사용자만 좋아요 버튼을 누를 수 있습니다. 로그인 페이지로 이동합니다.');
                    window.location.href = loginPageUrl + '?redirect=' + encodeURIComponent(window.location.href);
                    return;
                }

                var button = $(this);
                var reviewId = button.data('review-id');
                var icon = button.find('i');
                var likeCountSpan = $('#like-count-' + reviewId);

                $.ajax({
                    url: '../../auth/toggle_review_like.php',
                    type: 'POST',
                    data: { review_id: reviewId },
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            likeCountSpan.text(response.new_like_count);
                            if (response.liked) {
                                button.addClass('liked');
                                icon.removeClass('far').addClass('fas');
                            } else {
                                button.removeClass('liked');
                                icon.removeClass('fas').addClass('far');
                            }
                        } else {
                            alert('오류: ' + response.message);
                        }
                    },
                    error: function () {
                        alert('좋아요 처리 중 서버 오류가 발생했습니다.');
                    }
                });
            });
        });

        // 신고 버튼 클릭 처리 함수 (전역으로 정의)
        function handleReportClick(loginLinkForReport) {
            alert('로그인하지 않은 사용자는 신고 기능을 사용할 수 없습니다. 로그인 페이지로 이동합니다.');
            window.location.href = loginLinkForReport;
        }
    </script>
    <?php
    if (isset($conn) && $conn instanceof mysqli) {
        $conn->close();
    }
    ?>
</body>

</html>
