<?php
require_once 'includes/db.php';
$employees = fetchAll("
    SELECT e.*, r.name as role_name, s.name as shift_name 
    FROM employees e 
    LEFT JOIN roles r ON e.role_id = r.id 
    LEFT JOIN shifts s ON e.shift_id = s.id 
    WHERE e.company_id = ? AND e.user_id != ? 
    ORDER BY e.created_at DESC
", [$_SESSION['company_id'], $_SESSION['user_id']]);
$roles = fetchAll("SELECT * FROM roles");
$skills = fetchAll("SELECT * FROM skills");
$dashboards = fetchAll("SELECT * FROM dashboards");
$managers = fetchAll("SELECT id, name, role FROM users WHERE company_id = ? AND role IN ('owner', 'manager') AND is_active = 1", [$_SESSION['company_id']]);
$company_name = fetchValue("SELECT name FROM companies WHERE id = ?", [$_SESSION['company_id']]) ?: 'NexCore Apparel';
$shifts = fetchAll("SELECT id, name FROM shifts WHERE company_id = ? ORDER BY name ASC", [$_SESSION['company_id']]);
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; gap: 1rem;">
    <div style="position: relative; flex: 1; max-width: 400px;">
        <i class="fas fa-search" style="position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: var(--text-muted); opacity: 0.5;"></i>
        <input type="text" id="employeeSearch" class="form-control" placeholder="Search by name, NIC, or role..." style="padding-left: 2.75rem; border-radius: 50px; background: var(--bg-card); border: 1px solid var(--border); box-shadow: var(--shadow);">
    </div>
    <button class="btn btn-primary" onclick="openAddEmployeeModal()">
        <i class="fas fa-user-plus"></i> Add New Employee
    </button>
</div>

    <div class="data-grid">
        <?php foreach ($employees as $employee): ?>
        <div class="data-card">
            <div class="data-card-header">
                <div style="display: flex; align-items: center; gap: 1rem;">
                    <div class="user-avatar" style="width: 48px; height: 48px; font-size: 1.25rem; overflow: hidden; background: var(--bg-dark); border: 2px solid var(--border);">
                        <?php if ($employee['profile_picture']): ?>
                            <img src="<?php echo $employee['profile_picture']; ?>" style="width: 100%; height: 100%; object-fit: cover;">
                        <?php else: ?>
                            <?php echo strtoupper(substr($employee['name'], 0, 1)); ?>
                        <?php endif; ?>
                    </div>
                    <div>
                        <h3 style="font-size: 1.125rem; font-weight: 700; margin-bottom: 0.25rem;"><?php echo $employee['name']; ?></h3>
                        <span class="btn" style="padding: 0.2rem 0.6rem; font-size: 0.7rem; background: rgba(99, 102, 241, 0.1); color: var(--primary); border-radius: 6px;">
                            <?php echo $employee['role_name']; ?>
                        </span>
                    </div>
                </div>
                <span class="btn" style="padding: 0.25rem 0.75rem; font-size: 0.75rem; background: <?php echo $employee['is_active'] ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)'; ?>; color: <?php echo $employee['is_active'] ? 'var(--success)' : 'var(--danger)'; ?>;">
                    <?php echo $employee['is_active'] ? 'Active' : 'Inactive'; ?>
                </span>
            </div>
            
            <div class="data-card-body">
                <div class="data-card-item">
                    <i class="fas fa-id-card"></i>
                    <span>ID: <?php echo e($employee['employee_code']); ?></span>
                </div>
                <?php 
                $mgr_name = '';
                if ($employee['reporting_manager_id']) {
                    $mgr_name = fetchValue("SELECT name FROM users WHERE id = ?", [$employee['reporting_manager_id']]);
                }
                ?>
                <div class="data-card-item">
                    <i class="fas fa-user-tie"></i>
                    <span>Manager: <?php echo $mgr_name ? e($mgr_name) : '<span style="color: var(--text-muted); font-style: italic;">None</span>'; ?></span>
                </div>
                <div class="data-card-item">
                    <i class="fas fa-calendar-day"></i>
                    <span>Shift: <?php echo $employee['shift_name'] ? e($employee['shift_name']) : '<span style="color: var(--text-muted); font-style: italic;">None</span>'; ?></span>
                </div>
                <div class="data-card-item">
                    <i class="fas fa-fingerprint"></i>
                    <span>NIC: <?php echo $employee['nic']; ?></span>
                </div>
                <div class="data-card-item">
                    <i class="fas fa-envelope"></i>
                    <span style="color: var(--text-muted);"><?php echo $employee['email'] ?: 'No Email'; ?></span>
                </div>
                <div class="data-card-item">
                    <i class="fas fa-phone"></i>
                    <span style="color: var(--text-muted);"><?php echo $employee['phone']; ?></span>
                </div>
                <div class="data-card-item" style="color: var(--primary); font-weight: 700; margin-top: 0.5rem; padding-top: 0.5rem; border-top: 1px solid var(--border); display: flex; justify-content: space-between; gap: 0.5rem;">
                    <div>
                        <i class="fas fa-clock"></i>
                        <span>Rate: <?php echo formatCurrency($employee['hourly_rate']); ?>/hr</span>
                    </div>
                    <div>
                        <i class="fas fa-money-bill-wave"></i>
                        <span>Base: <?php echo formatCurrency($employee['base_salary']); ?></span>
                    </div>
                </div>

                <!-- Skills Section -->
                <div style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid var(--border);">
                    <div style="font-size: 0.7rem; color: var(--text-muted); margin-bottom: 0.5rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em;">Skills</div>
                    <div style="display: flex; flex-wrap: wrap; gap: 0.4rem;">
                        <?php 
                        $emp_skill_names = fetchAll("SELECT s.name FROM skills s JOIN employee_skill es ON s.id = es.skill_id WHERE es.employee_id = ?", [$employee['id']]);
                        if (!empty($emp_skill_names)):
                            foreach ($emp_skill_names as $skill_name): ?>
                                <span style="font-size: 0.65rem; padding: 0.2rem 0.5rem; background: var(--bg-dark); border: 1px solid var(--border); border-radius: 4px; color: var(--text-main);">
                                    <?php echo $skill_name['name']; ?>
                                </span>
                            <?php endforeach;
                        else: ?>
                            <span style="font-size: 0.65rem; color: var(--text-muted); font-style: italic;">No skills listed</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="data-card-footer">
                <button class="btn" style="background: var(--bg-dark); padding: 0.5rem; flex: 1;" onclick='editEmployee(<?php 
                    $emp_skills = fetchAll("SELECT skill_id FROM employee_skill WHERE employee_id = ?", [$employee['id']]);
                    $employee['skill_ids'] = array_column($emp_skills, 'skill_id');
                    $user = fetch("SELECT username FROM users WHERE id = ?", [$employee['user_id']]);
                    $employee['username'] = $user['username'] ?? '';
                    echo htmlspecialchars(json_encode($employee), ENT_QUOTES, "UTF-8"); 
                ?>)'>
                    <i class="fas fa-user-edit"></i> Edit
                </button>
                <button class="btn" style="background: rgba(99, 102, 241, 0.1); color: var(--primary); padding: 0.5rem;" title="ID Badge & QR Code" onclick='viewIdBadge({id: <?php echo $employee['id']; ?>, name: <?php echo json_encode($employee['name']); ?>, role_name: <?php echo json_encode($employee['role_name']); ?>, employee_code: <?php echo json_encode($employee['employee_code']); ?>, profile_picture: <?php echo json_encode($employee['profile_picture']); ?>})'>
                    <i class="fas fa-id-card"></i> Badge
                </button>
                <button class="btn" style="background: rgba(239, 68, 68, 0.1); color: var(--danger); padding: 0.5rem;" onclick="deleteEmployee(<?php echo $employee['id']; ?>)">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
        <?php endforeach; ?>
        
        <?php if (empty($employees)): ?>
        <div style="grid-column: 1 / -1; text-align: center; padding: 4rem; background: var(--bg-card); border-radius: 24px; border: 2px dashed var(--border);">
            <i class="fas fa-box-open fa-3x" style="margin-bottom: 1.5rem; color: var(--text-muted); opacity: 0.5;"></i>
            <h3 style="color: var(--text-main); margin-bottom: 0.5rem;">No Employees Found</h3>
            <p style="color: var(--text-muted);">Add your first team member to get started.</p>
        </div>
        <?php endif; ?>
    </div>

