<?php
require_once '../config/db.php';
checkAuth();
checkRole('admin');

$f_date = isset($_GET['date']) ? $_GET['date'] : '';
$f_user = isset($_GET['user_id']) ? $_GET['user_id'] : '';

$where = "WHERE 1";
if ($f_date) $where .= " AND r.report_date = '$f_date'";
if ($f_user) $where .= " AND r.user_id = '$f_user'";

$sql = "SELECT r.*, u.name, u.team FROM daily_reports r JOIN users u ON r.user_id = u.id $where ORDER BY r.report_date DESC LIMIT 50";
$reports = mysqli_query($conn, $sql);
$users = mysqli_query($conn, "SELECT id, name FROM users WHERE role='employee'");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Admin Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-dark bg-dark mb-4">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Admin Panel</a>
    <a class="nav-link text-white" href="../employee/logout.php">Logout</a>
  </div>
</nav>
<div class="container">
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <input type="date" name="date" class="form-control" value="<?= $f_date ?>">
                </div>
                <div class="col-md-3">
                    <select name="user_id" class="form-select">
                        <option value="">All Employees</option>
                        <?php while($u = mysqli_fetch_assoc($users)): ?>
                        <option value="<?= $u['id'] ?>" <?= $f_user == $u['id'] ? 'selected':'' ?>><?= $u['name'] ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">Filter</button>
                </div>
            </form>
        </div>
    </div>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Date</th><th>Employee</th><th>Team</th><th>Shift</th><th>Hours</th><th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php while($row = mysqli_fetch_assoc($reports)): ?>
            <tr>
                <td><?= $row['report_date'] ?></td>
                <td><?= $row['name'] ?></td>
                <td><?= $row['team'] ?></td>
                <td><?= ucfirst($row['shift']) ?></td>
                <td><?= $row['total_worked_hours'] ?></td>
                <td>
                    <a href="../employee/export_tasks.php?date=<?= $row['report_date'] ?>&override_user=<?= $row['user_id'] ?>" class="btn btn-sm btn-outline-success">CSV</a>
                </td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>
</body>
</html>
