<?php include 'header.php'; ?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Letter Records</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/remixicon@4.2.0/fonts/remixicon.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Plus Jakarta Sans', 'sans-serif']
                    },
                    colors: {
                        brand: {
                            50: '#eef2ff',
                            100: '#e0e7ff',
                            200: '#c7d2fe',
                            400: '#818cf8',
                            500: '#6366f1',
                            600: '#4f46e5',
                            700: '#4338ca'
                        }
                    }
                }
            }
        }
    </script>
    <style>
        * {
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        .badge {
            display: inline-flex;
            align-items: center;
            padding: 3px 10px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: 600;
            white-space: nowrap;
        }

        .act-btn {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all .15s;
            border: none;
            font-size: 14px;
        }

        .toast {
            position: fixed;
            bottom: 24px;
            right: 24px;
            z-index: 9999;
            padding: 12px 20px;
            border-radius: 12px;
            font-size: 13px;
            font-weight: 500;
            color: #fff;
            opacity: 0;
            pointer-events: none;
            transition: opacity .3s, transform .3s;
            transform: translateY(10px);
        }

        .toast.show {
            opacity: 1;
            transform: translateY(0);
        }

        .type-chip {
            cursor: pointer;
            user-select: none;
            transition: all .2s;
        }

        .type-chip.selected {
            background: #eef2ff !important;
            color: #4f46e5 !important;
            border-color: #c7d2fe !important;
        }

        input[type=date]::-webkit-calendar-picker-indicator {
            opacity: 0.5;
        }

        @media (max-width:640px) {
            .stat-scroll {
                display: flex;
                overflow-x: auto;
                gap: 10px;
                padding-bottom: 4px;
                -webkit-overflow-scrolling: touch;
                scrollbar-width: none;
            }

            .stat-scroll::-webkit-scrollbar {
                display: none;
            }

            .stat-card-wrap {
                min-width: 140px;
                flex-shrink: 0;
            }
        }

        .table-row-hover:hover td {
            background: #f9fafb;
        }

        /* Letter card selection */
        .letter-card {
            cursor: pointer;
            transition: all .2s;
            user-select: none;
        }

        .letter-card:hover {
            transform: translateY(-2px);
        }

        .letter-card.active {
            outline: 2.5px solid #6366f1;
            outline-offset: 2px;
        }

        .letter-card.active .card-check {
            display: flex !important;
        }

        /* Custom dropdown */
        .custom-dropdown {
            position: relative;
        }

        .dropdown-list {
            position: absolute;
            top: calc(100% + 6px);
            left: 0;
            right: 0;
            background: #fff;
            border: 1px solid #e5e7eb;
            border-radius: 14px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, .10);
            z-index: 200;
            max-height: 220px;
            overflow-y: auto;
            display: none;
        }

        .dropdown-list.open {
            display: block;
        }

        .dropdown-list::-webkit-scrollbar {
            width: 5px;
        }

        .dropdown-list::-webkit-scrollbar-thumb {
            background: #c7d2fe;
            border-radius: 20px;
        }

        .dropdown-item {
            padding: 10px 14px;
            font-size: 13px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: background .12s;
        }

        .dropdown-item:hover {
            background: #f5f3ff;
        }

        .dropdown-item.selected-item {
            background: #eef2ff;
            color: #4f46e5;
            font-weight: 600;
        }

.dropdown-input{
    width:100%;
    height:42px;
    padding:0 38px 0 40px;
    border:1px solid #e5e7eb;
    border-radius:12px;
    background:#f9fafb;
    font-size:13px;
    color:#374151;
    outline:none;
    transition:all .2s;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
}
.custom-dropdown{
    width:100%;
}

.custom-dropdown input{
    min-width:0;
}
        .dropdown-input:focus {
            border-color: #818cf8;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, .12);
            background: #fff;
        }

        /* Filter sidebar */
        .filter-chip {
            cursor: pointer;
            user-select: none;
            transition: all .15s;
        }

        .filter-chip.selected {
            background: #eef2ff !important;
            color: #4f46e5 !important;
            border-color: #c7d2fe !important;
        }
    </style>
</head>

