<?php
require_once __DIR__ . '/../../templates/header.php';

// Lấy danh sách nhân viên để hiển thị ở Tab 1
$sql_users = "SELECT id, username, display_name, salary_base, allowance, commission, phone, bank_name, bank_account 
              FROM cms_users WHERE user_status = 1 ORDER BY id ASC";
$employees = $conn->query($sql_users)->fetch_all(MYSQLI_ASSOC);
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Quản lý Lương & Hoa hồng</h1>

    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <ul class="nav nav-tabs card-header-tabs" id="payrollTabs" role="tablist">
                <li class="nav-item">
                    <button class="nav-link active" id="setup-tab" data-bs-toggle="tab" data-bs-target="#setup" type="button" role="tab"><i class="fas fa-cog me-2"></i>Cấu hình Lương</button>
                </li>
                <li class="nav-item">
                    <button class="nav-link" id="calc-tab" data-bs-toggle="tab" data-bs-target="#calc" type="button" role="tab"><i class="fas fa-calculator me-2"></i>Bảng Lương</button>
                </li>
            </ul>
        </div>
        <div class="card-body">
            <div class="tab-content" id="payrollTabsContent">
                
                <div class="tab-pane fade show active" id="setup" role="tabpanel">
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover" id="tableSalarySetup" width="100%">
                            <thead class="table-primary">
                                <tr>
                                    <th>Nhân viên</th>
                                    <th>Lương cứng (VNĐ)</th>
                                    <th>Phụ cấp (VNĐ)</th>
                                    <th>Hoa hồng (%)</th>
                                    <th>Thông tin NH</th>
                                    <th class="text-center">Lưu</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($employees as $emp): ?>
                                <tr id="row-<?php echo $emp['id']; ?>">
                                    <td>
                                        <div class="fw-bold"><?php echo htmlspecialchars($emp['display_name']); ?></div>
                                        <small class="text-muted"><?php echo htmlspecialchars($emp['username']); ?></small>
                                        <input type="text" class="form-control form-control-sm mt-1" placeholder="SĐT" value="<?php echo htmlspecialchars($emp['phone'] ?? ''); ?>" id="phone_<?php echo $emp['id']; ?>">
                                    </td>
                                    <td>
                                        <input type="text" class="form-control currency-input" value="<?php echo number_format($emp['salary_base']); ?>" id="salary_<?php echo $emp['id']; ?>">
                                    </td>
                                    <td>
                                        <input type="text" class="form-control currency-input" value="<?php echo number_format($emp['allowance']); ?>" id="allowance_<?php echo $emp['id']; ?>">
                                    </td>
                                    <td>
                                        <div class="input-group">
                                            <input type="number" step="0.1" class="form-control" value="<?php echo $emp['commission']; ?>" id="comm_<?php echo $emp['id']; ?>">
                                            <span class="input-group-text">%</span>
                                        </div>
                                    </td>
                                    <td>
                                        <input type="text" class="form-control form-control-sm mb-1" placeholder="Tên Ngân hàng" value="<?php echo htmlspecialchars($emp['bank_name'] ?? ''); ?>" id="bank_name_<?php echo $emp['id']; ?>">
                                        <input type="text" class="form-control form-control-sm" placeholder="Số tài khoản" value="<?php echo htmlspecialchars($emp['bank_account'] ?? ''); ?>" id="bank_acc_<?php echo $emp['id']; ?>">
                                    </td>
                                    <td class="text-center align-middle">
                                        <button class="btn btn-success btn-sm btn-save-setup" data-id="<?php echo $emp['id']; ?>">
                                            <i class="fas fa-save"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="tab-pane fade" id="calc" role="tabpanel">
                    <div class="row mb-4 align-items-end">
                        <div class="col-md-3">
                            <label class="form-label fw-bold">Tháng / Năm</label>
                            <input type="month" class="form-control" id="payroll_month" value="<?php echo date('Y-m'); ?>">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold">Nhân viên</label>
                            <select class="form-select" id="payroll_user_id">
                                <option value="all">-- Tất cả nhân viên --</option>
                                <?php foreach ($employees as $emp): ?>
                                <option value="<?php echo $emp['id']; ?>"><?php echo $emp['display_name']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <button class="btn btn-primary me-2" id="btnCalculate"><i class="fas fa-search me-1"></i> Tính lương</button>
                            <button class="btn btn-success" id="btnExportExcel"><i class="fas fa-file-excel me-1"></i> Xuất Excel</button>
                        </div>
                    </div>

                    <div id="payrollResult">
                        <div class="alert alert-info text-center">Vui lòng chọn thời gian và bấm "Tính lương"</div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>

