<?php
// Employee Management Page
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';

require_login();
if (!has_role(['admin','super_admin'])) {
    echo '<div class="alert alert-danger">Access denied</div>';
    exit;
}

$mysqli = db();

// Get branches for dropdown
$branches = $mysqli->query("SELECT id, name FROM branches WHERE is_active = 1 ORDER BY name");
$designations = $mysqli->query("SELECT id, name FROM designations WHERE is_active = 1 ORDER BY name");
?>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="bi bi-people"></i> Employee Management</h2>
        <button class="btn btn-primary" onclick="openAddModal()">
            <i class="bi bi-plus"></i> Add Employee
        </button>
    </div>

    <style>
.table thead.table-dark th,
.table thead th {
    background-color: #212529 !important;
    color: white !important;
    font-weight: 600;
}
#employeesTable thead th {
    background-color: #343a40 !important;
    color: #fff !important;
    font-weight: 600;
    border-bottom: 2px solid #454d55;
}
#employeesTable tbody td {
    vertical-align: middle;
}
</style>

<!-- Filters -->
    <div class="card mb-3">
        <div class="card-body">
            <div class="row">
                <div class="col-md-4">
                    <label class="form-label">Filter by Branch</label>
                    <select class="form-select" id="filterBranch" onchange="loadEmployees()">
                        <option value="">All Branches</option>
                        <?php while ($b = $branches->fetch_assoc()): ?>
                            <option value="<?= $b['id'] ?>"><?= htmlspecialchars($b['name']) ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Search</label>
                    <input type="text" class="form-control" id="searchEmployee" placeholder="Name, Code, Phone..." onkeyup="loadEmployees()">
                </div>
            </div>
        </div>
    </div>

    <!-- Employees Table -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="employeesTable">
                    <thead class="table-dark" style="background-color: #343a40 !important; color: white !important;">
                        <tr>
                            <th>Emp Code</th>
                            <th>Name</th>
                            <th>Designation</th>
                            <th>Branch</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th>Base Salary</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr><td colspan="9" class="text-center">Loading...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add/Edit Employee Modal -->
