<?php
$db = mysqli_connect('localhost', 'root', '', 'szkolenia');
?>
<!doctype html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Szkolenia i kursy</title>
    <link rel="stylesheet" href="styl.css">
</head>
<body>
<header>
    <h1>SZKOLENIA</h1>
</header>
<main>
    <section id="section-1">
        <table>
            <tr>
                <th>Kurs</th>
                <th>Nazwa</th>
                <th>Cena</th>
            </tr>
            <?php
                $sql1 = "SELECT kod, nazwa, cena FROM kursy ORDER BY cena ASC;";
                $result1 = mysqli_query($db, $sql1);
                while ($row = mysqli_fetch_assoc($result1)) {
                    echo "<tr><td><img src='{$row['kod']}.jpg' alt='kurs'></td><td>{$row['nazwa']}</td><td>{$row['cena']}</td></tr>";
                }
            ?>
        </table>
    </section>
    <section id="section-2">
        <h2>Zapisy na kursy</h2>
        <form action="" method="post" >
            <label for="name">Imię</label>
            <input type="text" name="name" id="name">
            <label for="surname">Nazwisko</label>
            <input type="text" name="surname" id="surname">
            <label for="age">Wiek</label>
            <input type="number" name="age" id="age">
            <label for="type">Rodzaj kursu</label>
            <select name="type" id="type">
            <?php
                $sql2 = "SELECT nazwa FROM kursy";
                $result2 = mysqli_query($db, $sql2);
                while ($row = mysqli_fetch_assoc($result2)) {
                    echo "<option value='{$row['nazwa']} '>{$row['nazwa']}</option>'";
                }
            ?>
            </select>
            <button type="submit">Dodaj dane</button>
        </form>
        <?php
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if (!isset($_POST['name']) || !isset($_POST['surname']) || !isset($_POST['age'])) {
                echo "<p>Wprowadź wszystkie dane</p>";
            }
            $name = htmlspecialchars($_POST['name']);
            $surname = htmlspecialchars($_POST['surname']);
            $age = (int)htmlspecialchars($_POST['age']);
            $kurs = htmlspecialchars($_POST['type']);
            $sql3 = "INSERT INTO uczestnicy (imie, nazwisko, wiek) VALUES (?,?,?);";
            $stmt = mysqli_prepare($db, $sql3);
            mysqli_stmt_bind_param($stmt, 'ssi', $name, $surname, $age);
            mysqli_stmt_execute($stmt);

            echo "Dane uczestnika $name $surname zostały dodane";
        }
        ?>
    </section>
</main>
<footer>
    Stronę wykonał: Jakub Grzegorczyk 3p/1
</footer>
</body>
</html>
<?php
mysqli_close($db);
?>