<?php
session_start();
include '../db_config.php';
include '../functions.php';

check_login();
check_role('admin');

$msg = '';

// Handle Deletion
if(isset($_GET['del'])) {
    $del = sanitize_input($_GET['del']);
    // Optional: Check if exists first or just delete
    $stmt = $conn->prepare("DELETE FROM employee_login WHERE nic=?");
    $stmt->bind_param("s", $del);
    if($stmt->execute()) {
        $msg = "Employee account ($del) has been deleted.";
    } else {
        $msg = "Error deleting employee.";
    }
    $stmt->close();
}

if(isset($_POST['reset_password'])) {
    $nic = sanitize_input($_POST['id']);
    $pass = password_hash($_POST['new_password'], PASSWORD_DEFAULT);
    $stmt = $conn->prepare("UPDATE employee_login SET password=? WHERE nic=?");
    $stmt->bind_param("ss", $pass, $nic);
    if($stmt->execute()) {
         $msg = "Password reset successfully for $nic.";
    } else {
         $msg = "Error updating password.";
    }
    $stmt->close();
}

// Fetch Employees
$res = $conn->query("SELECT u.nic, u.nic as username, ed.full_name, ed.status, ed.district, ed.job_category, ed.profile_pic FROM employee_login u LEFT JOIN employee_details ed ON u.nic=ed.employee_nic WHERE u.role='employee' ORDER BY u.created_at DESC");

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Workers | Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <style> 
        body { font-family: 'Inter', sans-serif; } 
        .glass-panel {
            background: rgba(30, 41, 59, 0.4);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
    </style>
</head>
<body class="bg-slate-950 min-h-screen text-slate-200 selection:bg-indigo-500 selection:text-white">

    <!-- Navbar -->
    <nav class="bg-slate-900 border-b border-slate-800 sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-20 items-center">
                <a href="<?= BASE_URL ?>/index.php" class="text-2xl font-bold italic tracking-tighter text-white">
                    Work For <span class="text-indigo-400">Sri Lanka</span>
                    <span class="text-xs font-normal text-white bg-indigo-600 px-2 py-0.5 rounded ml-2 align-middle border border-indigo-500/50">Admin Panel</span>
                </a>
                <div class="flex items-center gap-6">
                    <span class="text-sm font-medium text-slate-400 hidden md:inline">Logged in as: <span class="text-indigo-400 font-mono"><?=$_SESSION['username']?></span></span>
                    <a href="../logout.php" class="text-slate-400 hover:text-red-400 font-medium transition text-sm flex items-center">
                        <i data-lucide="log-out" class="w-4 h-4 mr-2"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- Header Section -->
    <div class="relative bg-slate-900 py-10 px-4 border-b border-slate-800">
        <div class="absolute top-0 right-0 w-[500px] h-[500px] bg-indigo-600/10 rounded-full blur-[100px] -mt-20 -mr-20 pointer-events-none"></div>
        
        <div class="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center gap-4 relative z-10">
            <div>
                <h1 class="text-3xl font-bold mb-2 text-white">Manage Workforce</h1>
                <p class="text-slate-400">View and manage all registered worker accounts.</p>
            </div>
            <a href="dashboard.php" class="bg-slate-800 hover:bg-slate-700 text-white px-5 py-2.5 rounded-xl font-bold transition flex items-center border border-slate-700 hover:border-indigo-500 hover:text-indigo-400 shadow-sm text-sm group">
                <i data-lucide="arrow-left" class="w-4 h-4 mr-2 group-hover:-translate-x-1 transition-transform"></i> Back to Dashboard
            </a>
        </div>
    </div>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto px-4 pb-20 pt-8">
        
        <?php if($msg): ?>
             <div class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-6 py-4 rounded-xl mb-6 flex items-center shadow-sm animate-fade-in-down">
                <i data-lucide="check-circle" class="w-5 h-5 mr-3 flex-shrink-0"></i>
                <span class="font-bold mr-2">Success!</span> <?=$msg?>
            </div>
        <?php endif; ?>

        <div class="glass-panel rounded-3xl shadow-xl overflow-hidden">
            <!-- Table Header & Search -->
            <div class="p-6 border-b border-slate-700/50 bg-slate-800/30 flex flex-col md:flex-row justify-between items-center gap-4">
                <div class="flex items-center gap-4 flex-wrap">
                    <h2 class="text-lg font-bold text-white flex items-center">
                        <i data-lucide="users" class="w-5 h-5 mr-2 text-indigo-400"></i> Registered Workers
                        <span class="ml-3 bg-indigo-500/10 text-indigo-400 text-xs font-bold px-2.5 py-1 rounded-full border border-indigo-500/20"><?=$res->num_rows?></span>
                    </h2>
                    <a href="export_employees.php" class="bg-emerald-600/20 hover:bg-emerald-600/30 text-emerald-400 border border-emerald-600/30 text-xs font-bold px-4 py-2 rounded-xl transition flex items-center">
                        <i data-lucide="download" class="w-3.5 h-3.5 mr-2"></i> Excel
                    </a>
                    <button onclick="downloadPDF()" class="bg-red-500/20 hover:bg-red-500/30 text-red-400 border border-red-500/30 text-xs font-bold px-4 py-2 rounded-xl transition flex items-center">
                        <i data-lucide="file-text" class="w-3.5 h-3.5 mr-2"></i> PDF
                    </button>
                </div>
                
                <div class="relative w-full md:w-64">
                    <span class="absolute left-3 top-3 text-slate-500"><i data-lucide="search" class="w-4 h-4"></i></span>
                    <input type="text" id="searchInput" onkeyup="filterTable()" placeholder="Search per name or NIC..." class="w-full pl-10 pr-4 py-2.5 bg-slate-900/50 border border-slate-700 rounded-xl text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition outline-none text-slate-200 placeholder-slate-600">
                </div>
            </div>

            <!-- Table -->
            <div class="overflow-x-auto">
                <?php if($res->num_rows > 0): ?>
                <table class="w-full text-left text-sm text-slate-400" id="employeeTable">
                    <thead class="bg-slate-800/50 text-slate-400 uppercase font-semibold text-xs tracking-wider">
                        <tr>
                            <th class="px-6 py-4">Worker Profile</th>
                            <th class="px-6 py-4">NIC (Username)</th>
                            <th class="px-6 py-4">Job Info</th>
                            <th class="px-6 py-4">Status</th>
                            <th class="px-6 py-4 text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-700/50">
                        <?php while($r = $res->fetch_assoc()): ?>
                        <tr class="hover:bg-slate-800/30 transition group">
                            <td class="px-6 py-4">
                                <div class="flex items-center">
                                    <img src="../uploads/profiles/<?=$r['profile_pic'] ? $r['profile_pic'] : 'default.png'?>" class="h-10 w-10 rounded-full object-cover border-2 border-slate-600 shadow-sm mr-3">
                                    <div>
                                        <div class="font-bold text-white"><?=$r['full_name'] ? $r['full_name'] : '<span class="text-slate-600 italic">No Name</span>'?></div>
                                        <div class="text-xs text-slate-500"><?=$r['district'] ? $r['district'] : 'Unknown District'?></div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 font-mono text-indigo-300/80 text-xs"><?=$r['username']?></td>
                            <td class="px-6 py-4">
                                <span class="bg-slate-800 text-slate-300 border border-slate-700 px-2 py-1 rounded text-xs font-semibold">
                                    <?=$r['job_category'] ? $r['job_category'] : 'Unassigned'?>
                                </span>
                            </td>
                            <td class="px-6 py-4">
                                <span class="px-2.5 py-1 rounded-full text-xs font-bold border
                                    <?= $r['status'] == 'Approved' ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20' : 
                                       ($r['status'] == 'Rejected' ? 'bg-red-500/10 text-red-400 border-red-500/20' : 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20') ?>">
                                    <?=$r['status'] ? $r['status'] : 'Pending'?>
                                </span>
                            </td>
                            <td class="px-6 py-4 text-right">
                                <div class="flex items-center justify-end gap-2 opacity-60 group-hover:opacity-100 transition-opacity">
                                    <a href="../worker_profile.php?id=<?=encrypt_id($r['username'])?>" target="_blank" class="bg-slate-700 hover:bg-slate-600 text-slate-300 p-2 rounded-lg transition" title="View Profile">
                                        <i data-lucide="eye" class="w-4 h-4"></i>
                                    </a>
                                    <a href="edit_employee.php?id=<?=$r['username']?>" class="bg-indigo-500/10 hover:bg-indigo-500/20 text-indigo-400 p-2 rounded-lg transition border border-indigo-500/20" title="Edit Details">
                                        <i data-lucide="edit" class="w-4 h-4"></i>
                                    </a>
                                     <button onclick="resetPass('<?=$r['username']?>', '<?=$r['full_name']?>')" class="bg-yellow-500/10 hover:bg-yellow-500/20 text-yellow-400 p-2 rounded-lg transition border border-yellow-500/20" title="Reset Password">
                                        <i data-lucide="key" class="w-4 h-4"></i>
                                    </button>
                                    <a href="?del=<?=$r['username']?>" onclick="return confirm('Are you sure you want to delete this worker account permanently?');" class="bg-red-500/10 hover:bg-red-500/20 text-red-400 p-2 rounded-lg transition border border-red-500/20" title="Delete Account">
                                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
                <?php else: ?>
                    <div class="p-12 text-center text-slate-500 flex flex-col items-center">
                        <div class="bg-slate-800 p-4 rounded-full mb-3 border border-slate-700">
                            <i data-lucide="users" class="w-8 h-8 text-slate-600"></i>
                        </div>
                        <p>No registered workers found in the system.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Simple Footer -->
    <footer class="bg-slate-900 border-t border-slate-800 py-8 text-center text-slate-500 text-sm mt-12">
        <p>&copy; <?=date('Y')?> Work For Sri Lanka. All rights reserved.</p>
    </footer>

    <form id="resetForm" method="post" style="display:none;">
        <input type="hidden" name="reset_password" value="1">
        <input type="hidden" name="id" id="resetId">
        <input type="hidden" name="new_password" id="resetPassInput">
    </form>

    <!-- jsPDF Libraries -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.29/jspdf.plugin.autotable.min.js"></script>

    <script>
        lucide.createIcons();
        window.jsPDF = window.jspdf.jsPDF;

        function downloadPDF() {
            const doc = new jsPDF();
            
            // Add Title
            doc.setFontSize(18);
            doc.text("Work For Sri Lanka - Worker List", 14, 22);
            doc.setFontSize(11);
            doc.text("Generated on: " + new Date().toLocaleDateString(), 14, 30);

            // AutoTable
            doc.autoTable({
                html: '#employeeTable',
                startY: 35,
                theme: 'grid',
                styles: { fontSize: 8 },
                columns: [
                    { header: 'Profile', dataKey: 'Profile' },
                    { header: 'NIC', dataKey: 'NIC' },
                    { header: 'Job Info', dataKey: 'Job Info' },
                    { header: 'Status', dataKey: 'Status' }
                ],
                didParseCell: function(data) {
                    // Clean up text content if needed
                    if (data.section === 'body') {
                         
                    }
                }
            });

            doc.save('workers_list.pdf');
        }

        function filterTable() {
            var input, filter, table, tr, td, i, txtValue;
            input = document.getElementById("searchInput");
            filter = input.value.toUpperCase();
            table = document.getElementById("employeeTable");
            tr = table.getElementsByTagName("tr");
            for (i = 0; i < tr.length; i++) {
                // Check Name (0) and NIC (1)
                var tdName = tr[i].getElementsByTagName("td")[0];
                var tdNic = tr[i].getElementsByTagName("td")[1];
                if (tdName || tdNic) {
                    var txtName = tdName.textContent || tdName.innerText;
                    var txtNic = tdNic.textContent || tdNic.innerText;
                    if (txtName.toUpperCase().indexOf(filter) > -1 || txtNic.toUpperCase().indexOf(filter) > -1) {
                        tr[i].style.display = "";
                    } else {
                        tr[i].style.display = "none";
                    }
                }
            }
        }

        function resetPass(id, name) {
            let newPass = prompt("Enter NEW PASSWORD for " + name + " (" + id + "):");
            if(newPass != null && newPass != "") {
                document.getElementById('resetId').value = id;
                document.getElementById('resetPassInput').value = newPass;
                document.getElementById('resetForm').submit();
            }
        }
    </script>
</body>
</html>
