<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

$host = "192.168.1.20";
$database = "orologi";
$user = "pdo";
$password = "";

try {
    $connection = new PDO("mysql:host=$host;dbname=$database", $user, $password);
    $marche = $connection->prepare("SELECT marca FROM marche");
    $marche->execute();

    if (empty($_GET["marca"])) {
        $prepare = $connection->prepare("SELECT Codice, Modello, Marca, Prezzo FROM orologi ORDER BY Marca");
    } else {
        $marca = $_GET["marca"];
        $prepare = $connection->prepare("SELECT Codice, Modello, Marca, Prezzo FROM orologi WHERE Marca = ? ORDER BY Marca");
        $prepare->bindParam(1, $marca);
    }

    $prepare->execute();

    $connection = null;

} catch (PDOException $e) {
    die ("Error!: " . $e->getMessage() . "<br/>");
}

?>

<html lang="en">
<head>
    <title>HTML</title>
    <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css"
    >
</head>

<body>
    <main class="container">
        <nav>
            <ul>
                <li><strong>Acme Corp</strong></li>
            </ul>
            <ul>
                <li>
                    <form>
                        <select name="favorite-cuisine" aria-label="Cerca per Marca" required
                                onchange="redirectToMarca(this)">
                            <option selected disabled value="">
                                Cerca per Marca
                            </option>
                            <?php foreach ($marche->fetchAll() as $rw) : ?>
                                <option value=<?= $rw["marca"] ?>><?= $rw["marca"] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </form>
                </li>
            </ul>
            <ul>
                <li><a href="#">Login</a></li>
                <li><a href="index.php">Home</a></li>

            </ul>
        </nav>

        <div class="grid">
            <?php foreach ($prepare->fetchAll() as $row) : ?>
                <?= "<div>" ?>
                <article>
                    <header><a href=<?= "dettagli.php?cod=" . $row["Codice"] ?>><b><?= $row["Modello"] ?></b></a>
                    </header>
                    <?= $row["Marca"] ?>
                    <footer>Prezzo: <?= $row["Prezzo"] ?> &euro;</footer>
                </article>
                <?= "</div>" ?>
            <?php endforeach; ?>
        </div>
    </main>

    <script>
        function redirectToMarca(selectElement) {
            const selectedMarca = selectElement.value;
            if (selectedMarca) {
                window.location.href = `index.php?marca=${encodeURIComponent(selectedMarca)}`;
            }
        }
    </script>
</body>


</html>