<?php
    require_once 'config.php'; // načítanie konfigurácie databázy
    include 'session_check.php';

    // logika triedenia produktov
    $sort_options = [
        'default' => 'id ASC',
        'price_asc' => 'price ASC',
        'price_desc' => 'price DESC',
        'rating_desc' => 'rating DESC',
    ];
    $sort_key = $_GET['sort'] ?? 'default';
    if (!array_key_exists($sort_key, $sort_options)) {
        $sort_key = 'default';
    }
    $order_by_clause = $sort_options[$sort_key];
    // koniec logiky triedenia

    // logika vyhľadávania produktov
    $search_term = trim($_GET['search'] ?? '');
    $where_clauses = [];
    $params = []; // parametre pre prepared statement

    if (!empty($search_term)) {
        $where_clauses[] = "name LIKE ?";
        $params[] = "%{$search_term}%"; // pridá % pre LIKE vyhľadávanie
    }
    // koniec logiky vyhľadávania

    // načítanie produktov z databázy (iba s dostupným skladom)
    $products = [];
    try {
        $sql = "SELECT p.id, p.name, p.price, p.product_gallery, p.rating FROM products p WHERE (SELECT COALESCE(SUM(ps.quantity), 0) FROM product_stock ps WHERE ps.product_id = p.id) > 0";

        // pridá WHERE pre vyhľadávanie
        if (!empty($where_clauses)) {
            $sql .= " AND " . implode(' AND ', array_map(function($c) { return str_replace('name ', 'p.name ', $c); }, $where_clauses));
        }

        $sql .= " ORDER BY " . str_replace(['id', 'name', 'price', 'rating'], ['p.id', 'p.name', 'p.price', 'p.rating'], $order_by_clause);

        $stmt = $pdo->prepare($sql); // pripraví statement
        $stmt->execute($params); // vykoná s parametrami
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    } catch (PDOException $e) {
        // chyba pri načítaní produktov
        error_log("Database error fetching products: " . $e->getMessage());
        $_SESSION['error_message'] = "Error loading products. Please try again later.";
    }

    // zobrazenie správ o úspechu/chybe
    if (isset($_SESSION['success_message'])) {
        echo '<p style="color: green; text-align: center;">' . htmlspecialchars($_SESSION['success_message']) . '</p>';
        unset($_SESSION['success_message']);
    }
    if (isset($_SESSION['error_message'])) {
        echo '<p style="color: red; text-align: center;">' . htmlspecialchars($_SESSION['error_message']) . '</p>';
        unset($_SESSION['error_message']);
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>All Products - ShoeBox</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,500;0,600;0,700;1,300&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="style.css">
</head>
<body class="page-products">
    <div class="header" style="background: #fff !important;">
        <div class="container">
            <div class="navbar">
                <div class="logo">
                    <a href="index.php"><img src="obrazky/logo.png" width="125px"></a>
                </div>
                <nav>
                    <ul id="MenuItems">
                        <li><a href="index.php">Home</a></li>
                        <li><a href="products.php">Product</a></li>
                        <li><a href="about.php">About</a></li>
                        <li><a href="contact.php">Contact</a></li>
                        <?php if ($is_logged_in): ?>
                            <li><a href="account.php"><?php echo htmlspecialchars($username); ?></a></li>
                            <?php if ($is_admin): ?><li><a href="admin/index.php">Admin</a></li><?php endif; ?>
                            <li><a href="logout.php">Logout</a></li>
                        <?php else: ?>
                            <li><a href="account.php">Login/Register</a></li>
                        <?php endif; ?>
                    </ul>
                </nav>
                <a href="cart.php"><img src="obrazky/cart.svg" class="cart-icon" width="30px" height="30px"></a>
                <img src="obrazky/menu.png" class="menu-icon" onclick="menutoggel()">
            </div>
        </div>
    </div>
    <div class="small-container" style="text-align: center; margin-top: 10px; margin-bottom: 0;">
        <?php
        // Moved message display here from top
        if (isset($_SESSION['success_message'])) {
            echo '<p style="color: green;">' . htmlspecialchars($_SESSION['success_message']) . '</p>';
            unset($_SESSION['success_message']);
        }
        if (isset($_SESSION['error_message'])) {
            echo '<p style="color: red;">' . htmlspecialchars($_SESSION['error_message']) . '</p>';
            unset($_SESSION['error_message']);
        }
        ?>
    </div>
    <div class="small-container">
        <div class="row row-2">
            <h2>All Products</h2>
            <!-- Filter Form (Search + Sort) -->
            <form method="GET" action="products.php" id="filterForm" class="filter-form" style="display: flex; align-items: center; gap: 10px;">
                
                <input type="text" name="search" placeholder="Search products..." value="<?= htmlspecialchars($search_term) ?>" style="padding: 5px;">
                
                <select name="sort" style="padding: 5px;"> <!-- Removed onchange -->
                    <option value="default" <?= ($sort_key == 'default') ? 'selected' : '' ?>>Default Sorting</option>
                    <option value="price_asc" <?= ($sort_key == 'price_asc') ? 'selected' : '' ?>>Sort by price: low to high</option>
                    <option value="price_desc" <?= ($sort_key == 'price_desc') ? 'selected' : '' ?>>Sort by price: high to low</option>
                    <option value="rating_desc" <?= ($sort_key == 'rating_desc') ? 'selected' : '' ?>>Sort by rating</option>
                </select>
                 
                <button type="submit" class="btn" style="padding: 6px 12px;">Filter</button>

                 <!-- Keep other existing GET parameters hidden -->
                 <?php
                    foreach ($_GET as $key => $value) {
                        if (!in_array($key, ['sort', 'search'])) { // Exclude sort and search
                            echo "<input type='hidden' name='" . htmlspecialchars($key) . "' value='" . htmlspecialchars($value) . "'>";
                        }
                    }
                 ?>
            </form>
        </div>

        <div class="row">
            <?php if (empty($products)): ?>
                <p>No products found.</p>
            <?php else: ?>
                <?php foreach ($products as $product): ?>
                    <div class="col-4">
                        <a href="product_detail.php?id=<?= htmlspecialchars($product['id']) ?>">
                            <img src="<?= image_url_src(product_main_image($product['product_gallery'] ?? null)) ?>" alt="<?= htmlspecialchars($product['name']) ?>">
                        </a>
                        <a href="product_detail.php?id=<?= htmlspecialchars($product['id']) ?>">
                             <h4><?= htmlspecialchars($product['name']) ?></h4>
                        </a>
                        <div class="rating">
                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                <span class="fa fa-star<?= ($i <= $product['rating']) ? ' checked' : '' ?>"></span>
                            <?php endfor; ?>
                        </div>
                        <p>€<?= htmlspecialchars(number_format($product['price'], 2)) ?></p>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- Pagination (needs server-side implementation) -->
        <div class="page-btn">
            <span>1</span>
            <span>2</span>
            <span>3</span>
            <span>4</span>
            <span>&#8594;</span>
        </div>
    </div>

    <!--footer-->
    <div class="footer">
        <div class="container">
            <div class="row">
                <div class="footer-col-1">
                    <h3>Download Our App</h3>
                    <p>Download App for Android and IOS Mobile phone.</p>
                    <br>
                    <div class="app-logo">
                        <img src="obrazky/play-store.png">
                        <img src="obrazky/app-store.png">
                    </div>
                </div>
                <div class="footer-col-2">
                    <img src="obrazky/logo-white.png">
                    <p>Our Purpose Is To Sustainably Make the Pleasure and Benefits of Sports Accessible to the Many</p>
                </div>
                <div class="footer-col-3">
                    <h3>Useful Links</h3>
                    <ul>
                        <li>Cupons</li>
                        <li>Blog Post</li>
                        <li>Return Policy</li>
                        <li>Join Affliate</li>
                    </ul>
                </div>
                <div class="footer-col-4">
                    <h3>Follow us</h3>
                    <ul>
                        <li>Facebook</li>
                        <li>Twitter</li>
                        <li>Instagram</li>
                        <li>YouTube</li>
                    </ul>
                </div>
            </div>
            <hr>
            <p class="copyright">Copyright 2025 Alex Melicher</p>
        </div>
    </div>

    <!-- JS etc. -->
    <script>
        var MenuItems = document.getElementById("MenuItems");
        MenuItems.style.maxHeight = "0px";
        function menutoggel() {
            if(MenuItems.style.maxHeight == "0px") {
                MenuItems.style.maxHeight = "200px"
            } else {
                MenuItems.style.maxHeight = "0px"
            }
        }
    </script>
</body>
</html> 