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

// Redirect to login if not logged in
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];

// Super admin filter by admin_id
$filter_admin_id = null;
if ($role_id == 1 && isset($_GET['admin_id']) && is_numeric($_GET['admin_id'])) {
    $filter_admin_id = intval($_GET['admin_id']);
}

// Date filters
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to   = isset($_GET['date_to'])   ? $_GET['date_to']   : '';

// Build SQL
$where = [];
$params = [];
$types = "";

// Role conditions
if ($role_id == 1) {
    if ($filter_admin_id) {
        $where[] = "assigned_to = ?";
        $params[] = $filter_admin_id;
        $types .= "i";
    }
} else {
    $where[] = "assigned_to = ?";
    $params[] = $user_id;
    $types .= "i";
}

// Date range conditions
if (!empty($date_from)) {
    $where[] = "DATE(uploaded_at) >= ?";
    $params[] = $date_from;
    $types .= "s";
}
if (!empty($date_to)) {
    $where[] = "DATE(uploaded_at) <= ?";
    $params[] = $date_to;
    $types .= "s";
}

// Final query
$sql = "SELECT filename, uploaded_at FROM attendance_files";
if (!empty($where)) {
    $sql .= " WHERE " . implode(" AND ", $where);
}
$sql .= " ORDER BY uploaded_at DESC";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

// For super admin: get list of admins
$admins = [];
if ($role_id == 1) {
    $resAdmins = $conn->query("SELECT user_id, username FROM users WHERE role_id != 1 ORDER BY username");
    while ($row = $resAdmins->fetch_assoc()) {
        $admins[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Attendance Reports</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            background: #f4f6f9;
            margin: 0;
            padding: 0;
        }
        h2 {
            text-align: center;
            margin: 20px 0;
            color: #2c3e50;
        }
        .filter-container {
            width: 90%;
            margin: 10px auto;
            padding: 15px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
        }
        .filter-container form {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }
        .filter-container label {
            font-weight: bold;
            margin-right: 5px;
        }
        .filter-container input, 
        .filter-container select {
            padding: 6px 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        .filter-container button {
            background: #007BFF;
            color: #fff;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
        }
        .filter-container button:hover {
            background: #0056b3;
        }
        table {
            width: 90%;
            margin: 20px auto;
            border-collapse: collapse;
            background: #fff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        th, td {
            padding: 12px 15px;
            text-align: center;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #2c3e50;
            color: white;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .file-missing {
            color: red;
            font-weight: bold;
        }
        .file-download {
            color: #007BFF;
            text-decoration: none;
            font-weight: bold;
        }
        .file-download:hover {
            text-decoration: underline;
        }
        .logout {
            width: 90%;
            margin: 30px auto;
            text-align: right;
        }
        .logout a {
            display: inline-block;
            padding: 10px 20px;
            background-color: #e74c3c;
            color: #fff;
            text-decoration: none;
            border-radius: 5px;
            font-weight: bold;
        }
        .logout a:hover {
            background-color: #c0392b;
        }
    </style>
</head>
<body>

<div style="display:flex; justify-content:space-between; align-items:center; width:90%; margin:20px auto;">
    <h2>Attendance Reports</h2>
    <a href="logout.php" style="background:#e74c3c; color:#fff; padding:8px 16px; text-decoration:none; border-radius:5px; font-size:14px;">
        Logout
    </a>
</div>


<div class="filter-container">
    <form method="get" action="">
        <?php if ($role_id == 1): ?>
            <label for="admin_id">Admin:</label>
            <select name="admin_id" id="admin_id">
                <option value="">-- All Admins --</option>
                <?php foreach ($admins as $admin): ?>
                    <option value="<?= $admin['user_id'] ?>" <?= ($filter_admin_id == $admin['user_id']) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($admin['username']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        <?php endif; ?>

        <label for="date_from">From:</label>
        <input type="date" name="date_from" id="date_from" value="<?= htmlspecialchars($date_from) ?>">

        <label for="date_to">To:</label>
        <input type="date" name="date_to" id="date_to" value="<?= htmlspecialchars($date_to) ?>">

        <button type="submit">Filter</button>
    </form>
</div>

<?php if ($result && $result->num_rows > 0): ?>
    <table>
        <thead>
            <tr>
                <th>S.No</th>
                <th>Filename</th>
                <th>Uploaded At</th>
                <th>File</th>
            </tr>
        </thead>
        <tbody>
        <?php 
        $sno = 1; 
        while ($row = $result->fetch_assoc()):
            $originalFilename = $row['filename'];
            $parts = explode('_', $originalFilename, 2);
            $cleanFilename = isset($parts[1]) ? $parts[1] : $originalFilename;
            $formattedDate = date("d-m-Y", strtotime($row['uploaded_at']));
            $filePath = "uploads/" . $originalFilename;
            $fileExists = file_exists($filePath);
        ?>
            <tr>
                <td><?= $sno++ ?></td>
                <td><?= htmlspecialchars($cleanFilename) ?></td>
                <td><?= $formattedDate ?></td>
                <td>
                    <?php if ($fileExists): ?>
                        <a href="<?= $filePath ?>" target="_blank" class="file-download">Download File</a>
                    <?php else: ?>
                        <span class="file-missing">File Missing</span>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
<?php else: ?>
    <p style="text-align:center;">No reports available.</p>
<?php endif; ?>



</body>
</html>