<body class="bg-gray-50 min-h-screen">

    <!-- Overlay -->
    <div id="overlay" class="fixed inset-0 bg-black/30 z-40 hidden" onclick="closeSidebar()"></div>

    <!-- ========== MAIN WRAPPER ========== -->
    <div class="max-w-[1400px] mx-auto px-3 sm:px-4 lg:px-6 py-4 lg:py-6">

        <!-- ===== HEADER ===== -->
        <div class="bg-white rounded-2xl border border-gray-200 px-4 sm:px-5 py-4 mb-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div class="flex-1 min-w-0">
                <h1 class="text-xl sm:text-2xl font-bold text-gray-800">HR Letter Records</h1>
                <p class="text-xs sm:text-sm text-gray-400 mt-0.5">Manage all HR letters from here</p>
            </div>
            <div class="flex flex-wrap items-center gap-2">
                <div class="relative flex-1 sm:flex-none">
                    <input id="searchInput" type="text" placeholder="Search employee..."
                        oninput="filterTable()"
                        class="w-full sm:w-52 h-10 pl-9 pr-3 rounded-xl border border-gray-200 bg-gray-50 text-sm text-gray-700 placeholder:text-gray-400 focus:ring-2 focus:ring-brand-400 focus:border-brand-400 outline-none transition">
                    <i class="ri-search-line absolute left-3 inset-y-0 flex items-center text-gray-400 text-base"></i>
                </div>
                <button onclick="openSidebar()"
                    class="h-10 px-4 rounded-xl border border-gray-200 bg-white hover:bg-brand-50 hover:border-brand-200 hover:text-brand-600 text-gray-600 text-sm font-medium flex items-center gap-1.5 transition">
                    <i class="ri-filter-3-line text-base"></i><span class="hidden sm:inline">Filter</span>
                </button>
            </div>
        </div>

        <!-- ===== GENERATE LETTER SECTION ===== -->
        <div class="bg-white rounded-2xl border border-gray-200 p-4 sm:p-5 mb-4">
            <div class="flex flex-col lg:flex-row lg:items-center gap-4 mb-4">
                <div class="w-8 h-8 rounded-lg bg-brand-50 text-brand-500 flex items-center justify-center flex-shrink-0">
                    <i class="ri-file-add-line text-lg"></i>
                </div>
                <div class="flex-1 min-w-0">
                    <h2 class="text-sm font-bold text-gray-800">Generate Letter</h2>
                    <p class="text-xs text-gray-400">Select an employee, choose a letter type and click Generate</p>
                </div>
                
                
                                <!-- Employee Dropdown -->
                <div class="w-full sm:w-[280px] lg:w-72 flex-shrink-0">
                    <div class="custom-dropdown" id="empDropdownWrap">
                        <div class="relative">
                            <i class="ri-user-3-line absolute left-3 inset-y-0 flex items-center text-gray-400 text-sm z-10"></i>
                            <input id="empSearchInput" type="text" class="dropdown-input" placeholder="Search employee..."
                                autocomplete="off"
                                onfocus="openDropdown()" oninput="filterDropdown(this.value)" onclick="openDropdown()">
                            <i class="ri-arrow-down-s-line absolute right-3 inset-y-0 flex items-center text-gray-400 pointer-events-none" id="dropArrow"></i>
                        </div>
                        <div class="dropdown-list" id="empDropdownList"></div>
                    </div>
                    <!-- Selected employee chip -->
                    <div id="selectedEmpChip" class="hidden mt-2 inline-flex items-center gap-2 bg-brand-50 text-brand-600 border border-brand-200 px-3 py-1.5 rounded-full text-xs font-semibold">
                        <div id="chipAvatar" class="w-5 h-5 rounded-full bg-brand-200 text-brand-700 text-[9px] font-bold flex items-center justify-center"></div>
                        <span id="chipName"></span>
                        <button onclick="clearEmployee()" class="ml-1 text-brand-400 hover:text-brand-700 transition"><i class="ri-close-line text-xs"></i></button>
                    </div>
                </div>
                
            </div>

            <div class="flex flex-col lg:flex-row gap-4 items-start lg:items-end">



                <!-- Letter Type Cards -->
                <div class="flex-1 w-full">
                    <label class="block text-xs font-semibold text-gray-500 mb-2">
                        <i class="ri-file-list-3-line mr-1"></i>Select Letter Type <span class="text-red-400">*</span>
                    </label>
                    <div class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-2" id="letterTypeCards">

                        <div class="letter-card relative bg-white border border-gray-200 rounded-xl p-2.5 flex flex-col items-center gap-1.5 hover:border-blue-300 hover:bg-blue-50/50"
                            onclick="selectLetterType(this,'Offer Letter')">
                            <div class="card-check hidden absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-brand-500 text-white text-[9px] items-center justify-center"><i class="ri-check-line"></i></div>
                            <div class="w-8 h-8 rounded-lg bg-blue-50 text-blue-600 flex items-center justify-center"><i class="ri-file-text-line text-base"></i></div>
                            <span class="text-[10px] font-semibold text-gray-600 text-center leading-tight">Offer Letter</span>
                        </div>

                        <div class="letter-card relative bg-white border border-gray-200 rounded-xl p-2.5 flex flex-col items-center gap-1.5 hover:border-purple-300 hover:bg-purple-50/50"
                            onclick="selectLetterType(this,'Appointment Letter')">
                            <div class="card-check hidden absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-brand-500 text-white text-[9px] items-center justify-center"><i class="ri-check-line"></i></div>
                            <div class="w-8 h-8 rounded-lg bg-purple-50 text-purple-600 flex items-center justify-center"><i class="ri-award-line text-base"></i></div>
                            <span class="text-[10px] font-semibold text-gray-600 text-center leading-tight">Appointment Letter</span>
                        </div>

                        <div class="letter-card relative bg-white border border-gray-200 rounded-xl p-2.5 flex flex-col items-center gap-1.5 hover:border-green-300 hover:bg-green-50/50"
                            onclick="selectLetterType(this,'Appraisal Letter')">
                            <div class="card-check hidden absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-brand-500 text-white text-[9px] items-center justify-center"><i class="ri-check-line"></i></div>
                            <div class="w-8 h-8 rounded-lg bg-green-50 text-green-600 flex items-center justify-center"><i class="ri-line-chart-line text-base"></i></div>
                            <span class="text-[10px] font-semibold text-gray-600 text-center leading-tight">Appraisal Letter</span>
                        </div>

                        <div class="letter-card relative bg-white border border-gray-200 rounded-xl p-2.5 flex flex-col items-center gap-1.5 hover:border-teal-300 hover:bg-teal-50/50"
                            onclick="selectLetterType(this,'Experience Letter')">
                            <div class="card-check hidden absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-brand-500 text-white text-[9px] items-center justify-center"><i class="ri-check-line"></i></div>
                            <div class="w-8 h-8 rounded-lg bg-teal-50 text-teal-600 flex items-center justify-center"><i class="ri-award-line text-base"></i></div>
                            <span class="text-[10px] font-semibold text-gray-600 text-center leading-tight">Experience Letter</span>
                        </div>

                        <div class="letter-card relative bg-white border border-gray-200 rounded-xl p-2.5 flex flex-col items-center gap-1.5 hover:border-amber-300 hover:bg-amber-50/50"
                            onclick="selectLetterType(this,'No Due Certificate')">
                            <div class="card-check hidden absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-brand-500 text-white text-[9px] items-center justify-center"><i class="ri-check-line"></i></div>
                            <div class="w-8 h-8 rounded-lg bg-amber-50 text-amber-600 flex items-center justify-center"><i class="ri-shield-check-line text-base"></i></div>
                            <span class="text-[10px] font-semibold text-gray-600 text-center leading-tight">No Due Cert.</span>
                        </div>

                        <div class="letter-card relative bg-white border border-gray-200 rounded-xl p-2.5 flex flex-col items-center gap-1.5 hover:border-red-300 hover:bg-red-50/50"
                            onclick="selectLetterType(this,'Full and Final Settlement')">
                            <div class="card-check hidden absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-brand-500 text-white text-[9px] items-center justify-center"><i class="ri-check-line"></i></div>
                            <div class="w-8 h-8 rounded-lg bg-red-50 text-red-500 flex items-center justify-center"><i class="ri-money-dollar-circle-line text-base"></i></div>
                            <span class="text-[10px] font-semibold text-gray-600 text-center leading-tight">Full &amp; Final</span>
                        </div>

                        <div class="letter-card relative bg-white border border-gray-200 rounded-xl p-2.5 flex flex-col items-center gap-1.5 hover:border-pink-300 hover:bg-pink-50/50"
                            onclick="selectLetterType(this,'Rules and Regulations')">
                            <div class="card-check hidden absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-brand-500 text-white text-[9px] items-center justify-center"><i class="ri-check-line"></i></div>
                            <div class="w-8 h-8 rounded-lg bg-pink-50 text-pink-600 flex items-center justify-center"><i class="ri-book-open-line text-base"></i></div>
                            <span class="text-[10px] font-semibold text-gray-600 text-center leading-tight">Rules &amp; Regs</span>
                        </div>

                    </div>
                </div>

                <!-- Generate Button -->
                <div class="flex-shrink-0 w-full lg:w-auto">
                    <button onclick="generateLetter()"
                        id="generateBtn"
                        class="w-full lg:w-auto h-11 px-6 rounded-xl bg-gradient-to-r from-brand-500 to-brand-600 hover:from-brand-600 hover:to-brand-700 text-white text-sm font-bold flex items-center justify-center gap-2 shadow-md hover:shadow-brand-200 hover:shadow-lg transition-all duration-200 opacity-60 cursor-not-allowed"
                        disabled>
                        <i class="ri-file-add-line text-base"></i>
                        Generate
                    </button>
                </div>

            </div>
        </div>

        <!-- ===== STAT CARDS ===== -->
        <div class="hidden sm:grid grid-cols-2 md:grid-cols-4 xl:grid-cols-7 gap-3 mb-4">
            <div class="bg-white border border-gray-200 rounded-2xl p-3.5 flex items-center gap-3 hover:shadow-sm transition">
                <div class="w-10 h-10 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center flex-shrink-0"><i class="ri-file-text-line text-xl"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[11px] text-gray-400 font-medium leading-tight">Offer Letter</p>
                    <p id="sc-offer" class="text-xl font-bold text-gray-800 leading-tight mt-0.5">0</p>
                </div>
            </div>
            <div class="bg-white border border-gray-200 rounded-2xl p-3.5 flex items-center gap-3 hover:shadow-sm transition">
                <div class="w-10 h-10 rounded-xl bg-purple-50 text-purple-600 flex items-center justify-center flex-shrink-0"><i class="ri-award-line text-xl"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[11px] text-gray-400 font-medium leading-tight">Appointment</p>
                    <p id="sc-appt" class="text-xl font-bold text-gray-800 leading-tight mt-0.5">0</p>
                </div>
            </div>
            <div class="bg-white border border-gray-200 rounded-2xl p-3.5 flex items-center gap-3 hover:shadow-sm transition">
                <div class="w-10 h-10 rounded-xl bg-green-50 text-green-600 flex items-center justify-center flex-shrink-0"><i class="ri-line-chart-line text-xl"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[11px] text-gray-400 font-medium leading-tight">Appraisal</p>
                    <p id="sc-appr" class="text-xl font-bold text-gray-800 leading-tight mt-0.5">0</p>
                </div>
            </div>
            <div class="bg-white border border-gray-200 rounded-2xl p-3.5 flex items-center gap-3 hover:shadow-sm transition">
                <div class="w-10 h-10 rounded-xl bg-teal-50 text-teal-600 flex items-center justify-center flex-shrink-0"><i class="ri-award-line text-xl"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[11px] text-gray-400 font-medium leading-tight">Experience</p>
                    <p id="sc-exp" class="text-xl font-bold text-gray-800 leading-tight mt-0.5">0</p>
                </div>
            </div>
            <div class="bg-white border border-gray-200 rounded-2xl p-3.5 flex items-center gap-3 hover:shadow-sm transition">
                <div class="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center flex-shrink-0"><i class="ri-shield-check-line text-xl"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[11px] text-gray-400 font-medium leading-tight">No Due Cert.</p>
                    <p id="sc-ndc" class="text-xl font-bold text-gray-800 leading-tight mt-0.5">0</p>
                </div>
            </div>
            <div class="bg-white border border-gray-200 rounded-2xl p-3.5 flex items-center gap-3 hover:shadow-sm transition">
                <div class="w-10 h-10 rounded-xl bg-red-50 text-red-500 flex items-center justify-center flex-shrink-0"><i class="ri-money-dollar-circle-line text-xl"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[11px] text-gray-400 font-medium leading-tight">Full &amp; Final</p>
                    <p id="sc-fnf" class="text-xl font-bold text-gray-800 leading-tight mt-0.5">0</p>
                </div>
            </div>
            <div class="bg-white border border-gray-200 rounded-2xl p-3.5 flex items-center gap-3 hover:shadow-sm transition">
                <div class="w-10 h-10 rounded-xl bg-pink-50 text-pink-600 flex items-center justify-center flex-shrink-0"><i class="ri-book-open-line text-xl"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[11px] text-gray-400 font-medium leading-tight">Rules &amp; Regs</p>
                    <p id="sc-rnr" class="text-xl font-bold text-gray-800 leading-tight mt-0.5">0</p>
                </div>
            </div>
        </div>

        <!-- Mobile stat scroll -->
        <div class="sm:hidden mb-4 stat-scroll">
            <div class="stat-card-wrap bg-white border border-gray-200 rounded-2xl p-3 flex items-center gap-2.5">
                <div class="w-9 h-9 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center flex-shrink-0"><i class="ri-file-text-line text-lg"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[10px] text-gray-400 font-medium">Offer Letter</p>
                    <p id="sc-offer-m" class="text-lg font-bold text-gray-800">0</p>
                </div>
            </div>
            <div class="stat-card-wrap bg-white border border-gray-200 rounded-2xl p-3 flex items-center gap-2.5">
                <div class="w-9 h-9 rounded-xl bg-purple-50 text-purple-600 flex items-center justify-center flex-shrink-0"><i class="ri-award-line text-lg"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[10px] text-gray-400 font-medium">Appointment</p>
                    <p id="sc-appt-m" class="text-lg font-bold text-gray-800">0</p>
                </div>
            </div>
            <div class="stat-card-wrap bg-white border border-gray-200 rounded-2xl p-3 flex items-center gap-2.5">
                <div class="w-9 h-9 rounded-xl bg-green-50 text-green-600 flex items-center justify-center flex-shrink-0"><i class="ri-line-chart-line text-lg"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[10px] text-gray-400 font-medium">Appraisal</p>
                    <p id="sc-appr-m" class="text-lg font-bold text-gray-800">0</p>
                </div>
            </div>
            <div class="stat-card-wrap bg-white border border-gray-200 rounded-2xl p-3 flex items-center gap-2.5">
                <div class="w-9 h-9 rounded-xl bg-teal-50 text-teal-600 flex items-center justify-center flex-shrink-0"><i class="ri-award-line text-lg"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[10px] text-gray-400 font-medium">Experience</p>
                    <p id="sc-exp-m" class="text-lg font-bold text-gray-800">0</p>
                </div>
            </div>
            <div class="stat-card-wrap bg-white border border-gray-200 rounded-2xl p-3 flex items-center gap-2.5">
                <div class="w-9 h-9 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center flex-shrink-0"><i class="ri-shield-check-line text-lg"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[10px] text-gray-400 font-medium">No Due</p>
                    <p id="sc-ndc-m" class="text-lg font-bold text-gray-800">0</p>
                </div>
            </div>
            <div class="stat-card-wrap bg-white border border-gray-200 rounded-2xl p-3 flex items-center gap-2.5">
                <div class="w-9 h-9 rounded-xl bg-red-50 text-red-500 flex items-center justify-center flex-shrink-0"><i class="ri-money-dollar-circle-line text-lg"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[10px] text-gray-400 font-medium">Full &amp; Final</p>
                    <p id="sc-fnf-m" class="text-lg font-bold text-gray-800">0</p>
                </div>
            </div>
            <div class="stat-card-wrap bg-white border border-gray-200 rounded-2xl p-3 flex items-center gap-2.5">
                <div class="w-9 h-9 rounded-xl bg-pink-50 text-pink-600 flex items-center justify-center flex-shrink-0"><i class="ri-book-open-line text-lg"></i></div>
                <div class="flex-1 min-w-0">
                    <p class="text-[10px] text-gray-400 font-medium">Rules &amp; Regs</p>
                    <p id="sc-rnr-m" class="text-lg font-bold text-gray-800">0</p>
                </div>
            </div>
        </div>

        <!-- ===== TABLE ===== -->
        <div class="bg-white rounded-2xl border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full min-w-[800px]">
                    <thead class="bg-gray-50 border-b border-gray-200">
                        <tr>
                            <th class="px-4 py-3.5 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">No.</th>
                            <th class="px-4 py-3.5 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Letter ID</th>
                            <th class="px-4 py-3.5 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Letter Type</th>
                            <th class="px-4 py-3.5 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Name</th>
                            <th class="px-4 py-3.5 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Employee</th>
                            <th class="px-4 py-3.5 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Date</th>
                            <th class="px-4 py-3.5 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Generated By</th>
                            <th class="px-4 py-3.5 text-left text-[11px] font-semibold text-gray-400 uppercase tracking-wider">Action</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody" class="divide-y divide-gray-100 bg-white"></tbody>
                </table>
            </div>
            <div class="px-4 py-3.5 border-t border-gray-100 flex flex-col sm:flex-row items-center justify-between gap-3">
                <p id="footTxt" class="text-xs text-gray-400">Showing — of — records</p>
                <div id="pagination" class="flex items-center gap-1.5"></div>
            </div>
        </div>

    </div><!-- /main wrapper -->


    <!-- ========== FILTER SIDEBAR ========== -->
    <div id="filterSidebar"
        class="fixed top-0 right-[-340px] w-[300px] h-full bg-white border-l border-gray-200 z-50 transition-all duration-300 flex flex-col shadow-2xl">
        <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100">
            <h2 class="text-base font-bold text-gray-800">Filters</h2>
            <button onclick="closeSidebar()" class="w-8 h-8 rounded-lg border border-gray-200 text-gray-400 hover:bg-gray-100 flex items-center justify-center transition">
                <i class="ri-close-line text-lg"></i>
            </button>
        </div>
        <div class="flex-1 overflow-y-auto px-5 py-4 space-y-5">
            <div class="flex-1 min-w-0">
                <label class="block text-xs font-semibold text-gray-500 mb-1.5">From Date</label>
                <div class="relative">
                    <i class="ri-calendar-line absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                    <input id="fFrom" type="date" class="w-full h-10 rounded-xl border border-gray-200 bg-gray-50 pl-9 pr-3 text-sm text-gray-700 outline-none focus:border-brand-400 focus:ring-2 focus:ring-brand-100 transition">
                </div>
            </div>
            <div class="flex-1 min-w-0">
                <label class="block text-xs font-semibold text-gray-500 mb-1.5">To Date</label>
                <div class="relative">
                    <i class="ri-calendar-line absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                    <input id="fTo" type="date" class="w-full h-10 rounded-xl border border-gray-200 bg-gray-50 pl-9 pr-3 text-sm text-gray-700 outline-none focus:border-brand-400 focus:ring-2 focus:ring-brand-100 transition">
                </div>
            </div>
            <div class="flex-1 min-w-0">
                <label class="block text-xs font-semibold text-gray-500 mb-1.5">Employee</label>
                <div class="relative">
                    <i class="ri-user-line absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