<div class="modal fade" id="addEmployeeModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="employeeModalTitle"><i class="bi bi-person-plus"></i> Add Employee</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addEmployeeForm" onsubmit="saveEmployee(event)" enctype="multipart/form-data">
                <div class="modal-body">
                    <input type="hidden" name="csrf" value="<?= $_SESSION['csrf_token'] ?>">
                    <input type="hidden" name="id" id="employeeId">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Employee Code *</label>
                                <input type="text" name="emp_code" id="empCode" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Full Name *</label>
                                <input type="text" name="full_name" id="empFullName" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">ID Number (NIC)</label>
                                <input type="text" name="id_no" id="empIdNo" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Phone</label>
                                <input type="text" name="phone" id="empPhone" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Email</label>
                                <input type="email" name="email" id="empEmail" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Address</label>
                                <textarea name="address" id="empAddress" class="form-control" rows="2"></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Joined Date</label>
                                <input type="date" name="joined_date" id="empJoinedDate" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Resigned Date</label>
                                <input type="date" name="resigned_date" id="empResignedDate" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Branch</label>
                                <select name="branch_id" id="empBranchId" class="form-select">
                                    <option value="">Select Branch</option>
                                    <?php 
                                    $branches->data_seek(0);
                                    while ($b = $branches->fetch_assoc()): 
                                    ?>
                                        <option value="<?= $b['id'] ?>"><?= htmlspecialchars($b['name']) ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Designation</label>
                                <select name="designation_id" id="empDesignationId" class="form-select">
                                    <option value="">Select Designation</option>
                                    <?php 
                                    $designations->data_seek(0);
                                    while ($d = $designations->fetch_assoc()): 
                                    ?>
                                        <option value="<?= $d['id'] ?>"><?= htmlspecialchars($d['name']) ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Base Salary (LKR)</label>
                                <input type="number" name="base_salary" id="empBaseSalary" class="form-control" step="0.01" min="0">
                            </div>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input type="checkbox" name="is_active" id="empIsActive" class="form-check-input" value="1" checked>
                                    <label class="form-check-label">Active</label>
                                </div>
                            </div>
                            <hr class="my-2">
                            <h6 class="text-primary"><i class="bi bi-building"></i> Payroll Details</h6>
                            <div class="mb-3">
                                <label class="form-label">EPF Number</label>
                                <input type="text" name="epf_no" id="empEpfNo" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">ETF Number</label>
                                <input type="text" name="etf_no" id="empEtfNo" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Tax Number (TIN)</label>
                                <input type="text" name="tax_no" id="empTaxNo" class="form-control">
                            </div>
                        </div>
                    </div>
                    <hr class="my-2">
                    <h6 class="text-success"><i class="bi bi-bank"></i> Bank Details</h6>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Bank Name</label>
                                <input type="text" name="bank_name" id="empBankName" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Branch</label>
                                <input type="text" name="bank_branch" id="empBankBranch" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Account Number</label>
                                <input type="text" name="bank_account" id="empBankAccount" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Account Name</label>
                                <input type="text" name="account_name" id="empAccountName" class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Payment Method</label>
                        <select name="payment_method" id="empPaymentMethod" class="form-select">
                            <option value="bank_transfer">Bank Transfer</option>
                            <option value="cash">Cash</option>
                            <option value="cheque">Cheque</option>
                        </select>
                    </div>
                    <hr class="my-2">
                    <div class="mb-3">
                        <label class="form-label">ID Card Image</label>
                        <input type="file" name="id_copy" id="empIdCopy" class="form-control" accept="image/*">
                        <div id="idCardPreview" class="mt-2" style="display:none;">
                            <img src="" alt="ID Card" class="img-thumbnail" style="max-height: 150px;">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="saveBtn">Save Employee</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function loadEmployees() {
    const branchId = $('#filterBranch').val();
    const search = $('#searchEmployee').val();
    
    $.get('api/employees.php', { 
        action: 'list',
        branch_id: branchId
    }, function(res) {
        let html = '';
        const searchLower = search.toLowerCase();
        
        res.data.forEach(emp => {
            // Filter by search
            if (search && !emp.full_name.toLowerCase().includes(searchLower) && 
                !emp.emp_code.toLowerCase().includes(searchLower) &&
                !(emp.phone || '').toLowerCase().includes(searchLower)) {
                return;
            }
            
            const isActive = parseInt(emp.is_active) === 1;
            const statusBadge = isActive 
                ? '<span class="badge bg-success">Active</span>'
                : '<span class="badge bg-secondary">Inactive</span>';
            
            html += `<tr>
                <td><strong>${emp.emp_code}</strong></td>
                <td>${emp.full_name}</td>
                <td>${emp.designation_name || emp.designation || '-'}</td>
                <td>${emp.branch_name || '-'}</td>
                <td>${emp.phone || '-'}</td>
                <td>${emp.email || '-'}</td>
                <td>${emp.base_salary ? fmt(emp.base_salary) : '-'}</td>
                <td>${statusBadge}</td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary" onclick="editEmployee(${emp.id})" title="Edit">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-outline-${isActive ? 'warning' : 'success'}" onclick="toggleEmployeeStatus(${emp.id}, ${isActive ? 1 : 0})" title="${isActive ? 'Deactivate' : 'Activate'}">
                            ${isActive ? '<i class="bi bi-pause-fill"></i>' : '<i class="bi bi-play-fill"></i>'}
                        </button>
                    </div>
                </td>
            </tr>`;
        });
        
        $('#employeesTable tbody').html(html || '<tr><td colspan="9" class="text-center">No employees found</td></tr>');
    });
}

let editingId = null;

function openAddModal() {
    editingId = null;
    $('#employeeModalTitle').html('<i class="bi bi-person-plus"></i> Add Employee');
    $('#saveBtn').text('Save Employee');
    $('#addEmployeeForm')[0].reset();
    $('#employeeId').val('');
    $('#idCardPreview').hide();
    generateEmpCode();
    $('#addEmployeeModal').modal('show');
}

function generateEmpCode() {
    $.get('api/employees.php', { action: 'generate_code' }, function(res) {
        $('#empCode').val(res.code);
    });
}

