<?php
require_once 'includes/db.php';
$employees = fetchAll("SELECT e.*, r.name as role_name FROM employees e LEFT JOIN roles r ON e.role_id = r.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");
?>

<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: EMP-<?php echo str_pad($employee['id'], 4, '0', STR_PAD_LEFT); ?></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);">
                    <i class="fas fa-clock"></i>
                    <span>Hourly Rate: LKR <?php echo number_format($employee['hourly_rate'], 2); ?></span>
                </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;" 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(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 1fr 1fr; 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;">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; 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 (LKR) <span class="required-mark">*</span></label>
                        <div style="position: relative;">
                            <span style="position: absolute; left: 0.75rem; top: 50%; transform: translateY(-50%); font-weight: 700; color: var(--text-muted); font-size: 0.75rem;">LKR</span>
                            <input type="number" step="0.01" id="employee_hourly_rate" name="hourly_rate" class="form-control" style="padding: 0.5rem 0.5rem 0.5rem 3rem;" required>
                        </div>
                    </div>
                </div>

                <!-- Third Row: Address & Roles -->
                <div style="display: grid; grid-template-columns: 1.5fr 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: 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;">
                            </div>
                            <div class="form-group" style="margin-bottom: 0;">
                                <input type="password" id="employee_password" name="password" class="form-control" placeholder="Password (New)" style="padding: 0.4rem; font-size: 0.8rem;">
                            </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>

<script>
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);

function openAddEmployeeModal() {
    document.getElementById('modalTitle').innerText = 'Add New Employee';
    document.getElementById('employeeForm').reset();
    document.getElementById('employee_id').value = '';
    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');
}

function editEmployee(employee) {
    document.getElementById('modalTitle').innerText = 'Edit Employee';
    document.getElementById('employee_id').value = employee.id;
    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_role').value = employee.role_id;
    document.getElementById('employee_dashboard').value = employee.dashboard_id;
    document.getElementById('employee_username').value = employee.username || '';
    
    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>