<select id="fEmp">

    <option value="">All Employees</option>

    <option value="Rahul Sharma">
        Rahul Sharma
    </option>

    <option value="Amit Mehta">
        Amit Mehta
    </option>

    <option value="Priya Patel">
        Priya Patel
    </option>

    <option value="Neha Singh">
        Neha Singh
    </option>

    <option value="Karan Desai">
        Karan Desai
    </option>

</select>
                    <i class="ri-arrow-down-s-line absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                </div>
            </div>
            <div class="flex-1 min-w-0">
                <label class="block text-xs font-semibold text-gray-500 mb-1.5">Generated By</label>
                <div class="relative">
                    <i class="ri-user-settings-line absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
<select id="fGenBy">

    <option value="">All</option>

    <option value="Admin">
        Admin
    </option>

    <option value="HR Manager">
        HR Manager
    </option>

    <option value="Finance">
        Finance
    </option>

    <option value="Director">
        Director
    </option>

</select>
                    <i class="ri-arrow-down-s-line absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                </div>
            </div>
<!-- Letter Type -->
<div class="flex-1 min-w-0">

    <label class="block text-xs font-semibold text-gray-500 mb-1.5">
        Letter Type
    </label>

    <div class="relative">


        <select id="letterTypeSelect">

            <option value="">All Letter Types</option>

            <option value="Offer Letter">
                Offer Letter
            </option>

            <option value="Appointment Letter">
                Appointment Letter
            </option>

            <option value="Appraisal Letter">
                Appraisal Letter
            </option>

            <option value="Experience Letter">
                Experience Letter
            </option>

            <option value="No Due Certificate">
                No Due Certificate
            </option>

            <option value="Full and Final Settlement">
                Full and Final Settlement
            </option>

            <option value="Rules and Regulations">
                Rules and Regulations
            </option>

        </select>

    </div>

