<?php echo message_box('success'); ?>
<?php echo message_box('error'); ?>
<?php
$department_options = array('' => lang('select_department'));
if (!empty($all_department_info)) {
    foreach ($all_department_info as $v_department_info) {
        if (!empty($v_department_info->deptname)) {
            $deptname = $v_department_info->deptname;
        } else {
            $deptname = lang('undefined_department');
        }
        $department_options[$v_department_info->departments_id] = $deptname;
    }
}
?>

<div class="space-y-4">
    <div class="rounded-2xl border border-border bg-card shadow-sm">
        <div class="border-b border-border px-5 py-4">
            <div class="flex items-center gap-2 text-sm font-semibold text-foreground">
                <i data-lucide="receipt" class="h-5 w-5"></i>
                <span><?= lang('generate_payslip') ?></span>
            </div>
        </div>
        <div class="p-5">
            <form id="form" role="form" enctype="multipart/form-data"
                action="<?php echo base_url() ?>admin/payroll/generate_payslip" method="post"
                class="space-y-4">
                <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                    <?= form_select_group('departments_id', lang('select_department'), $department_options, !empty($departments_id) ? $departments_id : '', true, array('class' => 'select_box')); ?>
                    <?= form_datepicker('payment_month', lang('select') . ' ' . lang('month'), !empty($payment_month) ? $payment_month : '', true, array('class' => 'monthyear', 'data-type' => 'month', 'data-format' => 'Y-m', 'data-auto-close' => 'true')); ?>
                </div>
                <div class="flex justify-end">
                    <button id="submit" type="submit" name="flag" value="1"
                        class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-xs font-semibold text-white shadow-sm hover:bg-indigo-500">
                        <i data-lucide="arrow-right" class="h-4 w-4"></i>
                        <?= lang('go') ?>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <?php if (!empty($flag)): ?>
        <div class="rounded-2xl border border-border bg-card shadow-sm">
            <div class="border-b border-border px-5 py-4">
                <div class="flex flex-wrap items-center justify-between gap-2 text-sm font-semibold text-foreground">
                    <span><?= lang('generate_payslip_for') ?>
                        <?php
                        if (!empty($payment_month)) {
                            echo ' <span class="text-muted-foreground">' . date('F Y', safe_strtotime($payment_month)) . '</span>';
                        }
                        ?>
                    </span>
                </div>
            </div>
            <div class="p-5">
                <form id="bulkPayrollForm" action="<?= base_url('admin/payroll/bulk_generate_payslip') ?>" method="post" class="space-y-4">
                    <input type="hidden" name="departments_id" value="<?= html_escape($departments_id) ?>">
                    <input type="hidden" name="payment_month" value="<?= html_escape($payment_month) ?>">
                    <div class="rounded-2xl border border-border bg-muted/20 p-4">
                        <div class="grid grid-cols-1 gap-4 lg:grid-cols-12">
                            <div class="lg:col-span-3 space-y-1">
                                <label class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('payment_method') ?></label>
                                <select name="payment_type" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm text-foreground select_box">
                                    <option value=""><?= lang('select') . ' ' . lang('payment_method') ?></option>
                                    <?php
                                    if (!empty($all_payment_method)) {
                                        foreach ($all_payment_method as $v_payment_method) { ?>
                                            <option value="<?= $v_payment_method->payment_methods_id ?>"><?= $v_payment_method->method_name ?></option>
                                        <?php }
                                    } ?>
                                </select>
                            </div>
                            <div class="lg:col-span-3 space-y-1">
                                <label class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('fine_deduction') ?></label>
                                <input type="number" step="0.01" min="0" name="fine_deduction" value="0" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm text-foreground">
                            </div>
                            <div class="lg:col-span-4 space-y-1">
                                <label class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('comments') ?></label>
                                <input type="text" name="comments" class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm text-foreground">
                            </div>
                            <div class="lg:col-span-2 space-y-1">
                                <label class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('account') ?></label>
                                <?php
                                $selected_account_id = config_item('default_account');
                                $selected_account_label = '';
                                if (!empty($selected_account_id)) {
                                    $selected_account_label = get_row('tbl_accounts', array('account_id' => $selected_account_id), 'account_name');
                                }
                                echo form_lookup_group(
                                    'account_id',
                                    '',
                                    $selected_account_id,
                                    $selected_account_label,
                                    false,
                                    array(),
                                    '',
                                    array('type' => 'account')
                                );
                                ?>
                            </div>
                        </div>
                            <div class="mt-4 flex flex-wrap items-center justify-between gap-3">
                                <label class="inline-flex items-center gap-2 text-sm font-medium text-foreground">
                                <input type="checkbox" id="selectAllEmployees" class="h-4 w-4 rounded border-border text-primary focus:ring-primary/30">
                                <span>Select all</span>
                                </label>
                                <div class="flex items-center gap-3 text-sm text-muted-foreground">
                                <span><span id="selectedEmployeeCount">0</span> selected</span>
                                <span><span id="selectedEmployeeAmount">0.00</span></span>
                                </div>
                                <label class="inline-flex items-center gap-2 text-sm text-foreground">
                                <input type="checkbox" class="h-4 w-4 rounded border-border text-primary focus:ring-primary/30" checked name="deduct_from_account" value="1">
                                <span><?= lang('deduct_from_default_account') ?></span>
                            </label>
                            <button id="bulkPayrollSubmit" type="submit" class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-xs font-semibold text-white shadow-sm hover:bg-indigo-500">
                                <i data-lucide="wallet" class="h-4 w-4"></i>
                                Bulk pay
                            </button>
                        </div>
                        <div id="bulkPayrollProgress" class="mt-4 hidden rounded-xl border border-border bg-background p-4">
                            <div class="flex items-center justify-between gap-3">
                                <div>
                                    <div class="text-sm font-semibold text-foreground">Processing bulk payroll</div>
                                    <div id="bulkPayrollProgressText" class="text-xs text-muted-foreground">Waiting to start</div>
                                </div>
                                <div id="bulkPayrollProgressDetail" class="text-sm font-medium text-foreground">0 / 0</div>
                            </div>
                            <div class="mt-3 h-2 overflow-hidden rounded-full bg-muted">
                                <div id="bulkPayrollProgressBar" class="h-full w-0 rounded-full bg-indigo-600 transition-all duration-300"></div>
                            </div>
                            <div id="bulkPayrollProgressLog" class="mt-2 text-xs text-muted-foreground"></div>
                        </div>
                    </div>
                    <div class="overflow-x-auto rounded-xl border border-border">
                        <table class="min-w-full text-sm" id="datatable_action" cellspacing="0" width="100%">
                            <thead class="bg-muted/40 text-xs uppercase tracking-wide text-muted-foreground">
                            <tr>
                                <th class="px-4 py-3 text-left w-12"><span class="sr-only"><?= lang('select') ?></span></th>
                                <th class="px-4 py-3 text-left"><?= lang('emp_id') ?></th>
                                <th class="px-4 py-3 text-left"><strong><?= lang('name') ?></strong></th>
                                <th class="px-4 py-3 text-left"><strong><?= lang('salary_type') ?></strong></th>
                                <th class="px-4 py-3 text-left"><strong><?= lang('basic_salary') ?></strong></th>
                                <th class="px-4 py-3 text-left"><strong><?= lang('net_salary') ?></strong></th>
                                <th class="px-4 py-3 text-left"><strong><?= lang('details') ?></strong></th>
                                <th class="px-4 py-3 text-left"><strong><?= lang('status') ?></strong></th>
                            </tr>
                            </thead>
                            <tbody class="divide-y divide-border bg-background [&>tr>td]:px-4 [&>tr>td]:py-3">
                            <?php
                            if (!empty($employee_rows)) : foreach ($employee_rows as $v_employee) :
                                    $set_salary = false;
                                    $salary_info = !empty($salary_payment_map[$v_employee->user_id]) ? $salary_payment_map[$v_employee->user_id] : null;
                                    $salary_type_label = '-';
                                    if (!empty($v_employee->salary_grade)) {
                                        $salary_type_label = $v_employee->salary_grade . ' <small>(' . lang('monthly') . ')</small>';
                                    } elseif (!empty($v_employee->hourly_grade)) {
                                        $salary_type_label = $v_employee->hourly_grade . ' <small>(' . lang('hourly') . ')</small>';
                                    } else {
                                        $salary_type_label = '<span class="text-rose-600 dark:text-rose-300">' . lang('did_not_set_salary_yet') . '</span>';
                                        $set_salary = true;
                                    }
                                    $basic_salary = !empty($v_employee->basic_salary) ? (float) $v_employee->basic_salary : 0;
                                    $total_allowance = 0;
                                    $total_deduction = 0;
                                    $total_advance = 0;
                                    $total_award = 0;
                                    $total_amount = 0;
                                    $net_salary_amount = 0;
                                    if (!empty($total_hours[$v_employee->user_id])) {
                                        $total_hour = $total_hours[$v_employee->user_id]['total_hours'];
                                        $total_minutes = $total_hours[$v_employee->user_id]['total_minutes'];
                                        $hours_ammount = ($total_hour > 0) ? $total_hour * $v_employee->hourly_rate : 0;
                                        $minutes_ammount = ($total_minutes > 0) ? $total_minutes * round($v_employee->hourly_rate / 60, 2) : 0;
                                        $total_advance = !empty($advance_salary[$v_employee->user_id]) ? $advance_salary[$v_employee->user_id]['advance_amount'] : 0;
                                        $total_award = !empty($award_info[$v_employee->user_id]) ? $award_info[$v_employee->user_id]['award_amount'] : 0;
                                        $total_amount = $hours_ammount + $minutes_ammount + $total_award - $total_advance;
                                        $net_salary_amount = $total_amount;
                                    } elseif (!empty($v_employee->basic_salary)) {
                                        if (!empty($allowance_info[$v_employee->user_id])) {
                                            $total_allowance = $allowance_info[$v_employee->user_id];
                                        }
                                        if (!empty($deduction_info[$v_employee->user_id])) {
                                            $total_deduction = $deduction_info[$v_employee->user_id];
                                        }
                                        if (!empty($advance_salary[$v_employee->user_id])) {
                                            $total_advance = $advance_salary[$v_employee->user_id]['advance_amount'];
                                        }
                                        if (!empty($award_info[$v_employee->user_id])) {
                                            $total_award = $award_info[$v_employee->user_id]['award_amount'];
                                        }
                                        if (!empty($overtime_info[$v_employee->user_id]) && !empty($v_employee->overtime_salary)) {
                                            $total_hour = $overtime_info[$v_employee->user_id]['overtime_hours'];
                                            $total_minutes = $overtime_info[$v_employee->user_id]['overtime_minutes'];
                                            $hours_ammount = ($total_hour > 0) ? $total_hour * $v_employee->overtime_salary : 0;
                                            $minutes_ammount = ($total_minutes > 0) ? $total_minutes * round($v_employee->overtime_salary / 60, 2) : 0;
                                            $total_amount = $hours_ammount + $minutes_ammount;
                                        }
                                        $net_salary_amount = $basic_salary + $total_allowance + $total_amount + $total_award - $total_deduction - $total_advance;
                                    }
                                    ?>
                                    <tr id="employee-row-<?= $v_employee->user_id ?>" data-user-id="<?= $v_employee->user_id ?>" data-payable="<?= number_format((float) $net_salary_amount, 2, '.', '') ?>">
                                        <td>
                                            <?php if (empty($salary_info) && empty($set_salary)) : ?>
                                                <input type="checkbox" name="selected_users[]" value="<?= $v_employee->user_id ?>" class="employee-check h-4 w-4 rounded border-border text-primary focus:ring-primary/30">
                                            <?php else: ?>
                                                <input type="checkbox" disabled class="h-4 w-4 rounded border-border text-muted-foreground">
                                            <?php endif; ?>
                                        </td>
                                        <td><?= html_escape($v_employee->employment_id) ?></td>
                                        <td>
                                            <?= btn_modal(
                                                !empty($salary_info) ? 'admin/payroll/salary_payment_details/' . $salary_info->salary_payment_id : 'admin/payroll/view_payment_details/' . $v_employee->user_id . '/' . $payment_month,
                                                html_escape($v_employee->fullname),
                                                lang('view'),
                                                'lg',
                                                false,
                                                array('class' => 'text-primary hover:underline mb-0')
                                            ) ?>
                                        </td>
                                        <td><?= $salary_type_label ?></td>
                                        <td><?= !empty($v_employee->basic_salary) ? display_money($v_employee->basic_salary) : (!empty($v_employee->hourly_grade) ? display_money($v_employee->hourly_rate) . ' <small>(' . lang('per_hour') . ')</small>' : '-') ?></td>
                                        <td class="font-semibold text-foreground"><?= display_money($net_salary_amount) ?></td>
                                        <td>
                                            <?= btn_modal(
                                                !empty($salary_info) ? 'admin/payroll/salary_payment_details/' . $salary_info->salary_payment_id : 'admin/payroll/view_payment_details/' . $v_employee->user_id . '/' . $payment_month,
                                                '',
                                                lang('view'),
                                                'lg',
                                                'eye',
                                                array('class' => 'inline-flex items-center justify-center rounded-lg border border-slate-200 bg-slate-50 p-2 text-slate-600 hover:bg-slate-100 h-7 mb-0')
                                            ) ?>
                                        </td>
                                        <td class="employee-payment-status">
                                            <?php if (!empty($salary_info) && $salary_info->user_id == $v_employee->user_id) { ?>
                                                <span class="inline-flex items-center rounded-full bg-emerald-500/15 px-2 py-0.5 text-xs font-semibold text-emerald-700 dark:text-emerald-300"><?= lang('paid') ?></span>
                                            <?php } elseif (empty($set_salary)) { ?>
                                                <span class="inline-flex items-center rounded-full bg-amber-500/15 px-2 py-0.5 text-xs font-semibold text-amber-700 dark:text-amber-300">Pending</span>
                                            <?php } else { ?>
                                                <span class="inline-flex items-center rounded-full bg-rose-500/15 px-2 py-0.5 text-xs font-semibold text-rose-700 dark:text-rose-300">Not set</span>
                                            <?php } ?>
                                        </td>
                                    </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>