<!-- Employee Modal -->
<div id="employeeModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 800px;">
        <div class="modal-header" style="padding: 0.75rem 1.25rem;">
            <h2 id="modalTitle" style="font-size: 1.25rem;">Add New Employee</h2>
            <button class="btn" style="background: none; color: var(--text-muted); padding: 0.5rem;" onclick="closeModal('employeeModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form id="employeeForm" enctype="multipart/form-data">
            <input type="hidden" id="employee_id" name="id">
            <div class="modal-body" style="padding-top: 0.5rem;">
                <!-- Top Row: Profile & Basic Info -->
                <div style="display: grid; grid-template-columns: 100px 1.2fr 2fr 2fr; gap: 1rem; margin-bottom: 0.75rem; align-items: flex-end;">
                    <div style="display: flex; flex-direction: column; align-items: center; gap: 0.25rem;">
                        <div id="imagePreview" class="user-avatar" style="width: 70px; height: 70px; font-size: 1.5rem; border: 2px solid var(--primary); background: var(--bg-dark); cursor: pointer; overflow: hidden;" onclick="document.getElementById('employee_image').click()">
                            <i class="fas fa-camera" style="opacity: 0.5;"></i>
                        </div>
                        <input type="file" id="employee_image" name="profile_picture" style="display: none;" accept="image/*" onchange="previewImage(this)">
                        <span style="font-size: 0.6rem; color: var(--text-muted); text-align: center;">Photo</span>
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="margin-bottom: 0.25rem; font-size: 0.75rem;">Employee ID <span class="required-mark">*</span></label>
                        <input type="text" id="employee_code_input" name="employee_code" class="form-control" style="padding: 0.5rem;" required>
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="margin-bottom: 0.25rem; font-size: 0.75rem;">Full Name <span class="required-mark">*</span></label>
                        <input type="text" id="employee_name" name="name" class="form-control" style="padding: 0.5rem;" required>
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="margin-bottom: 0.25rem; font-size: 0.75rem;">Email Address</label>
                        <input type="email" id="employee_email" name="email" class="form-control" style="padding: 0.5rem;">
                    </div>
                </div>

                <!-- Second Row: Contact & Identity -->
                <div style="display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 0.75rem; margin-bottom: 0.75rem;">
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="margin-bottom: 0.25rem; font-size: 0.75rem;">Phone <span class="required-mark">*</span></label>
                        <input type="tel" id="employee_phone" name="phone" class="form-control" style="padding: 0.5rem;" required>
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="margin-bottom: 0.25rem; font-size: 0.75rem;">NIC Number <span class="required-mark">*</span></label>
                        <input type="text" id="employee_nic" name="nic" class="form-control" style="padding: 0.5rem;" required>
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="margin-bottom: 0.25rem; font-size: 0.75rem;">Hourly Rate <span class="required-mark">*</span></label>
                        <div style="display: flex; align-items: stretch; width: 100%;">
                            <span style="background: var(--bg-dark); border: 1px solid rgba(0,0,0,0.1); border-right: none; padding: 0.5rem 0.75rem; border-radius: 10px 0 0 10px; font-weight: 700; color: var(--text-muted); display: inline-flex; align-items: center; font-size: 0.85rem; white-space: nowrap;"><?php echo $_SESSION['company_currency'] ?? '$'; ?></span>
                            <input type="number" step="0.01" id="employee_hourly_rate" name="hourly_rate" class="form-control" style="border-top-left-radius: 0; border-bottom-left-radius: 0; flex: 1; padding: 0.5rem;" required>
                        </div>
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="margin-bottom: 0.25rem; font-size: 0.75rem;">Base Salary <span class="required-mark">*</span></label>
                        <div style="display: flex; align-items: stretch; width: 100%;">
                            <span style="background: var(--bg-dark); border: 1px solid rgba(0,0,0,0.1); border-right: none; padding: 0.5rem 0.75rem; border-radius: 10px 0 0 10px; font-weight: 700; color: var(--text-muted); display: inline-flex; align-items: center; font-size: 0.85rem; white-space: nowrap;"><?php echo $_SESSION['company_currency'] ?? '$'; ?></span>
                            <input type="number" step="0.01" id="employee_base_salary" name="base_salary" class="form-control" style="border-top-left-radius: 0; border-bottom-left-radius: 0; flex: 1; padding: 0.5rem;" required>
                        </div>
                    </div>
                </div>

                <!-- Third Row: Address & Roles -->
                <div style="display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 0.75rem; margin-bottom: 0.75rem;">
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="margin-bottom: 0.25rem; font-size: 0.75rem;">Address <span class="required-mark">*</span></label>
                        <input type="text" id="employee_address" name="address" class="form-control" style="padding: 0.5rem;" required>
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="margin-bottom: 0.25rem; font-size: 0.75rem;">Role <span class="required-mark">*</span></label>
                        <select id="employee_role" name="role_id" class="form-control" style="padding: 0.5rem;" required>
                            <?php foreach ($roles as $role): ?>
                                <option value="<?php echo $role['id']; ?>"><?php echo $role['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="margin-bottom: 0.25rem; font-size: 0.75rem;">Dashboard <span class="required-mark">*</span></label>
                        <select id="employee_dashboard" name="dashboard_id" class="form-control" style="padding: 0.5rem;" required>
                            <?php foreach ($dashboards as $db): ?>
                                <option value="<?php echo $db['id']; ?>"><?php echo $db['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <!-- Fourth Row: Manager & Shift -->
                <div style="display: grid; grid-template-columns: 1.2fr 0.8fr; gap: 0.75rem; margin-bottom: 0.75rem;">
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="margin-bottom: 0.25rem; font-size: 0.75rem;">Reporting Manager <span class="required-mark">*</span></label>
                        <select id="employee_reporting_manager" name="reporting_manager_id" class="form-control" style="padding: 0.5rem;" required>
                            <option value="" disabled selected>Select Reporting Manager</option>
                            <?php foreach ($managers as $mgr): ?>
                                <option value="<?php echo $mgr['id']; ?>"><?php echo htmlspecialchars($mgr['name'] . ' (' . ucfirst($mgr['role']) . ')'); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="margin-bottom: 0.25rem; font-size: 0.75rem;">Shift</label>
                        <select id="employee_shift" name="shift_id" class="form-control" style="padding: 0.5rem;">
                            <option value="">No Shift</option>
                            <?php foreach ($shifts as $shift): ?>
                                <option value="<?php echo $shift['id']; ?>"><?php echo htmlspecialchars($shift['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <!-- Fourth Row: Skills & Login Details combined -->
                <div style="display: grid; grid-template-columns: 1.5fr 1fr; gap: 1rem; margin-top: 0.5rem; padding-top: 0.75rem; border-top: 1px solid var(--border);">
                    <div id="skillsSection">
                        <label class="form-label" style="margin-bottom: 0.4rem; font-size: 0.75rem; font-weight: 600;">Skills Portfolio</label>
                        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.4rem; background: rgba(255,255,255,0.03); padding: 0.5rem; border-radius: 8px; border: 1px solid var(--border);">
                            <?php foreach ($skills as $skill): ?>
                            <label style="display: flex; align-items: center; gap: 0.4rem; font-size: 0.7rem; cursor: pointer;">
                                <input type="checkbox" name="skills[]" value="<?php echo $skill['id']; ?>" class="skill-checkbox">
                                <?php echo $skill['name']; ?>
                            </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div>
                        <label class="form-label" style="margin-bottom: 0.4rem; font-size: 0.75rem; font-weight: 600;">Login Credentials</label>
                        <div style="background: rgba(255,255,255,0.03); padding: 0.5rem; border-radius: 8px; border: 1px solid var(--border); display: flex; flex-direction: column; gap: 0.5rem;">
                            <div class="form-group" style="margin-bottom: 0;">
                                <input type="text" id="employee_username" name="username" class="form-control" placeholder="Username *" style="padding: 0.4rem; font-size: 0.8rem;" required>
                            </div>
                            <div class="form-group" style="margin-bottom: 0; position: relative;">
                                <input type="password" id="employee_password" name="password" class="form-control" placeholder="Password (New)" style="padding: 0.4rem 2.2rem 0.4rem 0.4rem; font-size: 0.8rem;">
                                <button type="button" onclick="togglePasswordVisibility('employee_password', this)" style="position: absolute; right: 0.4rem; top: 50%; transform: translateY(-50%); background: none; border: none; color: var(--text-muted); cursor: pointer; padding: 0.25rem; display: flex; align-items: center; justify-content: center;">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer" style="padding: 0.75rem 1.25rem;">
                <button type="button" class="btn" style="background: var(--glass-bg); padding: 0.5rem 1rem;" onclick="closeModal('employeeModal')">Cancel</button>
                <button type="submit" class="btn btn-primary" style="padding: 0.5rem 1.5rem;">Save Employee</button>
            </div>
        </form>
    </div>
</div>

<!-- ID Badge Modal -->
<div id="badgeModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 400px; padding: 1.5rem; text-align: center;">
        <div class="modal-header" style="padding: 0; border: none; margin-bottom: 1rem; justify-content: space-between; align-items: center;">
            <h3 style="margin: 0; font-size: 1.15rem; color: var(--text-main);">Employee ID Badge</h3>
            <button class="btn" style="background: none; color: var(--text-muted); padding: 0.5rem; border: none;" onclick="closeModal('badgeModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <!-- Printable Badge Area -->
        <div id="printableBadge" style="width: 280px; height: 420px; background: linear-gradient(135deg, #1e1b4b, #312e81); border-radius: 16px; margin: 1.5rem auto; padding: 1.5rem; color: white; display: flex; flex-direction: column; align-items: center; justify-content: space-between; border: 2px solid rgba(255,255,255,0.15); box-shadow: 0 10px 25px rgba(0,0,0,0.3); position: relative; overflow: hidden; font-family: 'Outfit', sans-serif;">
            <!-- Subtle background graphics -->
            <div style="position: absolute; width: 200px; height: 200px; background: rgba(99, 102, 241, 0.1); border-radius: 50%; top: -50px; right: -50px; pointer-events: none;"></div>
            <div style="position: absolute; width: 150px; height: 150px; background: rgba(16, 185, 129, 0.05); border-radius: 50%; bottom: -30px; left: -30px; pointer-events: none;"></div>

            <!-- Header -->
            <div style="text-align: center; width: 100%;">
                <div style="font-weight: 800; font-size: 1.1rem; letter-spacing: -0.5px; text-transform: uppercase;"><?php echo htmlspecialchars($company_name); ?></div>
                <div style="font-size: 0.6rem; color: #a5b4fc; text-transform: uppercase; letter-spacing: 1px; font-weight: 600;">Garment Factory ID</div>
            </div>

            <!-- Avatar -->
            <div style="width: 100px; height: 100px; border-radius: 50%; border: 3px solid #6366f1; overflow: hidden; background: rgba(255,255,255,0.05); display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 10px rgba(0,0,0,0.3); margin-top: 0.5rem;">
                <img id="badgeAvatar" src="assets/img/avatar-placeholder.png" style="width: 100%; height: 100%; object-fit: cover;">
            </div>

            <!-- Profile Info -->
            <div style="text-align: center; margin-top: 0.5rem;">
                <div id="badgeName" style="font-size: 1.25rem; font-weight: 700; line-height: 1.2;">Employee Name</div>
                <div id="badgeRole" style="font-size: 0.8rem; color: #93c5fd; font-weight: 600; text-transform: uppercase; margin-top: 0.25rem; letter-spacing: 0.5px;">Operator</div>
            </div>

            <!-- QR Code Container -->
            <div style="background: white; padding: 0.5rem; border-radius: 12px; display: inline-flex; align-items: center; justify-content: center; margin: 0.5rem 0; box-shadow: 0 4px 10px rgba(0,0,0,0.2);">
                <img id="badgeQr" src="" crossorigin="anonymous" style="width: 110px; height: 110px; image-rendering: pixelated;" alt="QR Code">
            </div>

            <!-- Employee ID Text -->
            <div style="text-align: center;">
                <div id="badgeCode" style="font-family: monospace; font-size: 1.1rem; font-weight: 700; color: #60a5fa; letter-spacing: 1px;">EMP-00000</div>
            </div>
        </div>

        <div style="display: flex; gap: 0.5rem; justify-content: center; margin-top: 1rem;">
            <button class="btn btn-primary" onclick="downloadBadge()" style="padding: 0.5rem 1.5rem; display: flex; align-items: center; gap: 0.5rem;">
                <i class="fas fa-download"></i> Download Badge
            </button>
            <button class="btn" style="background: var(--glass-bg); padding: 0.5rem 1rem;" onclick="closeModal('badgeModal')">Close</button>
        </div>
    </div>
</div>

<!-- html2canvas library for downloading badge as image -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script>
// Modal Helpers
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) modal.classList.add('active');
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) modal.classList.remove('active');
}

function viewIdBadge(employee) {
    const avatarImg = document.getElementById('badgeAvatar');
    const nameEl = document.getElementById('badgeName');
    const roleEl = document.getElementById('badgeRole');
    const codeEl = document.getElementById('badgeCode');
    const qrImg = document.getElementById('badgeQr');
    
    nameEl.textContent = employee.name;
    roleEl.textContent = employee.role_name || 'Staff';
    codeEl.textContent = employee.employee_code || 'EMP-' + String(employee.id).padStart(5, '0');
    
    if (employee.profile_picture) {
        avatarImg.src = employee.profile_picture;
    } else {
        avatarImg.src = 'assets/img/avatar-placeholder.png';
    }
    
    // Generate QR code using public dynamic api
    const qrData = encodeURIComponent(employee.employee_code || 'EMP-' + String(employee.id).padStart(5, '0'));
    qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${qrData}`;
    
    openModal('badgeModal');
}

function downloadBadge() {
    const badge = document.getElementById('printableBadge');
    const employeeCode = document.getElementById('badgeCode').textContent;
    
    if (typeof html2canvas === 'undefined') {
        alert("Download library is still loading. Please try again in a moment.");
        return;
    }
    
    const btn = document.querySelector('#badgeModal button.btn-primary');
    const originalContent = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating...';
    
    // Tiny delay to ensure smooth rendering lifecycle
    setTimeout(() => {
        html2canvas(badge, {
            useCORS: true,
            allowTaint: false,
            scale: 3, // Scale up to 3x for high-res crisp text and QR code
            backgroundColor: null // Keep transparent background behind rounded corners
        }).then(canvas => {
            const link = document.createElement('a');
            link.download = `ID_Badge_${employeeCode}.png`;
            link.href = canvas.toDataURL('image/png');
            link.click();
            
            btn.disabled = false;
            btn.innerHTML = originalContent;
        }).catch(err => {
            console.error("Badge download error:", err);
            alert("Error generating image. Please try again.");
            btn.disabled = false;
            btn.innerHTML = originalContent;
        });
    }, 150);
}

function togglePasswordVisibility(inputId, btn) {
    const input = document.getElementById(inputId);
    const icon = btn.querySelector('i');
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        input.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
}

function resetPasswordInput() {
    const input = document.getElementById('employee_password');
    input.type = 'password';
    const btn = input.nextElementSibling;
    if (btn && btn.querySelector('i')) {
        const icon = btn.querySelector('i');
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
}

function toggleSkillsSection() {
    const roleSelect = document.getElementById('employee_role');
    const roleName = roleSelect.options[roleSelect.selectedIndex].text;
    const skillsSection = document.getElementById('skillsSection');
    skillsSection.style.display = roleName === 'Manager' ? 'none' : 'block';
}

document.getElementById('employee_role').addEventListener('change', toggleSkillsSection);

async function openAddEmployeeModal() {
    document.getElementById('modalTitle').innerText = 'Add New Employee';
    document.getElementById('employeeForm').reset();
    document.getElementById('employee_id').value = '';
    document.getElementById('employee_code_input').value = '';
    document.getElementById('employee_shift').value = '';
    
    // Set Password field to required for Add Employee
    const passInput = document.getElementById('employee_password');
    passInput.required = true;
    passInput.placeholder = 'Password *';
    resetPasswordInput();
    
    document.getElementById('imagePreview').innerHTML = `<i class="fas fa-camera" style="opacity: 0.5;"></i>`;
    
    // Clear checkboxes
    document.querySelectorAll('.skill-checkbox').forEach(cb => cb.checked = false);
    
    toggleSkillsSection();
    openModal('employeeModal');

    // Fetch next employee code dynamically
    try {
        const response = await fetch('api/employees.php?action=get_next_code');
        const data = await response.json();
        if (data.success) {
            document.getElementById('employee_code_input').value = data.employee_code;
        }
    } catch (err) {
        console.error('Error fetching next employee code:', err);
    }
}

function editEmployee(employee) {
    document.getElementById('modalTitle').innerText = 'Edit Employee';
    document.getElementById('employee_id').value = employee.id;
    document.getElementById('employee_code_input').value = employee.employee_code || '';
    document.getElementById('employee_name').value = employee.name;
    document.getElementById('employee_email').value = employee.email;
    document.getElementById('employee_phone').value = employee.phone;
    document.getElementById('employee_nic').value = employee.nic;
    document.getElementById('employee_address').value = employee.address;
    document.getElementById('employee_hourly_rate').value = employee.hourly_rate || '0.00';
    document.getElementById('employee_base_salary').value = employee.base_salary || '0.00';
    document.getElementById('employee_role').value = employee.role_id;
    document.getElementById('employee_dashboard').value = employee.dashboard_id;
    document.getElementById('employee_reporting_manager').value = employee.reporting_manager_id || '';
    document.getElementById('employee_username').value = employee.username || '';
    document.getElementById('employee_shift').value = employee.shift_id || '';
    
    // Set Password field to optional for Edit Employee
    const passInput = document.getElementById('employee_password');
    passInput.required = false;
    passInput.placeholder = 'Password (New)';
    resetPasswordInput();
    
    if (employee.profile_picture) {
        document.getElementById('imagePreview').innerHTML = `<img src="${employee.profile_picture}" style="width:100%; height:100%; object-fit:cover;">`;
    } else {
        document.getElementById('imagePreview').innerHTML = `<i class="fas fa-camera" style="opacity: 0.5;"></i>`;
    }

    // Set checkboxes
    const skillIds = (employee.skill_ids || []).map(id => id.toString());
    document.querySelectorAll('.skill-checkbox').forEach(cb => {
        cb.checked = skillIds.includes(cb.value.toString());
    });
    
    toggleSkillsSection();
    openModal('employeeModal');
}

function previewImage(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('imagePreview').innerHTML = `<img src="${e.target.result}" style="width:100%; height:100%; object-fit:cover;">`;
        };
        reader.readAsDataURL(input.files[0]);
    }
}

document.getElementById('employeeForm').onsubmit = async (e) => {
    e.preventDefault();
    const btn = e.target.querySelector('button[type="submit"]');
    const formData = new FormData(e.target);
    formData.append('action', 'save');
    
    const result = await apiCall('employees', { data: formData, btn: btn });
    if (result.success) {
        notify(result.message);
        setTimeout(() => location.reload(), 1000);
    } else {
        notify(result.message, 'error');
    }
};

async function deleteEmployee(id) {
    if (await confirmAction({ title: 'Delete Employee', message: 'Are you sure you want to delete this employee? This will also remove their system access.' })) {
        const result = await apiCall('employees', { action: 'delete', id: id });
        if (result.success) {
            notify(result.message);
            setTimeout(() => location.reload(), 1000);
        } else {
            notify(result.message, 'error');
        }
    }
}

// Real-time Employee Search
document.getElementById('employeeSearch').addEventListener('input', function(e) {
    const term = e.target.value.toLowerCase();
    const cards = document.querySelectorAll('.data-card');
    let hasResults = false;
    
    cards.forEach(card => {
        const name = card.querySelector('h3').innerText.toLowerCase();
        const role = card.querySelector('.btn[style*="background: rgba(99, 102, 241, 0.1)"]').innerText.toLowerCase();
        const details = card.querySelector('.data-card-body').innerText.toLowerCase();
        
        if (name.includes(term) || role.includes(term) || details.includes(term)) {
            card.style.display = 'flex';
            hasResults = true;
        } else {
            card.style.display = 'none';
        }
    });

    // Handle "No Results" state
    const grid = document.querySelector('.data-grid');
    let noResultsMsg = document.getElementById('noSearchMsg');
    
    if (!hasResults) {
        if (!noResultsMsg) {
            noResultsMsg = document.createElement('div');
            noResultsMsg.id = 'noSearchMsg';
            noResultsMsg.style.cssText = 'grid-column: 1 / -1; text-align: center; padding: 4rem; color: var(--text-muted);';
            noResultsMsg.innerHTML = `
                <i class="fas fa-search-minus fa-3x" style="margin-bottom: 1rem; opacity: 0.5;"></i>
                <h3>No matches found for "${e.target.value}"</h3>
                <p>Try checking the spelling or use a different search term.</p>
            `;
            grid.appendChild(noResultsMsg);
        } else {
            noResultsMsg.querySelector('h3').innerText = `No matches found for "${e.target.value}"`;
        }
    } else if (noResultsMsg) {
        noResultsMsg.remove();
    }
});
</script>