</div>
        </div>
        <div class="px-5 py-4 border-t border-gray-100 flex gap-3">
            <button onclick="resetFilter()" class="flex-1 h-10 rounded-xl border border-gray-200 bg-white text-gray-600 text-sm font-semibold hover:bg-gray-50 transition">Reset</button>
            <button onclick="applyFilter()" class="flex-1 h-10 rounded-xl bg-gradient-to-r from-brand-500 to-brand-600 text-white text-sm font-semibold shadow-sm transition">Apply Filter</button>
        </div>
    </div>


    <!-- ========== DELETE CONFIRM MODAL ========== -->
    <div id="delModalWrap"
        class="fixed inset-0 bg-black/40 z-[60] hidden items-center justify-center p-4"
        onclick="closeDelModal(event)">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-xs border border-gray-100" onclick="event.stopPropagation()">
            <div class="px-6 pt-6 pb-4 text-center">
                <div class="w-12 h-12 rounded-full bg-red-50 text-red-500 flex items-center justify-center mx-auto mb-3">
                    <i class="ri-delete-bin-6-line text-2xl"></i>
                </div>
                <h3 class="text-base font-bold text-gray-800">Delete Record?</h3>
                <p class="text-sm text-gray-400 mt-1">This letter record will be permanently removed.</p>
            </div>
            <div class="px-6 pb-5 flex gap-3">
                <button onclick="closeDelModal()" class="flex-1 h-10 rounded-xl border border-gray-200 bg-white text-gray-600 text-sm font-semibold hover:bg-gray-50 transition">Cancel</button>
                <button onclick="confirmDelete()" class="flex-1 h-10 rounded-xl bg-red-500 hover:bg-red-600 text-white text-sm font-semibold transition">Delete</button>
            </div>
        </div>
    </div>

    <!-- Toast -->
    <div id="toast" class="toast"></div>
    
    