</div>

<script type="text/javascript">
    (function () {
        var form = document.getElementById('bulkPayrollForm');
        if (!form) {
            return;
        }

        var selectAll = document.getElementById('selectAllEmployees');
        var selectedCount = document.getElementById('selectedEmployeeCount');
        var selectedAmount = document.getElementById('selectedEmployeeAmount');
        var submitButton = document.getElementById('bulkPayrollSubmit');
        var progressBox = document.getElementById('bulkPayrollProgress');
        var progressText = document.getElementById('bulkPayrollProgressText');
        var progressDetail = document.getElementById('bulkPayrollProgressDetail');
        var progressBar = document.getElementById('bulkPayrollProgressBar');
        var progressLog = document.getElementById('bulkPayrollProgressLog');
        var ajaxUrl = '<?= base_url('admin/payroll/bulk_generate_payslip_process') ?>';

        function checks() {
            return Array.prototype.slice.call(form.querySelectorAll('.employee-check:not(:disabled)'));
        }

        function updateBulkSummary() {
            var total = 0;
            var count = 0;
            checks().forEach(function (checkbox) {
                if (checkbox.checked) {
                    count++;
                    var row = checkbox.closest('tr');
                    if (row) {
                        total += parseFloat(row.getAttribute('data-payable') || '0');
                    }
                }
            });

            if (selectedCount) {
                selectedCount.textContent = count;
            }
            if (selectedAmount) {
                selectedAmount.textContent = total.toFixed(2);
            }
            if (selectAll) {
                var enabled = checks();
                selectAll.checked = enabled.length > 0 && enabled.every(function (checkbox) {
                    return checkbox.checked;
                });
            }
        }

        function setProgress(done, total, text, log) {
            if (progressBox) {
                progressBox.classList.remove('hidden');
            }
            if (progressText) {
                progressText.textContent = text || 'Processing bulk payroll';
            }
            if (progressDetail) {
                progressDetail.textContent = done + ' / ' + total;
            }
            if (progressBar) {
                var percent = total > 0 ? Math.round((done / total) * 100) : 0;
                progressBar.style.width = percent + '%';
            }
            if (progressLog) {
                progressLog.textContent = log || '';
            }
        }

        function markRow(userId, result) {
            var row = form.querySelector('tr[data-user-id="' + userId + '"]');
            if (!row) {
                return;
            }
            var statusCell = row.querySelector('.employee-payment-status');
            var checkbox = row.querySelector('.employee-check');

            if (result && result.status) {
                row.classList.add('opacity-70');
                if (checkbox) {
                    checkbox.checked = false;
                    checkbox.disabled = true;
                }
                if (statusCell) {
                    statusCell.innerHTML = '<span class="inline-flex items-center rounded-full bg-emerald-500/15 px-2 py-0.5 text-xs font-semibold text-emerald-700 dark:text-emerald-300">Paid</span>';
                }
            } else if (result && result.skipped) {
                if (statusCell) {
                    statusCell.innerHTML = '<span class="inline-flex items-center rounded-full bg-amber-500/15 px-2 py-0.5 text-xs font-semibold text-amber-700 dark:text-amber-300">Skipped</span>';
                }
            } else if (statusCell) {
                statusCell.innerHTML = '<span class="inline-flex items-center rounded-full bg-rose-500/15 px-2 py-0.5 text-xs font-semibold text-rose-700 dark:text-rose-300">Failed</span>';
            }
        }

        async function processEmployee(userId) {
            var fd = new FormData(form);
            fd.delete('selected_users[]');
            fd.append('user_id', userId);
            var response = await fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                body: fd
            });
            return await response.json();
        }

        form.addEventListener('submit', async function (event) {
            event.preventDefault();

            var selected = checks().filter(function (checkbox) {
                return checkbox.checked;
            }).map(function (checkbox) {
                return checkbox.value;
            });

            if (!selected.length) {
                setProgress(0, 0, 'Select at least one employee', 'No eligible employees were selected.');
                return;
            }

            if (submitButton) {
                submitButton.disabled = true;
                submitButton.classList.add('opacity-70', 'cursor-not-allowed');
            }

            var total = selected.length;
            var created = 0;
            var skipped = 0;
            var failed = 0;

            setProgress(0, total, 'Starting bulk payroll', 'Preparing payroll for ' + total + ' employee(s)');

            for (var i = 0; i < total; i++) {
                var userId = selected[i];
                setProgress(i, total, 'Processing employee ' + (i + 1) + ' of ' + total, 'Working on employee ID ' + userId);
                try {
                    var result = await processEmployee(userId);
                    markRow(userId, result);
                    if (result && result.status) {
                        created++;
                        setProgress(i + 1, total, 'Paid ' + (i + 1) + ' of ' + total, result.message || 'Payment created');
                    } else if (result && result.skipped) {
                        skipped++;
                        setProgress(i + 1, total, 'Skipped ' + (i + 1) + ' of ' + total, result.message || 'Already paid');
                    } else {
                        failed++;
                        setProgress(i + 1, total, 'Failed ' + (i + 1) + ' of ' + total, (result && result.message) ? result.message : 'Payment failed');
                    }
                } catch (error) {
                    failed++;
                    markRow(userId, {status: false});
                    setProgress(i + 1, total, 'Failed ' + (i + 1) + ' of ' + total, 'Request failed for employee ID ' + userId);
                }
                updateBulkSummary();
            }

            setProgress(total, total, 'Bulk payroll finished', created + ' created, ' + skipped + ' skipped, ' + failed + ' failed');
            if (submitButton) {
                submitButton.disabled = false;
                submitButton.classList.remove('opacity-70', 'cursor-not-allowed');
            }
        });

        if (selectAll) {
            selectAll.addEventListener('change', function () {
                checks().forEach(function (checkbox) {
                    checkbox.checked = selectAll.checked;
                });
                updateBulkSummary();
            });
        }

        form.addEventListener('change', function (event) {
            if (event.target && event.target.classList.contains('employee-check')) {
                updateBulkSummary();
            }
        });

        updateBulkSummary();
    })();
</script>

<!-- end -->
