<?php
session_start();

$host = "infodb.ansan.ac.kr";
$dbname = "db2151040_capstone";
$user = "i2151040";
$pass = "qkaqka0019@";

$pdo = null; // PDO 객체 초기화
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("데이터베이스 연결 실패: " . $e->getMessage());
}

$search_query = isset($_GET['search_query']) ? trim($_GET['search_query']) : '';

$sql = "
    SELECT 
        r.restaurant_id,
        r.name,
        r.opening_hours,
        r.image_url,
        COALESCE(ROUND(AVG(rv.rating), 1), 0.0) AS avg_rating, /* 리뷰가 없는 경우 0.0으로 표시 */
        COUNT(DISTINCT rv.review_id) AS review_count /* DISTINCT로 리뷰 중복 계산 방지 */
    FROM Restaurants r
    LEFT JOIN Reviews rv ON r.restaurant_id = rv.restaurant_id
";

$params = [];

if (!empty($search_query)) {
    $sql .= "
        LEFT JOIN Foods f ON r.restaurant_id = f.restaurant_id
        WHERE r.name LIKE :search_query OR f.name LIKE :search_query
    ";
    $params[':search_query'] = '%' . $search_query . '%';
}

$sql .= " GROUP BY r.restaurant_id, r.name, r.opening_hours, r.image_url ORDER BY r.restaurant_id ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$restaurants = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>안산대 M오더</title>
    <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: space-between; padding: 0 15px; height: 70px; box-sizing: border-box; }
        .header h1 { display: flex; align-items: center; font-size: 1.2em; margin: 0; flex-grow: 1; justify-content: center; }
        .header-logo-img { height: 50px; width: auto; margin-right: 8px; }
        .cart-link { text-decoration: none; color: inherit; display: flex; align-items: center; }
        .cart-icon { font-size: 1.5em; color: #555; cursor: pointer; }
        
        .search-bar { padding: 10px 15px; background-color: white; border-bottom: 1px solid #eee; }
        .search-form { display: flex; }
        .search-input-container { display: flex; flex-grow: 1; align-items: center; background-color: #f0f0f0; border-radius: 25px; padding: 8px 12px; }
        .search-icon { margin-right: 8px; color: #777; cursor: pointer; }
        .clear-icon { margin-left: 8px; color: #aaa; cursor: pointer; display: none; }
        .search-input-container input { flex-grow: 1; border: none; background-color: transparent; outline: none; font-size: 0.95em; }
        .search-button { 
            background: none; border: none; font-size: 1.2em; color: #007bff;
            padding: 0 0 0 10px; cursor: pointer; display: none; 
        }

        .content-list { flex: 1; overflow-y: auto; padding: 0 15px; }
        a.restaurant-item { text-decoration: none; color: inherit; display: flex; align-items: center; padding: 15px 0; border-bottom: 1px solid #eee; }
        .restaurant-item img { width: 80px; height: 80px; border-radius: 8px; margin-right: 15px; object-fit: cover; background-color: #eee; }
        .restaurant-info { flex-grow: 1; display: flex; justify-content: space-between; align-items: center; }
        .restaurant-info .details h2 { font-size: 1.1em; margin: 0 0 5px 0; color: #333; }
        .restaurant-info .details p { font-size: 0.85em; margin: 0; color: #666; }
        .restaurant-info .rating { display: flex; align-items: center; min-width: auto; font-size: 0.9em; color: #555; }
        .restaurant-info .rating .fa-star { color: #ffc107; margin-right: 3px; }
        .restaurant-info .rating .reviews { font-size: 0.9em; color: #888; margin-left: 4px; }
        .no-results { text-align: center; padding: 30px 15px; color: #777; }

        .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:hover, .bottom-nav a.active { color: #007bff; }
    </style>
</head>

<body>
    <div class="container">
        <header class="header">
            <h1>
                <img src="assets/images/임시로고.jpg" alt="안산대 M오더 로고" class="header-logo-img">
                <span>안산대 M오더</span>
            </h1>
            <a href="pages/order/cart.php" class="cart-link"> <i class="fas fa-shopping-cart cart-icon"></i></a>
        </header>

        <div class="search-bar">
            <form method="GET" action="main.php" class="search-form">
                <div class="search-input-container">
                    <i class="fas fa-search search-icon"></i>
                    <input type="text" name="search_query" placeholder="가게 또는 메뉴 검색" value="<?php echo htmlspecialchars($search_query); ?>">
                    <i class="fas fa-times-circle clear-icon" id="clearSearch"></i>
                </div>
                <button type="submit" class="search-button"><i class="fas fa-arrow-right"></i></button> </form>
        </div>

        <div class="content-list">
            <?php if (count($restaurants) > 0): ?>
                <?php foreach ($restaurants as $restaurant): ?>
                    <a href="pages/menu/menulist.php?restaurant_id=<?php echo $restaurant['restaurant_id']; ?>" class="restaurant-item">
                        <img src="<?php echo htmlspecialchars(!empty($restaurant['image_url']) ? $restaurant['image_url'] : '../../assets/images/default_store.png'); ?>" alt="<?php echo htmlspecialchars($restaurant['name']); ?> 로고">
                        <div class="restaurant-info">
                            <div class="details">
                                <h2><?php echo htmlspecialchars($restaurant['name']); ?></h2>
                                <p><?php echo htmlspecialchars($restaurant['opening_hours']); ?></p>
                            </div>
                            <div class="rating">
                                <i class="fas fa-star"></i>&nbsp;<?php echo $restaurant['avg_rating'] ?? '0.0'; ?>
                                <span class="reviews">(<?php echo $restaurant['review_count'] >= 999 ? '999+' : $restaurant['review_count']; ?>)</span>
                            </div>
                        </div>
                    </a>
                <?php endforeach; ?>
            <?php else: ?>
                <p class="no-results">
                    <?php echo !empty($search_query) ? "'" . htmlspecialchars($search_query) . "'에 대한 검색 결과가 없습니다." : "표시할 가게가 없습니다."; ?>
                </p>
            <?php endif; ?>
        </div>

        <nav class="bottom-nav">
            <a href="main.php" class="active"><i class="fas fa-home"></i></a>
            <a href="pages/user/dibs.php"><i class="fas fa-heart"></i></a>
            <a href="pages/order/orderlist.php"><i class="fas fa-receipt"></i></a>
            <a href="auth/redirect-mypage.php"><i class="fas fa-user"></i></a> </nav>
    </div>

    <script>
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.querySelector('.search-input-container input[name="search_query"]');
    const clearIcon = document.getElementById('clearSearch');
    const searchForm = document.querySelector('.search-form');
    const searchIconElement = document.querySelector('.search-icon');

    let previousSearchValue = searchInput.value;

    function toggleClearIcon() {
        if (searchInput.value.length > 0) {
            clearIcon.style.display = 'inline';
        } else {
            clearIcon.style.display = 'none';
        }
    }

    function showAllRestaurants() {
        if (window.location.search.includes("search_query=") && searchInput.value === '') { 
            window.location.href = 'main.php';
        } else if (searchInput.value === '') {
        }
    }

    searchInput.addEventListener('input', function() {
        toggleClearIcon();
        if (searchInput.value === '' && previousSearchValue !== '') {
            showAllRestaurants();
        }
        previousSearchValue = searchInput.value;
    });

    clearIcon.addEventListener('click', function() {
        searchInput.value = ''; 
        toggleClearIcon();
        showAllRestaurants(); 
    });

    if (searchIconElement) {
        searchIconElement.addEventListener('click', function() {
            searchForm.submit(); 
        });
    }

    toggleClearIcon();
});
    </script>
</body>
</html>