<script>

const letterTypeSelect = new TomSelect("#letterTypeSelect", {

    create: false,
    maxOptions: 10,
    placeholder: "Search Letter Type...",

    openOnFocus: false,
    dropdownParent: "body",

    closeAfterSelect:true,

    onType:function(str){

        if(str.trim().length > 0){

            this.open();

        }else{

            this.close();

        }

    },

    onItemAdd:function(){

        this.control_input.value = "";

        this.control_input.setAttribute(
            "readonly",
            "readonly"
        );

        this.blur();
        this.close();

    },

    onDropdownOpen:function(){

        this.control_input.removeAttribute(
            "readonly"
        );

    }

});


/* CONTROL STYLE */
letterTypeSelect.control.classList.add(
    "flex",
    "items-center",
    "h-10",
    "w-full",
    "rounded-xl",
    "border",
    "border-gray-200",
    "bg-gray-50",
    "pl-9",
    "pr-3",
    "text-sm",
    "text-gray-700"
);


/* DROPDOWN STYLE */
letterTypeSelect.dropdown.classList.add(
    "z-[99999]",
    "overflow-hidden",
    "rounded-xl",
    "border",
    "border-gray-200",
    "bg-white",
    "shadow-xl"
);


/* INPUT STYLE */
letterTypeSelect.control_input.classList.add(
    "w-full",
    "bg-transparent",
    "text-sm",
    "text-gray-700",
    "placeholder:text-gray-400",
    "focus:outline-none",
    "ml-1"
);


/* DROPDOWN POSITION FIX */
letterTypeSelect.on("dropdown_open", function(){

    const controlRect =
        letterTypeSelect.control.getBoundingClientRect();

    letterTypeSelect.dropdown.style.position = "absolute";

    letterTypeSelect.dropdown.style.width =
        controlRect.width + "px";

    letterTypeSelect.dropdown.style.top =
        (controlRect.bottom + window.scrollY + 5) + "px";

    letterTypeSelect.dropdown.style.left =
        (controlRect.left + window.scrollX) + "px";

    letterTypeSelect.dropdown.style.zIndex = "99999";

});

</script>    
    
<script>

const generatedBySelect = new TomSelect("#fGenBy", {

    create: false,
    maxOptions: 10,
    placeholder: "Search Generated By...",

    openOnFocus: false,
    dropdownParent: "body",

    closeAfterSelect:true,

    onType:function(str){

        if(str.trim().length > 0){

            this.open();

        }else{

            this.close();

        }

    },

    onItemAdd:function(){

        this.control_input.value = "";

        this.control_input.setAttribute(
            "readonly",
            "readonly"
        );

        this.blur();
        this.close();

    },

    onDropdownOpen:function(){

        this.control_input.removeAttribute(
            "readonly"
        );

    }

});


/* CONTROL STYLE */
generatedBySelect.control.classList.add(
    "flex",
    "items-center",
    "h-10",
    "w-full",
    "rounded-xl",
    "border",
    "border-gray-200",
    "bg-gray-50",
    "pl-9",
    "pr-3",
    "text-sm",
    "text-gray-700"
);


/* DROPDOWN STYLE */
generatedBySelect.dropdown.classList.add(
    "z-[99999]",
    "overflow-hidden",
    "rounded-xl",
    "border",
    "border-gray-200",
    "bg-white",
    "shadow-xl"
);


/* INPUT STYLE */
generatedBySelect.control_input.classList.add(
    "w-full",
    "bg-transparent",
    "text-sm",
    "text-gray-700",
    "placeholder:text-gray-400",
    "focus:outline-none",
    "ml-1"
);