<script>
$(document).ready(function() {
    // 1. FORMAT TIỀN TỆ KHI NHẬP LIỆU
    $('.currency-input').on('keyup', function() {
        let val = $(this).val().replace(/\D/g, "");
        $(this).val(new Intl.NumberFormat('vi-VN').format(val));
    });

    // 2. LƯU CẤU HÌNH LƯƠNG (AJAX)
    $('.btn-save-setup').click(function() {
        let id = $(this).data('id');
        let salary = $('#salary_' + id).val().replace(/\./g, '');
        let allowance = $('#allowance_' + id).val().replace(/\./g, '');
        let commission = $('#comm_' + id).val();
        let phone = $('#phone_' + id).val();
        let bank_name = $('#bank_name_' + id).val();
        let bank_acc = $('#bank_acc_' + id).val();

        $.post('/quanlybanhang/ajax/payroll_ajax.php', {
            action: 'save_config',
            user_id: id,
            salary_base: salary,
            allowance: allowance,
            commission: commission,
            phone: phone,
            bank_name: bank_name,
            bank_account: bank_acc
        }, function(res) {
            alert(res.message);
        }, 'json');
    });

    // 3. TÍNH LƯƠNG (AJAX)
    $('#btnCalculate').click(function() {
        let month = $('#payroll_month').val();
        let user_id = $('#payroll_user_id').val();
        
        $('#payrollResult').html('<div class="text-center py-4"><div class="spinner-border text-primary"></div><p>Đang tính toán...</p></div>');

        $.post('/quanlybanhang/ajax/payroll_ajax.php', {
            action: 'calculate',
            month: month,
            user_id: user_id
        }, function(res) {
            if(res.status === 'success') {
                renderPayrollTable(res.data);
            } else {
                $('#payrollResult').html('<div class="alert alert-danger">'+res.message+'</div>');
            }
        }, 'json');
    });

    // 4. XUẤT EXCEL
    $('#btnExportExcel').click(function() {
        let month = $('#payroll_month').val();
        let user_id = $('#payroll_user_id').val();
        window.location.href = `/quanlybanhang/modules/payroll/export_excel.php?month=${month}&user_id=${user_id}`;
    });

    function renderPayrollTable(data) {
        if(data.length === 0) {
            $('#payrollResult').html('<div class="alert alert-warning text-center">Không có dữ liệu cho tháng này.</div>');
            return;
        }

        let html = `
        <div class="table-responsive">
            <table class="table table-bordered table-striped">
                <thead class="bg-dark text-white">
                    <tr>
                        <th>Nhân viên</th>
                        <th class="text-end">Lương cứng</th>
                        <th class="text-end">Phụ cấp</th>
                        <th class="text-end">Doanh số</th>
                        <th class="text-end">Lợi nhuận</th>
                        <th class="text-center">% HH</th>
                        <th class="text-end">Tiền Hoa hồng</th>
                        <th class="text-end bg-primary text-white">TỔNG THỰC LĨNH</th>
                    </tr>
                </thead>
                <tbody>`;
        
        let totalAll = 0;

        data.forEach(item => {
            totalAll += parseFloat(item.total_salary);
            html += `
            <tr>
                <td>
                    <b>${item.name}</b><br>
                    <small>${item.bank_name} - ${item.bank_account}</small>
                </td>
                <td class="text-end">${new Intl.NumberFormat('vi-VN').format(item.salary_base)}</td>
                <td class="text-end">${new Intl.NumberFormat('vi-VN').format(item.allowance)}</td>
                <td class="text-end text-muted">${new Intl.NumberFormat('vi-VN').format(item.sales)}</td>
                <td class="text-end text-success fw-bold">${new Intl.NumberFormat('vi-VN').format(item.profit)}</td>
                <td class="text-center">${item.commission_rate}%</td>
                <td class="text-end fw-bold text-warning">${new Intl.NumberFormat('vi-VN').format(item.commission_money)}</td>
                <td class="text-end fw-bold text-primary fs-5">${new Intl.NumberFormat('vi-VN').format(item.total_salary)}</td>
            </tr>`;
        });

        html += `
            <tr class="fw-bold fs-5 bg-light">
                <td colspan="7" class="text-end">TỔNG CHI LƯƠNG THÁNG:</td>
                <td class="text-end text-danger">${new Intl.NumberFormat('vi-VN').format(totalAll)} đ</td>
            </tr>
            </tbody></table></div>`;
        
        $('#payrollResult').html(html);
    }
});
</script>