<?php
    include_once 'config/database.php';
    $USER = 'admin';
    $PASSWORD = 'ChinitaCiambella';

    // Request auth
    if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] !== $USER || $_SERVER['PHP_AUTH_PW'] !== $PASSWORD) {
        header('WWW-Authenticate: Basic realm="WeddingReport"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Authentication required';
        exit;
    }

    // Obtain report from database
    $database = new Database();
    $db = $database->getConnection();
    $query = "
        -- Report
        SELECT
            u.name,
            u.surname,
            (SELECT t.created FROM token t WHERE t.user_id = u.id ORDER BY t.created ASC LIMIT 1) AS started_app,
            CASE WHEN p.will_be_present IS NULL THEN '⏳' ELSE (
                CASE WHEN p.will_be_present THEN '✅' ELSE '❌' END
                ) END as will_be_present,
            p.created as when_user_answered,
            p.notes
        FROM `user` u
        LEFT JOIN presence p
            ON p.user_id = u.id
        GROUP BY u.id
        ORDER BY when_user_answered DESC, started_app DESC
    ";
    $stmt = $db->prepare($query);
    if (!$stmt->execute()) {
        echo("<html><body><h1>Error running query!</h1></body></html>");
        exit;
    }
?>

<html>
    <head>
        <title>Wedding report</title>
        <style>
            table, th, td {
                border: 1px solid black;
                border-collapse: collapse;
            }
            th {
                background-color: #96D4D4;
            }
        </style>
    </head>
    <body>
        <h1>Wedding report</h1>
        <table>
            <tr>
                <th>Name</th><th>Surname</th><th>Used app</th><th>Will be present</th><th>When answered</th><th>Notes</th>
            </tr>
            <?php
                // Draw table rows
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                    ?>
                        <tr>
                            <td><?php echo($row['name']); ?></td>
                            <td><?php echo($row['surname']); ?></td>
                            <td><?php echo($row['started_app']); ?></td>
                            <td style="text-align:center"><?php echo($row['will_be_present']); ?></td>
                            <td><?php echo($row['when_user_answered']); ?></td>
                            <td><?php echo($row['notes']); ?></td>
                        </tr>
                    <?php
                }
            ?>
        </table>
    </body>
</html>