/* DROPDOWN POSITION FIX */
generatedBySelect.on("dropdown_open", function(){

    const controlRect =
        generatedBySelect.control.getBoundingClientRect();

    generatedBySelect.dropdown.style.position = "absolute";

    generatedBySelect.dropdown.style.width =
        controlRect.width + "px";

    generatedBySelect.dropdown.style.top =
        (controlRect.bottom + window.scrollY + 5) + "px";

    generatedBySelect.dropdown.style.left =
        (controlRect.left + window.scrollX) + "px";

    generatedBySelect.dropdown.style.zIndex = "99999";

});

</script>    
    
<script>

const employeeSelect = new TomSelect("#fEmp", {

    create: false,
    maxOptions: 10,
    placeholder: "Search Employee...",

    openOnFocus: false,
    dropdownParent: "body",

    closeAfterSelect:true,

    onType:function(str){

        if(str.trim().length > 0){

            this.open();

        }else{

            this.close();

        }

    },

    onItemAdd:function(){

        this.control_input.value = "";

        this.control_input.setAttribute(
            "readonly",
            "readonly"
        );

        this.blur();
        this.close();

    },

    onDropdownOpen:function(){

        this.control_input.removeAttribute(
            "readonly"
        );

    }

});


/* CONTROL STYLE */
employeeSelect.control.classList.add(
    "flex",
    "items-center",
    "h-10",
    "w-full",
    "rounded-xl",
    "border",
    "border-gray-200",
    "bg-gray-50",
    "pl-9",
    "pr-3",
    "text-sm",
    "text-gray-700"
);


/* DROPDOWN STYLE */
employeeSelect.dropdown.classList.add(
    "z-[99999]",
    "overflow-hidden",
    "rounded-xl",
    "border",
    "border-gray-200",
    "bg-white",
    "shadow-xl"
);


/* INPUT STYLE */
employeeSelect.control_input.classList.add(
    "w-full",
    "bg-transparent",
    "text-sm",
    "text-gray-700",
    "placeholder:text-gray-400",
    "focus:outline-none",
    "ml-1"
);


/* DROPDOWN POSITION FIX */
employeeSelect.on("dropdown_open", function(){

    const controlRect =
        employeeSelect.control.getBoundingClientRect();

    employeeSelect.dropdown.style.position = "absolute";

    employeeSelect.dropdown.style.width =
        controlRect.width + "px";

    employeeSelect.dropdown.style.top =
        (controlRect.bottom + window.scrollY + 5) + "px";

    employeeSelect.dropdown.style.left =
        (controlRect.left + window.scrollX) + "px";

    employeeSelect.dropdown.style.zIndex = "99999";

});

