<?php
session_start();
include 'config.php';
include 'header.php';

if (!isset($_SESSION['username'])) {
    header("Location: index.php");
    exit();
}

$role = $_SESSION['role'];

// Fetch distinct values for filters
$titles_sql = "SELECT DISTINCT title FROM documents";
$titles_result = $conn->query($titles_sql);

$usernames_sql = "SELECT DISTINCT username FROM users";
$usernames_result = $conn->query($usernames_sql);

$statuses_sql = "SELECT DISTINCT status FROM document_status";
$statuses_result = $conn->query($statuses_sql);
?>

<div class="container mt-4">
    <h1 class="text-primary text-center">Welcome, <?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8'); ?></h1>

    <?php if ($role == 'Super Admin' || $role == 'Admin') { ?>
        <div class="card mt-4">
            <div class="card-header bg-info text-white">
                <h2>User Activity on Documents</h2>
            </div>
            <div class="card-body table-responsive">
                <table class="table table-bordered table-hover" id="activityTable">
                    <thead class="thead-dark">
                        <tr>
                            <th>
                                Document Title<br>
                                <select id="titleFilter" class="form-control" onchange="filterTable()">
                                    <option value="">All</option>
                                    <?php while ($row = $titles_result->fetch_assoc()) { ?>
                                        <option value="<?php echo htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8'); ?></option>
                                    <?php } ?>
                                </select>
                            </th>
                            <th>
                                Username<br>
                                <select id="usernameFilter" class="form-control" onchange="filterTable()">
                                    <option value="">All</option>
                                    <?php while ($row = $usernames_result->fetch_assoc()) { ?>
                                        <option value="<?php echo htmlspecialchars($row['username'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($row['username'], ENT_QUOTES, 'UTF-8'); ?></option>
                                    <?php } ?>
                                </select>
                            </th>
                            <th>
                                Status<br>
                                <select id="statusFilter" class="form-control" onchange="filterTable()">
                                    <option value="">All</option>
                                    <option value="Read">Read</option>
                                    <option value="Submitted">Submitted</option>
                                    <option value="Not Submitted">Not Submitted</option>
                                </select>
                            </th>
                            <th>Download</th>
                            <th>Acknowledge</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $activity_sql = "SELECT ds.document_id, d.title, u.username, ds.status
                                         FROM document_status ds
                                         JOIN documents d ON ds.document_id = d.id
                                         JOIN users u ON ds.employee_id = u.id";
                        $stmt = $conn->prepare($activity_sql);
                        $stmt->execute();
                        $activity_result = $stmt->get_result();

                        while ($activity_result && $activity_row = $activity_result->fetch_assoc()) {
                            $statusBadge = '';
                            switch ($activity_row['status']) {
                                case 'Read':
                                    $statusBadge = '<span class="badge bg-primary">Read</span>';
                                    break;
                                case 'Submitted':
                                    $statusBadge = '<span class="badge bg-success">Submitted</span>';
                                    break;
                                case 'Not Submitted':
                                    $statusBadge = '<span class="badge bg-danger">Not Submitted</span>';
                                    break;
                                default:
                                    $statusBadge = '<span class="badge bg-secondary">Unknown</span>';
                                    break;
                            }

                            echo "<tr>";
                            echo "<td>" . htmlspecialchars($activity_row['title'], ENT_QUOTES, 'UTF-8') . "</td>";
                            echo "<td>" . htmlspecialchars($activity_row['username'], ENT_QUOTES, 'UTF-8') . "</td>";
                            echo "<td>" . $statusBadge . "</td>";
                            echo "<td><a href='generate_pdf.php?document_id=" . $activity_row['document_id'] . "' class='btn btn-success btn-sm'>Download</a></td>";
                            echo "<td>
                                <a href='mailto:?subject=Document Acknowledgment&body=Please review the document titled: " . htmlspecialchars($activity_row['title'], ENT_QUOTES, 'UTF-8') . "' class='btn btn-primary btn-sm'>Email</a>
                                <a href='https://wa.me/?text=Please%20review%20the%20document:%20" . urlencode($activity_row['title']) . "' target='_blank' class='btn btn-success btn-sm'>WhatsApp</a>
                              </td>";
                            echo "</tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card mt-4">
            <div class="card-header bg-success text-white">
                <h2>User Count</h2>
            </div>
            <div class="card-body">
                <p>Total Users: 
                <?php
                $user_count_sql = "SELECT COUNT(*) as total_users FROM users";
                $user_count_result = $conn->query($user_count_sql);
                $user_count_row = $user_count_result->fetch_assoc();
                echo htmlspecialchars($user_count_row['total_users'], ENT_QUOTES, 'UTF-8');
                ?>
                </p>
            </div>
        </div>
    <?php } elseif ($role == 'Employee') { ?>
        <div class="card mt-4">
            <div class="card-header bg-warning text-dark">
                <h2>Your Documents</h2>
            </div>
            <div class="card-body">
                <ul class="list-group">
                    <?php
                    $sql = "SELECT * FROM documents";
                    $result = $conn->query($sql);
                    while ($result && $row = $result->fetch_assoc()) {
                        echo "<li class='list-group-item'>" . htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8') . " - 
                            <a href='view_document.php?id=" . $row['id'] . "' class='btn btn-primary btn-sm'>View</a></li>";
                    }
                    ?>
                </ul>
            </div>
        </div>
    <?php } ?>
</div>

<script>
function filterTable() {
    var titleFilter = document.getElementById("titleFilter").value.toUpperCase();
    var usernameFilter = document.getElementById("usernameFilter").value.toUpperCase();
    var statusFilter = document.getElementById("statusFilter").value.toUpperCase();
    var table = document.getElementById("activityTable");
    var tr = table.getElementsByTagName("tr");

    for (var i = 1; i < tr.length; i++) {
        var tdTitle = tr[i].getElementsByTagName("td")[0];
        var tdUsername = tr[i].getElementsByTagName("td")[1];
        var tdStatus = tr[i].getElementsByTagName("td")[2];
        
        if (tdTitle && tdUsername && tdStatus) {
            var titleValue = tdTitle.textContent || tdTitle.innerText;
            var usernameValue = tdUsername.textContent || tdUsername.innerText;
            var statusValue = tdStatus.textContent || tdStatus.innerText;

            if ((titleFilter === "" || titleValue.toUpperCase().indexOf(titleFilter) > -1) &&
                (usernameFilter === "" || usernameValue.toUpperCase().indexOf(usernameFilter) > -1) &&
                (statusFilter === "" || statusValue.toUpperCase().indexOf(statusFilter) > -1)) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}
</script>

<?php include 'footer.php'; ?>
