<?php
// Start session only if it's not already active
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Include necessary files
include('sidebar.php');
include('header.php');
include('db_connection.php'); // Include the database connection $conn

try {
    // Fetch mason data with associated team lead names
    $sql = "
        SELECT mason.id, mason.name AS mason_name, mason.email, teamlead.name AS teamlead_name, mason.created_at 
        FROM roll AS mason 
        LEFT JOIN roll AS teamlead ON mason.teamlead_id = teamlead.id
        WHERE mason.role = 'mason'
    ";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $masonRecords = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Mason Table</title>
</head>

<body>

    <!-- Table Start -->
    <div class="container-fluid pt-4 px-4">
        <div class="row g-4">
            <div class="col-12">
                <div class="bg-light rounded h-100 p-4">
                    <h6 class="mb-4">Mason Table</h6>
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th scope="col">#</th>
                                    <th scope="col">Mason Name</th>
                                    <th scope="col">Email</th>
                                    <th scope="col">Team Lead</th>
                                    <th scope="col">Created At</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if ($masonRecords) {
                                    foreach ($masonRecords as $index => $mason) {
                                        echo "<tr>";
                                        echo "<th scope='row'>" . ($index + 1) . "</th>";
                                        echo "<td>" . htmlspecialchars($mason['mason_name']) . "</td>";
                                        echo "<td>" . htmlspecialchars($mason['email']) . "</td>";
                                        echo "<td>" . htmlspecialchars($mason['teamlead_name']) . "</td>";
                                        echo "<td>" . htmlspecialchars($mason['created_at']) . "</td>";
                                        echo "</tr>";
                                    }
                                } else {
                                    echo "<tr><td colspan='5'>No mason records found</td></tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Table End -->

</body>

</html>