<?php
// Start session so $_SESSION works
include '../config.php';
include 'common/header.php';

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// If role_id is not set, you can redirect to login
if (!isset($_SESSION['role_id'])) {
    header("Location: index.php");
    exit();
}

$role_id = $_SESSION['role_id'];

// Handle file upload (only if super admin)
if ($role_id == 1 && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['attendance'])) {
    $assigned_to = intval($_POST['assigned_to']); // Admin ID

    $targetDir = __DIR__ . "/uploads/";
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    $fileName = time() . "_" . basename($_FILES["attendance"]["name"]);
    $targetFile = $targetDir . $fileName;

    if (move_uploaded_file($_FILES["attendance"]["tmp_name"], $targetFile)) {
        // Insert into DB
        $stmt = $conn->prepare("INSERT INTO attendance_files (filename, uploaded_by, assigned_to) VALUES (?, ?, ?)");
        $stmt->bind_param("sii", $fileName, $user_id, $assigned_to);
        $stmt->execute();
        echo "<p class='text-green-600 font-semibold mb-4'>File uploaded successfully!</p>";
    } else {
        echo "<p class='text-red-600 font-semibold mb-4'>Error uploading file.</p>";
    }
}

// Get total employee count
$total_query = mysqli_query($conn, "SELECT COUNT(*) as total FROM register");
$total_result = mysqli_fetch_assoc($total_query);
$total_employees = $total_result['total'];

// Fetch uploaded files
if ($role_id == 1) {
    // Super admin sees all files
    $files = $conn->query("SELECT af.*, u.username AS assigned_admin 
                           FROM attendance_files af
                           LEFT JOIN user u ON af.assigned_to = u.id
                           ORDER BY af.id DESC");
} else {
    // Admin sees only files assigned to them
    $stmt = $conn->prepare("SELECT af.*, u.username AS assigned_admin 
                            FROM attendance_files af
                            LEFT JOIN user u ON af.assigned_to = u.id
                            WHERE af.assigned_to = ?
                            ORDER BY af.id DESC");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $files = $stmt->get_result();
}
?>

<!-- STATS CARDS -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
    <div class="bg-gradient-to-br from-purple-500 to-purple-600 text-white p-6 rounded-lg shadow-lg">
        <div class="flex items-center">
            <i class="fas fa-users text-4xl opacity-75"></i>
            <div class="ml-4">
                <p class="text-lg font-semibold">Total Employees</p>
                <p class="text-3xl font-bold"><?= $total_employees ?></p>
            </div>
        </div>
    </div>
</div>

<!-- QUICK ACTIONS -->
<div class="mt-8 bg-white p-6 rounded-lg shadow-md">
    <h2 class="text-xl font-bold text-gray-800 mb-4">Quick Actions</h2>
    <div class="flex flex-wrap gap-4">
        <a href="edit.php" class="bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg shadow hover:bg-blue-700 transition flex items-center">
            <i class="fas fa-plus mr-2"></i>Add Employee
        </a>
        <a href="excel.php" class="bg-gray-600 text-white font-semibold py-2 px-4 rounded-lg shadow hover:bg-gray-700 transition flex items-center">
            <i class="fas fa-list-alt mr-2"></i>Download Excel File
        </a>
    </div>

    <?php if ($role_id == 1): ?>
        <!-- Upload Form for Super Admin -->
        <div class="mt-6 border-t pt-4">
            <h3 class="text-lg font-semibold text-gray-700 mb-2">Upload Attendance File</h3>
            <form method="post" enctype="multipart/form-data" class="flex flex-col gap-3">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Assign to Admin:</label>
                    <select name="assigned_to" class="border rounded-lg px-3 py-2 w-full" required>
                        <?php
                        $admins = $conn->query("SELECT id, username FROM user WHERE role_id = 2");
                        while ($admin = $admins->fetch_assoc()) {
                            echo "<option value='{$admin['id']}'>{$admin['username']}</option>";
                        }
                        ?>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Select File:</label>
                    <input type="file" name="attendance" class="border rounded-lg px-3 py-2 w-full" required>
                </div>
                <button type="submit" class="bg-green-600 text-white font-semibold py-2 px-4 rounded-lg hover:bg-green-700 transition">
                    Upload File
                </button>
            </form>
        </div>
    <?php endif; ?>
</div>

<!-- FILE LIST -->
 <?php if ($role_id == 1): ?>
<div class="mt-8 bg-white p-6 rounded-lg shadow-md">
    <h2 class="text-xl font-bold text-gray-800 mb-4">Assigned Files</h2>
    <?php if ($files->num_rows > 0): ?>
        <table class="w-full border-collapse border border-gray-300">
            <thead>
                <tr class="bg-gray-200">
                    <th class="border border-gray-300 px-4 py-2">Filename</th>
                    <th class="border border-gray-300 px-4 py-2">Assigned To</th>
                    <th class="border border-gray-300 px-4 py-2">Download</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($file = $files->fetch_assoc()): ?>
                    <tr>
                        <td class="border border-gray-300 px-4 py-2"><?= htmlspecialchars($file['filename']) ?></td>
                        <td class="border border-gray-300 px-4 py-2"><?= htmlspecialchars($file['assigned_admin']) ?></td>
                        <td class="border border-gray-300 px-4 py-2">
                            <a href="uploads/<?= urlencode($file['filename']) ?>" class="text-blue-600 hover:underline" download>Download</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    <?php else: ?>
        <p class="text-gray-500">No files assigned to you.</p>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php include 'common/bottom.php'; ?>