</script>

    <!-- ========== SCRIPT ========== -->
    <script>
        /* ===== DATA ===== */
        const EMPLOYEES = [{
                name: 'Rahul Sharma',
                dept: 'Sales',
                role: 'Manager'
            },
            {
                name: 'Amit Mehta',
                dept: 'IT',
                role: 'Developer'
            },
            {
                name: 'Priya Patel',
                dept: 'HR',
                role: 'Executive'
            },
            {
                name: 'Neha Singh',
                dept: 'Finance',
                role: 'Analyst'
            },
            {
                name: 'Karan Desai',
                dept: 'Ops',
                role: 'Lead'
            },
            {
                name: 'Sneha Joshi',
                dept: 'Sales',
                role: 'Executive'
            },
            {
                name: 'Raj Kumar',
                dept: 'IT',
                role: 'Senior Dev'
            },
            {
                name: 'Pooja Shah',
                dept: 'Admin',
                role: 'Assistant'
            },
        ];

        const TYPE_META = {
            'Offer Letter': {
                badge: 'bg-blue-100 text-blue-700',
                sc: 'sc-offer'
            },
            'Appointment Letter': {
                badge: 'bg-purple-100 text-purple-700',
                sc: 'sc-appt'
            },
            'Appraisal Letter': {
                badge: 'bg-green-100 text-green-700',
                sc: 'sc-appr'
            },
            'Experience Letter': {
                badge: 'bg-teal-100 text-teal-700',
                sc: 'sc-exp'
            },
            'No Due Certificate': {
                badge: 'bg-amber-100 text-amber-700',
                sc: 'sc-ndc'
            },
            'Full and Final Settlement': {
                badge: 'bg-red-100 text-red-600',
                sc: 'sc-fnf'
            },
            'Rules and Regulations': {
                badge: 'bg-pink-100 text-pink-700',
                sc: 'sc-rnr'
            },
        };

        let records = [{
                id: 'LTR-001',
                type: 'Offer Letter',
                name: 'Offer Letter – Raj Enterprise',
                emp: 'Rahul Sharma',
                date: '2025-01-10',
                genBy: 'Admin'
            },
            {
                id: 'LTR-002',
                type: 'Appointment Letter',
                name: 'Appointment Letter – ABC Corp.',
                emp: 'Amit Mehta',
                date: '2025-02-14',
                genBy: 'HR Manager'
            },
            {
                id: 'LTR-003',
                type: 'Appraisal Letter',
                name: 'Appraisal Letter 2025',
                emp: 'Priya Patel',
                date: '2025-03-01',
                genBy: 'Admin'
            },
            {
                id: 'LTR-004',
                type: 'Experience Letter',
                name: 'Experience Letter – Neha Singh',
                emp: 'Neha Singh',
                date: '2025-04-05',
                genBy: 'HR Manager'
            },
            {
                id: 'LTR-005',
                type: 'No Due Certificate',
                name: 'No Due Certificate – Karan',
                emp: 'Karan Desai',
                date: '2025-04-20',
                genBy: 'Admin'
            },
            {
                id: 'LTR-006',
                type: 'Full and Final Settlement',
                name: 'FnF Settlement – Rahul Sharma',
                emp: 'Rahul Sharma',
                date: '2025-05-01',
                genBy: 'Finance'
            },
            {
                id: 'LTR-007',
                type: 'Rules and Regulations',
                name: 'Company Rules & Regulations 2025',
                emp: 'All Staff',
                date: '2025-05-10',
                genBy: 'Director'
            },
        ];

        let filtered = [...records];
        let page = 1;
        const PER = 5;
        let delTarget = -1;
        let filterTypes = [];

        /* ===== GENERATE SECTION STATE ===== */
        let selectedEmployee = '';
        let selectedLetterType = '';

        /* ----- Employee Dropdown ----- */
        function initDropdown() {
            renderDropdownList('');
        }

        function renderDropdownList(query) {
            const list = document.getElementById('empDropdownList');
            const q = query.toLowerCase();
            const matches = EMPLOYEES.filter(e => e.name.toLowerCase().includes(q) || e.dept.toLowerCase().includes(q));
            if (!matches.length) {
                list.innerHTML = `<div class="dropdown-item text-gray-400"><i class="ri-user-search-line mr-2"></i>No employee found</div>`;
                return;
            }
            list.innerHTML = matches.map(e => `
        <div class="dropdown-item ${selectedEmployee===e.name?'selected-item':''}" onclick="selectEmployee('${e.name}','${e.dept}','${e.role}')">
            <div class="w-7 h-7 rounded-full ${avatarBg(e.name)} text-[10px] font-bold flex items-center justify-center flex-shrink-0">${initials(e.name)}</div>
            <div class="flex-1 min-w-0">
                <p class="font-semibold text-gray-800 text-xs leading-tight">${e.name}</p>
                <p class="text-[10px] text-gray-400">${e.dept} · ${e.role}</p>
            </div>
        </div>`).join('');
        }

        function openDropdown() {
            document.getElementById('empDropdownList').classList.add('open');
            renderDropdownList(document.getElementById('empSearchInput').value);
        }

        function closeDropdown() {
            document.getElementById('empDropdownList').classList.remove('open');
        }

        function filterDropdown(val) {
            renderDropdownList(val);
            openDropdown();
        }

        function selectEmployee(name, dept, role) {
            selectedEmployee = name;
            document.getElementById('empSearchInput').value = name;
            document.getElementById('chipName').textContent = name;
            document.getElementById('chipAvatar').textContent = initials(name);
            document.getElementById('chipAvatar').className = `w-5 h-5 rounded-full text-[9px] font-bold flex items-center justify-center ${avatarBg(name)}`;
            document.getElementById('selectedEmpChip').classList.remove('hidden');
            closeDropdown();
            checkGenerateReady();
        }

        function clearEmployee() {
            selectedEmployee = '';
            document.getElementById('empSearchInput').value = '';
            document.getElementById('selectedEmpChip').classList.add('hidden');
            checkGenerateReady();
        }

        /* ----- Letter Type Cards ----- */
        function selectLetterType(card, type) {
            document.querySelectorAll('.letter-card').forEach(c => c.classList.remove('active'));
            card.classList.add('active');
            selectedLetterType = type;
            checkGenerateReady();
        }

        /* ----- Enable/disable Generate button ----- */
        function checkGenerateReady() {
            const btn = document.getElementById('generateBtn');
            if (selectedEmployee && selectedLetterType) {
                btn.disabled = false;
                btn.classList.remove('opacity-60', 'cursor-not-allowed');
                btn.classList.add('opacity-100', 'cursor-pointer');
            } else {
                btn.disabled = true;
                btn.classList.add('opacity-60', 'cursor-not-allowed');
                btn.classList.remove('opacity-100', 'cursor-pointer');
            }
        }

        /* ----- Generate ----- */
        function generateLetter() {
            if (!selectedEmployee || !selectedLetterType) return;
            const today = new Date().toISOString().split('T')[0];
            const n = records.length + 1;
            const id = `LTR-${String(n).padStart(3,'0')}`;
            records.push({
                id,
                type: selectedLetterType,
                name: `${selectedLetterType} – ${selectedEmployee}`,
                emp: selectedEmployee,
                date: today,
                genBy: 'Admin'
            });
            filtered = [...records];
            page = Math.ceil(filtered.length / PER);
            renderTable();

            // Reset
            clearEmployee();
            document.querySelectorAll('.letter-card').forEach(c => c.classList.remove('active'));
            selectedLetterType = '';
            checkGenerateReady();

            showToast(`${selectedLetterType || 'Letter'} generated ${selectedEmployee}!`);
        }

        /* ===== HELPERS ===== */
        function fmtDate(d) {
            if (!d) return '—';
            const [y, m, day] = d.split('-');
            const mn = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
            return `${parseInt(day)} ${mn[+m-1]} ${y}`;
        }

        function initials(n) {
            return n.split(' ').map(x => x[0]).join('').substring(0, 2).toUpperCase();
        }

        function avatarBg(n) {
            const c = ['bg-blue-100 text-blue-600', 'bg-purple-100 text-purple-600', 'bg-green-100 text-green-600', 'bg-teal-100 text-teal-600', 'bg-amber-100 text-amber-600', 'bg-pink-100 text-pink-600'];
            let h = 0;
            for (let ch of n) h = (h + ch.charCodeAt(0)) % c.length;
            return c[h];
        }

        /* ===== TABLE ===== */
        function renderTable() {
            const start = (page - 1) * PER,
                end = Math.min(start + PER, filtered.length);
            const slice = filtered.slice(start, end);
            const tb = document.getElementById('tableBody');
            if (!slice.length) {
                tb.innerHTML = `<tr><td colspan="8" class="px-4 py-12 text-center text-sm text-gray-400"><i class="ri-file-search-line text-3xl block mb-2"></i>No records found</td></tr>`;
            } else {
                tb.innerHTML = slice.map((r, i) => {
                    const meta = TYPE_META[r.type] || {
                        badge: 'bg-gray-100 text-gray-600'
                    };
                    const avt = avatarBg(r.emp);
                    return `<tr class="table-row-hover transition">
                <td class="px-4 py-3 text-sm font-bold text-brand-500">${String(start+i+1).padStart(2,'0')}</td>
                <td class="px-4 py-3 text-xs text-gray-400 font-mono font-medium">${r.id}</td>
                <td class="px-4 py-3"><span class="badge ${meta.badge}">${r.type}</span></td>
                <td class="px-4 py-3 text-sm text-gray-700 max-w-[180px] truncate" title="${r.name}">${r.name}</td>
                <td class="px-4 py-3">
                    <div class="flex items-center gap-2">
                        <div class="w-7 h-7 rounded-full ${avt} text-[10px] font-bold flex items-center justify-center flex-shrink-0">${initials(r.emp)}</div>
                        <span class="text-sm text-gray-700 whitespace-nowrap">${r.emp}</span>
                    </div>
                </td>
                <td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">${fmtDate(r.date)}</td>
                <td class="px-4 py-3 text-sm text-gray-600">${r.genBy}</td>
                <td class="px-4 py-3">
                    <div class="flex items-center gap-1.5">
                        <button class="act-btn bg-amber-50 text-amber-600 hover:bg-amber-100" title="Download" onclick="showToast('Downloading ${r.id}')"><i class="ri-download-2-line"></i></button>
                        <button class="act-btn bg-red-50 text-red-500 hover:bg-red-100" title="Delete" onclick="openDelModal(${start+i})"><i class="ri-delete-bin-line"></i></button>
                    </div>
                </td>
            </tr>`;
                }).join('');
            }
            document.getElementById('footTxt').textContent =
                filtered.length ? `Showing ${start+1}–${end} of ${filtered.length} records` : 'No records found';
            renderPagination();
            updateStats();
        }

        function renderPagination() {
            const total = Math.ceil(filtered.length / PER) || 1;
            const pg = document.getElementById('pagination');
            let html = `<button onclick="changePage(-1)" class="w-8 h-8 rounded-lg border border-gray-200 text-gray-400 hover:bg-gray-100 flex items-center justify-center text-xs transition"><i class="ri-arrow-left-s-line"></i></button>`;
            for (let i = 1; i <= total; i++) {
                const a = i === page;
                html += `<button onclick="goPage(${i})" class="w-8 h-8 rounded-lg ${a?'bg-gradient-to-r from-brand-500 to-brand-600 text-white shadow-sm':'border border-gray-200 text-gray-600 hover:bg-gray-100'} text-xs font-semibold flex items-center justify-center transition">${i}</button>`;
            }
            html += `<button onclick="changePage(1)" class="w-8 h-8 rounded-lg border border-gray-200 text-gray-400 hover:bg-gray-100 flex items-center justify-center text-xs transition"><i class="ri-arrow-right-s-line"></i></button>`;
            pg.innerHTML = html;
        }

        function updateStats() {
            const counts = {};
            records.forEach(r => counts[r.type] = (counts[r.type] || 0) + 1);
            Object.entries(TYPE_META).forEach(([t, m]) => {
                ['', '-m'].forEach(sfx => {
                    const el = document.getElementById(m.sc + sfx);
                    if (el) el.textContent = counts[t] || 0;
                });
            });
        }

        function filterTable() {
            const q = document.getElementById('searchInput').value.toLowerCase();
            filtered = records.filter(r =>
                r.emp.toLowerCase().includes(q) || r.name.toLowerCase().includes(q) ||
                r.id.toLowerCase().includes(q) || r.type.toLowerCase().includes(q)
            );
            page = 1;
            renderTable();
        }

        function changePage(d) {
            page = Math.max(1, Math.min(Math.ceil(filtered.length / PER) || 1, page + d));
            renderTable();
        }

        function goPage(p) {
            page = p;
            renderTable();
        }

        /* ===== FILTER SIDEBAR ===== */
        function openSidebar() {
            document.getElementById('filterSidebar').style.right = '0';
            document.getElementById('overlay').classList.remove('hidden');
        }

        function closeSidebar() {
            document.getElementById('filterSidebar').style.right = '-340px';
            document.getElementById('overlay').classList.add('hidden');
        }

        function toggleFilterType(el, type) {
            el.classList.toggle('selected');
            if (filterTypes.includes(type)) filterTypes = filterTypes.filter(t => t !== type);
            else filterTypes.push(type);
        }

        function applyFilter() {
            const from = document.getElementById('fFrom').value;
            const to = document.getElementById('fTo').value;
            const emp = document.getElementById('fEmp').value;
            const genBy = document.getElementById('fGenBy').value;
            filtered = records.filter(r => {
                if (emp && r.emp !== emp) return false;
                if (genBy && r.genBy !== genBy) return false;
                if (filterTypes.length && !filterTypes.includes(r.type)) return false;
                if (from && r.date < from) return false;
                if (to && r.date > to) return false;
                return true;
            });
            page = 1;
            closeSidebar();
            renderTable();
        }

        function resetFilter() {
            ['fFrom', 'fTo', 'fEmp', 'fGenBy'].forEach(id => document.getElementById(id).value = '');
            filterTypes = [];
            document.querySelectorAll('.filter-chip').forEach(c => c.classList.remove('selected'));
            filtered = [...records];
            page = 1;
            renderTable();
        }

        /* ===== DELETE MODAL ===== */
        function openDelModal(i) {
            delTarget = i;
            document.getElementById('delModalWrap').classList.remove('hidden');
            document.getElementById('delModalWrap').classList.add('flex');
        }

        function closeDelModal(e) {
            if (e && e.target !== document.getElementById('delModalWrap')) return;
            document.getElementById('delModalWrap').classList.add('hidden');
            document.getElementById('delModalWrap').classList.remove('flex');
            delTarget = -1;
        }

        function confirmDelete() {
            if (delTarget < 0) return;
            const r = filtered[delTarget];
            records = records.filter(x => x.id !== r.id);
            filtered = filtered.filter(x => x.id !== r.id);
            if ((page - 1) * PER >= filtered.length && page > 1) page--;
            document.getElementById('delModalWrap').classList.add('hidden');
            document.getElementById('delModalWrap').classList.remove('flex');
            delTarget = -1;
            renderTable();
            showToast('Record deleted successfully');
        }

        /* ===== TOAST ===== */
        function showToast(msg, type) {
            const t = document.getElementById('toast');
            t.textContent = msg;
            t.style.background = type === 'warn' ? '#d97706' : '#16a34a';
            t.classList.add('show');
            setTimeout(() => t.classList.remove('show'), 2200);
        }

        /* ===== CLOSE DROPDOWN ON OUTSIDE CLICK ===== */
        document.addEventListener('click', e => {
            const wrap = document.getElementById('empDropdownWrap');
            if (!wrap.contains(e.target)) closeDropdown();
        });

        /* ===== INIT ===== */
        initDropdown();
        renderTable();
    </script>

</body>

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