function saveEmployee(e) {
    e.preventDefault();
    const formData = new FormData(e.target);
    const form = e.target;
    
    const action = editingId ? 'update' : 'create';
    if (editingId) {
        formData.append('id', editingId);
    }
    
    $.ajax({
        url: 'api/employees.php?action=' + action,
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(res) {
            alert(res.message);
            if (res.message.includes('success') || res.message.includes('Updated') || res.message.includes('successfully')) {
                $('#addEmployeeModal').modal('hide');
                form.reset();
                $('#idCardPreview').hide();
                editingId = null;
                $('#employeeModalTitle').html('<i class="bi bi-person-plus"></i> Add Employee');
                $('#saveBtn').text('Save Employee');
                // Reload employee list immediately
                loadEmployees();
            }
        },
        error: function(xhr) {
            alert('Error: ' + (xhr.responseJSON?.message || 'Failed to save'));
        }
    });
}

function editEmployee(id) {
    editingId = id;
    $('#employeeModalTitle').html('<i class="bi bi-pencil"></i> Edit Employee');
    $('#saveBtn').text('Update Employee');
    
    $.get('api/employees.php', { action: 'get', id: id }, function(res) {
        if (res.data) {
            const emp = res.data;
            $('#empCode').val(emp.emp_code);
            $('#empFullName').val(emp.full_name);
            $('#empPhone').val(emp.phone || '');
            $('#empEmail').val(emp.email || '');
            $('#empIdNo').val(emp.id_no || '');
            $('#empBaseSalary').val(emp.base_salary || 0);
            $('#empAddress').val(emp.address || '');
            $('#empBranchId').val(emp.branch_id || '');
            $('#empDesignationId').val(emp.designation_id || '');
            $('#empIsActive').prop('checked', emp.is_active == 1);
            $('#employeeId').val(emp.id);
            
            // Payroll fields
            $('#empEpfNo').val(emp.epf_no || '');
            $('#empEtfNo').val(emp.etf_no || '');
            $('#empTaxNo').val(emp.tax_no || '');
            
            // Bank fields
            $('#empBankName').val(emp.bank_name || '');
            $('#empBankBranch').val(emp.bank_branch || '');
            $('#empBankAccount').val(emp.bank_account || '');
            $('#empAccountName').val(emp.account_name || '');
            $('#empPaymentMethod').val(emp.payment_method || 'bank_transfer');
            
            // Dates
            $('#empJoinedDate').val(emp.joined_date || '');
            $('#empResignedDate').val(emp.resigned_date || '');
            
            // Show ID card preview if exists
            if (emp.id_copy_path) {
                $('#idCardPreview img').attr('src', emp.id_copy_path);
                $('#idCardPreview').show();
            } else {
                $('#idCardPreview').hide();
            }
            
            $('#addEmployeeModal').modal('show');
        }
    });
}

function toggleEmployeeStatus(id, currentStatus) {
    const actionText = currentStatus ? 'Deactivate' : 'Activate';
    if (!confirm(`Are you sure you want to ${actionText} this employee?`)) return;
    
    // Get CSRF token from the hidden input
    const csrfToken = document.querySelector('input[name="csrf"]').value;
    
    // First get current data
    $.get('api/employees.php', { action: 'get', id: id }, function(res) {
        if (res.data) {
            const emp = res.data;
            const formData = new FormData();
            formData.append('csrf', csrfToken);
            formData.append('id', id);
            formData.append('emp_code', emp.emp_code);
            formData.append('full_name', emp.full_name);
            formData.append('phone', emp.phone || '');
            formData.append('email', emp.email || '');
            formData.append('id_no', emp.id_no || '');
            formData.append('address', emp.address || '');
            formData.append('branch_id', emp.branch_id || '');
            formData.append('designation', emp.designation || '');
            formData.append('designation_id', emp.designation_id || '');
            formData.append('base_salary', emp.base_salary || 0);
            formData.append('is_active', currentStatus ? 0 : 1);
            
            $.ajax({
                url: 'api/employees.php?action=update',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(res) {
                    alert(res.message);
                    loadEmployees();
                },
                error: function(xhr) {
                    alert('Error: ' + (xhr.responseJSON?.message || 'Failed to update status'));
                }
            });
        }
    }).fail(function() {
        alert('Error: Could not fetch employee data');
    });
}

// Preview uploaded image
$('#empIdCopy').on('change', function() {
    const file = this.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            $('#idCardPreview img').attr('src', e.target.result);
            $('#idCardPreview').show();
        };
        reader.readAsDataURL(file);
    }
});

function fmt(amount) {
    return 'LKR ' + parseFloat(amount).toLocaleString('en-LK', {minimumFractionDigits: 2, maximumFractionDigits: 2});
}

// Load on page load
$(function() {
    loadEmployees();
});
</script>
