<?php
require_once 'includes/db.php';
require_once 'includes/auth.php';

if (!hasRole(['owner', 'finance executive'])) {
    echo "Unauthorized";
    exit;
}

$current_month = intval(date('m'));
$current_year = intval(date('Y'));
?>

<!-- Tabs Header -->
<div class="tabs-container" style="margin-bottom: 1.5rem;">
    <div style="display: flex; gap: 0.5rem; border-bottom: 1px solid var(--border); padding-bottom: 0.5rem;">
        <button class="btn tab-btn active" id="btn-tab-calculations" onclick="switchTab('calculations')">
            <i class="fas fa-list-check" style="margin-right: 0.5rem;"></i>Payroll queue
        </button>
        <button class="btn tab-btn" id="btn-tab-history" onclick="switchTab('history')">
            <i class="fas fa-clock-rotate-left" style="margin-right: 0.5rem;"></i>Payroll History
        </button>
        <button class="btn tab-btn" id="btn-tab-configuration" onclick="switchTab('configuration')">
            <i class="fas fa-sliders" style="margin-right: 0.5rem;"></i>Payroll Configurations
        </button>
    </div>
</div>

<!-- Filters Bar (Only visible in Calculations tab) -->
<div id="payroll_filters_wrapper" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
    <!-- Dynamic Cycles Dropdown -->
    <div style="display: flex; align-items: center; gap: 0.75rem;">
        <label style="font-weight: 600; color: var(--text-color); margin: 0; display: flex; align-items: center; gap: 0.5rem;">
            <i class="fas fa-calendar-alt" style="color: var(--primary);"></i>
            Payroll Cycle Period:
        </label>
        <span id="payroll_cycle_period_text" style="font-weight: 600; color: var(--text-main); background: var(--bg-card); padding: 0.5rem 1.25rem; border-radius: 8px; border: 1px solid var(--border); display: inline-flex; align-items: center; min-height: 38px; box-shadow: var(--shadow); font-size: 0.95rem;">Loading...</span>
        <select id="payroll_cycle_period" style="display: none;" onchange="loadPayroll(); updatePayrollCycleText();">
            <option value="">Loading cycles...</option>
        </select>
    </div>

    <div style="display: flex; gap: 0.5rem; align-items: center;">
        <button id="btnDownloadPayroll" class="btn" style="background: #0EA5E9; color: white; display: none;" onclick="downloadPayrollSheet()">
            <i class="fas fa-file-excel" style="margin-right: 0.5rem;"></i>Download Payroll Sheet
        </button>
        <button id="btnCyclePaid" class="btn" style="background: #10B981; color: white; display: none;" onclick="markCyclePaid()">
            <i class="fas fa-money-check-alt" style="margin-right: 0.5rem;"></i>Payroll Cycle Paid
        </button>
        <button id="btnMarkPaid" class="btn" style="background: var(--success); color: white; display: none;" onclick="processPayrollPayments()">
            <i class="fas fa-check-circle" style="margin-right: 0.5rem;"></i>Confirm Payroll Cycle
        </button>
    </div>
</div>

<!-- Tab: Calculations Content -->
<div id="tab-calculations-content" class="tab-content-pane">
    <div class="card" style="padding: 1.5rem;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.25rem;">
            <h3 style="margin: 0; font-size: 1.1rem;"><i class="fas fa-list-check" style="color: var(--primary); margin-right: 0.5rem;"></i> Payroll Queue</h3>
            <div id="payrollStatusLabel" style="font-weight: 700;"></div>
        </div>
        
        <div class="table-container" style="overflow-x: auto;">
            <table class="table" style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="border-bottom: 2px solid var(--border); text-align: left;">
                        <th style="padding: 0.75rem 0.5rem; width: 100px;">Emp ID</th>
                        <th style="padding: 0.75rem 0.5rem; width: 160px;">Employee</th>
                        <th style="padding: 0.75rem 0.5rem; text-align: right; width: 135px;">Gross Salary (<span class="currency-label"></span>)</th>
                        <th style="padding: 0.75rem 0.5rem; text-align: right; width: 135px;">Salary Advance (<span class="currency-label"></span>)</th>
                        <th style="padding: 0.75rem 0.5rem; text-align: right; width: 155px;">Total Deductions (<span class="currency-label"></span>)</th>
                        <th style="padding: 0.75rem 0.5rem; text-align: right; width: 135px;">Net Salary (<span class="currency-label"></span>)</th>
                        <th style="padding: 0.75rem 0.5rem; text-align: center; width: 100px;">Status</th>
                        <th style="padding: 0.75rem 0.5rem; text-align: center; width: 180px;">Actions</th>
                    </tr>
                </thead>
                <tbody id="payrollTableBody">
                    <tr>
                        <td colspan="8" style="text-align: center; color: var(--text-muted); padding: 3rem;">Loading payroll data...</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Tab: Configuration Content -->
<div id="tab-configuration-content" class="tab-content-pane" style="display: none;">
    <div class="card" style="padding: 2rem; max-width: 650px; margin: 0 auto;">
        <h3 style="margin-top: 0; margin-bottom: 1.5rem;"><i class="fas fa-sliders" style="color: var(--primary); margin-right: 0.5rem;"></i> Payroll Configurations Setup</h3>
        
        <form id="payrollConfigForm" onsubmit="saveConfiguration(event)">
            <!-- Paid Working Days -->
            <div style="margin-bottom: 1.5rem;">
                <label style="display: block; font-weight: 600; margin-bottom: 0.5rem;">Paid Working Days Override</label>
                <input type="number" id="cfg_paid_working_days" name="paid_working_days" class="form-control" placeholder="Leave blank to calculate dynamically" min="1" max="31">
                <small style="color: var(--text-muted); display: block; margin-top: 0.25rem;">Specify a fixed number of working days per cycle, or leave blank to calculate based on actual weekdays (Mon-Fri) in the range.</small>
            </div>
            
            <hr style="border: 0; border-top: 1px solid var(--border); margin: 1.5rem 0;">
            
            <h4 style="margin-top: 0; margin-bottom: 1rem; font-size: 0.95rem; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.5px;">EPF & ETF Percentages</h4>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 1rem; margin-bottom: 1.5rem;">
                <div>
                    <label style="display: block; font-weight: 600; margin-bottom: 0.5rem; font-size: 0.85rem;">Employee EPF Deduction (%)</label>
                    <input type="number" id="cfg_epf_employee_percent" name="epf_employee_percent" class="form-control" step="0.01" min="0" max="100" value="0.00">
                </div>
                <div>
                    <label style="display: block; font-weight: 600; margin-bottom: 0.5rem; font-size: 0.85rem;">Employer EPF Liability (%)</label>
                    <input type="number" id="cfg_epf_employer_percent" name="epf_employer_percent" class="form-control" step="0.01" min="0" max="100" value="0.00">
                </div>
                <div>
                    <label style="display: block; font-weight: 600; margin-bottom: 0.5rem; font-size: 0.85rem;">Employer ETF Liability (%)</label>
                    <input type="number" id="cfg_etf_percent" name="etf_percent" class="form-control" step="0.01" min="0" max="100" value="0.00">
                </div>
            </div>
            <small style="color: var(--text-muted); display: block; margin-top: -0.5rem; margin-bottom: 1.5rem;">Set to 0 if not paying EPF/ETF. Under Sri Lankan labor law, standard rates are 8% Employee EPF, 12% Employer EPF, and 3% Employer ETF.</small>
            
            <hr style="border: 0; border-top: 1px solid var(--border); margin: 1.5rem 0;">
            
            <h4 style="margin-top: 0; margin-bottom: 1rem; font-size: 0.95rem; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.5px;">Attendance Incentives</h4>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1.5rem;">
                <div>
                    <label style="display: block; font-weight: 600; margin-bottom: 0.5rem; font-size: 0.85rem;">Perfect Attendance Incentive</label>
                    <input type="number" id="cfg_attendance_incentive_perfect" name="attendance_incentive_perfect" class="form-control" step="0.01" min="0" value="0.00">
                </div>
                <div>
                    <label style="display: block; font-weight: 600; margin-bottom: 0.5rem; font-size: 0.85rem;">1 Absence Attendance Incentive</label>
                    <input type="number" id="cfg_attendance_incentive_one_absent" name="attendance_incentive_one_absent" class="form-control" step="0.01" min="0" value="0.00">
                </div>
            </div>
            <small style="color: var(--text-muted); display: block; margin-top: -0.5rem; margin-bottom: 1.5rem;">Configure the reward amount automatically paid to employees with perfect attendance (0 days absent) or exactly 1 day absent during the cycle.</small>
            
            <hr style="border: 0; border-top: 1px solid var(--border); margin: 1.5rem 0;">
            
            <h4 style="margin-top: 0; margin-bottom: 1rem; font-size: 0.95rem; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.5px;">Payroll Cycle Dates</h4>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1.5rem;">
                <div>
                    <label style="display: block; font-weight: 600; margin-bottom: 0.5rem; font-size: 0.85rem;">Cycle Start Day</label>
                    <input type="number" id="cfg_cycle_start_day" name="cycle_start_day" class="form-control" min="1" max="31" required value="1">
                </div>
                <div>
                    <label style="display: block; font-weight: 600; margin-bottom: 0.5rem; font-size: 0.85rem;">Cycle End Day</label>
                    <input type="number" id="cfg_cycle_end_day" name="cycle_end_day" class="form-control" min="0" max="31" required value="0">
                </div>
            </div>
            <small style="color: var(--text-muted); display: block; margin-top: -0.5rem; margin-bottom: 1.5rem;">
                - Use Start: <strong>1</strong>, End: <strong>0</strong> to process calendar months (e.g., June 1st to June 30th).<br>
                - Use Start: <strong>26</strong>, End: <strong>25</strong> to process monthly cycles across calendar months (e.g., April 26th to May 25th).
            </small>
            
            <div style="display: flex; justify-content: flex-end; gap: 0.5rem; margin-top: 2rem;">
                <button type="submit" id="btnSaveConfig" class="btn" style="background: var(--primary); color: white;">
                    <i class="fas fa-save" style="margin-right: 0.5rem;"></i>Save Configuration
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Tab: Payroll History Content -->
<div id="tab-history-content" class="tab-content-pane" style="display: none;">
    <div class="card" style="padding: 1.5rem;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
            <h3 style="margin: 0; font-size: 1.1rem;">
                <i class="fas fa-clock-rotate-left" style="color: var(--primary); margin-right: 0.5rem;"></i>
                Payroll History
            </h3>
            <span style="font-size: 0.85rem; color: var(--text-muted);">All finalized payroll cycles grouped by period</span>
        </div>
        <div id="payrollHistoryContainer">
            <div style="text-align: center; color: var(--text-muted); padding: 3rem;">
                <i class="fas fa-spinner fa-spin" style="font-size: 1.5rem; margin-bottom: 0.75rem; display: block;"></i>
                Loading history...
            </div>
        </div>
    </div>
</div>

<!-- Update Payroll Adjustments Modal -->
<div id="updatePayrollModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 750px; width: 90vw; background: var(--bg-card); border: 1px solid var(--border);">
        <div class="modal-header">
            <h3 style="margin: 0; font-size: 1.2rem; color: var(--text-color);">
                <i class="fas fa-edit" style="color: var(--primary); margin-right: 0.5rem;"></i> Update Payroll Adjustments
            </h3>
            <button class="btn-icon" onclick="closeModal('updatePayrollModal')" style="background: none; border: none; cursor: pointer; font-size: 1.2rem; color: var(--text-muted);">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="modal-body" style="padding: 1.5rem; max-height: 75vh; overflow-y: auto;">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
                <!-- Employee Summary (Read-Only) -->
                <div style="background: var(--bg-dark); padding: 1.25rem; border-radius: 16px; border: 1px solid var(--border);">
                    <h4 style="margin-top: 0; margin-bottom: 1rem; font-size: 0.9rem; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.5px;">Employee Details</h4>
                    
                    <div style="display: flex; flex-direction: column; gap: 0.75rem; font-size: 0.9rem;">
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: var(--text-muted);">Emp ID:</span>
                            <strong id="up_emp_id" style="font-family: monospace;">-</strong>
                        </div>
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: var(--text-muted);">Name:</span>
                            <strong id="up_name">-</strong>
                        </div>
                        <div style="display: flex; justify-content: space-between; border-bottom: 1px solid var(--border); padding-bottom: 0.5rem; margin-bottom: 0.5rem;">
                            <span style="color: var(--text-muted);">Hourly Rate:</span>
                            <strong id="up_hourly_rate">-</strong>
                        </div>
                        
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: var(--text-muted);">Days Present:</span>
                            <strong id="up_days_present" style="color: #10B981;">-</strong>
                        </div>
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: var(--text-muted);">Days Absent:</span>
                            <strong id="up_days_absent" style="color: #EF4444;">-</strong>
                        </div>
                        <div style="display: flex; justify-content: space-between; border-bottom: 1px solid var(--border); padding-bottom: 0.5rem; margin-bottom: 0.5rem;">
                            <span style="color: var(--text-muted);">Hours (Regular / OT):</span>
                            <strong><span id="up_reg_hours">-</span> / <span id="up_ot_hours">-</span></strong>
                        </div>
                        
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: var(--text-muted);">Base Salary:</span>
                            <strong id="up_base_salary">-</strong>
                        </div>
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: var(--text-muted);">OT Pay:</span>
                            <strong id="up_ot_pay">-</strong>
                        </div>
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: var(--text-muted);">Attn Incentive:</span>
                            <strong id="up_attn_incentive" style="color: #10B981;">-</strong>
                        </div>
                        <div style="display: flex; justify-content: space-between;">
                            <span style="color: var(--text-muted);" id="lbl_up_epf_ee">EPF Employee:</span>
                            <strong id="up_epf_ee" style="color: #EF4444;">-</strong>
                        </div>
                        <div style="display: flex; justify-content: space-between; border-top: 1px dashed var(--border); padding-top: 0.5rem; margin-top: 0.5rem;">
                            <span style="color: var(--text-muted);">No-Pay Deduction:</span>
                            <strong id="up_no_pay" style="color: #EF4444;">-</strong>
                        </div>
                    </div>
                </div>

                <!-- Adjustments Inputs -->
                <div style="display: flex; flex-direction: column; gap: 1rem;">
                    <h4 style="margin-top: 0; margin-bottom: 0.25rem; font-size: 0.9rem; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.5px;">Adjustments</h4>
                    
                    <div>
                        <label style="display: block; font-weight: 600; font-size: 0.85rem; margin-bottom: 0.35rem; color: var(--text-color);">Production Incentive</label>
                        <input type="number" id="up_prod_incentive" step="0.01" min="0" class="form-control" oninput="recalculateUpdateModalLive()" style="font-weight: 600; background: var(--bg-card); color: var(--text-color); border: 1px solid var(--border);">
                    </div>
                    <div>
                        <label style="display: block; font-weight: 600; font-size: 0.85rem; margin-bottom: 0.35rem; color: var(--text-color);">Other Allowances</label>
                        <input type="number" id="up_other_allowances" step="0.01" min="0" class="form-control" oninput="recalculateUpdateModalLive()" style="font-weight: 600; background: var(--bg-card); color: var(--text-color); border: 1px solid var(--border);">
                    </div>
                    <div style="background: var(--bg-dark); padding: 1rem; border-radius: 12px; border: 1px solid var(--border); margin-bottom: 0.5rem;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem;">
                            <label style="font-weight: 600; font-size: 0.85rem; margin: 0; color: var(--text-color);"><i class="fas fa-hand-holding-dollar" style="color: #F59E0B; margin-right: 0.35rem;"></i> Salary Advances</label>
                            <span style="font-size: 0.85rem; font-weight: 700; color: #F59E0B;" id="up_salary_advance_sum_badge">Total: <span class="currency-label"></span>0.00</span>
                        </div>
                        
                        <!-- List of advances -->
                        <div id="up_advances_list" style="display: flex; flex-direction: column; gap: 0.5rem; max-height: 140px; overflow-y: auto; margin-bottom: 0.75rem; padding-right: 0.25rem;">
                            <!-- Populated dynamically -->
                        </div>
                        
                        <!-- Add new advance widget -->
                        <div id="up_new_advance_form" style="display: flex; gap: 0.5rem; align-items: center;">
                            <input type="number" id="new_advance_amount" placeholder="Amount" step="0.01" min="0.01" class="form-control" style="font-weight: 600; background: var(--bg-card); color: var(--text-color); border: 1px solid var(--border); padding: 0.35rem 0.5rem; font-size: 0.85rem; flex: 1;">
                            <input type="datetime-local" id="new_advance_date" class="form-control" style="background: var(--bg-card); color: var(--text-color); border: 1px solid var(--border); padding: 0.35rem 0.5rem; font-size: 0.85rem; flex: 1.5;">
                            <button type="button" class="btn" id="btnAddAdvance" onclick="addNewAdvanceBtnClick()" style="background: var(--primary); color: white; padding: 0.35rem 0.75rem; font-size: 0.85rem; border-radius: 6px; display: flex; align-items: center; gap: 0.25rem;">
                                <i class="fas fa-plus"></i> Add
                            </button>
                        </div>
                    </div>
                    <div>
                        <label style="display: block; font-weight: 600; font-size: 0.85rem; margin-bottom: 0.35rem; color: var(--text-color);">Other Deductions</label>
                        <input type="number" id="up_other_deductions" step="0.01" min="0" class="form-control" oninput="recalculateUpdateModalLive()" style="font-weight: 600; background: var(--bg-card); color: var(--text-color); border: 1px solid var(--border);">
                    </div>
                </div>
            </div>

            <!-- Recalculated Live Totals Banner -->
            <div style="margin-top: 1.5rem; background: var(--bg-dark); border: 1px solid var(--border); padding: 1.25rem; border-radius: 16px; display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 1rem; text-align: center; box-shadow: var(--shadow);">
                <div style="border-right: 1px solid var(--border);">
                    <div style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; font-weight: 600; margin-bottom: 0.25rem;">Gross Salary</div>
                    <div id="up_live_gross" style="font-size: 1.15rem; font-weight: 700; color: var(--text-color);">-</div>
                </div>
                <div style="border-right: 1px solid var(--border);">
                    <div style="font-size: 0.75rem; color: #F59E0B; text-transform: uppercase; font-weight: 600; margin-bottom: 0.25rem;">Salary Advance</div>
                    <div id="up_live_advance" style="font-size: 1.15rem; font-weight: 700; color: #F59E0B;">-</div>
                </div>
                <div style="border-right: 1px solid var(--border);">
                    <div style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; font-weight: 600; margin-bottom: 0.25rem;">Total Deductions</div>
                    <div id="up_live_deductions" style="font-size: 1.15rem; font-weight: 700; color: #EF4444;">-</div>
                </div>
                <div>
                    <div style="font-size: 0.75rem; color: var(--primary); text-transform: uppercase; font-weight: 700; margin-bottom: 0.25rem;">Net Salary</div>
                    <div id="up_live_net" style="font-size: 1.3rem; font-weight: 800; color: var(--primary);">-</div>
                </div>
            </div>
        </div>
        <div class="modal-footer" style="padding: 1.25rem; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; gap: 0.75rem; background: var(--bg-dark); border-bottom-left-radius: 24px; border-bottom-right-radius: 24px;">
            <button class="btn" style="background: var(--border); color: var(--text-color);" onclick="closeModal('updatePayrollModal')">Cancel</button>
            <button id="btnSaveUpdate" class="btn" style="background: var(--primary); color: white;" onclick="saveUpdateModal('draft')">Save Adjustments</button>
            <button id="btnConfirmUpdate" class="btn" style="background: var(--success); color: white;" onclick="saveUpdateModal('paid')">Confirm Payroll</button>
        </div>
    </div>
</div>

<!-- Employee Payslip Modal -->
<div id="payslipModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 600px; width: 90vw; background: var(--bg-card); border: 1px solid var(--border);">
        <div class="modal-header">
            <h3 style="margin: 0; font-size: 1.2rem; color: var(--text-color);">
                <i class="fas fa-file-invoice" style="color: var(--primary); margin-right: 0.5rem;"></i> Employee Payslip
            </h3>
            <button class="btn-icon" onclick="closeModal('payslipModal')" style="background: none; border: none; cursor: pointer; font-size: 1.2rem; color: var(--text-muted);">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="modal-body" id="payslipPrintArea" style="padding: 2rem; background: white; color: #1a1625; font-family: 'Inter', sans-serif;">
            <!-- Printable content container -->
            <div style="border: 2px solid #eaeaea; border-radius: 12px; padding: 1.5rem; background: #ffffff; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);">
                <!-- Payslip Header -->
                <div style="text-align: center; border-bottom: 2px dashed #eaeaea; padding-bottom: 1.25rem; margin-bottom: 1.25rem;">
                    <h2 style="margin: 0; color: #7C3AED; font-size: 1.4rem; font-weight: 800; letter-spacing: 0.5px;">NEXCORE APPAREL</h2>
                    <div style="font-size: 0.8rem; color: #6b7280; margin-top: 0.25rem; text-transform: uppercase; font-weight: 600; letter-spacing: 1px;">Monthly Payslip</div>
                    <div style="font-size: 0.85rem; font-weight: 700; color: #374151; margin-top: 0.5rem; background: #f3f4f6; display: inline-block; padding: 0.25rem 0.75rem; border-radius: 20px;" id="ps_period">Pay Period: -</div>
                </div>

                <!-- Info Grid -->
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; font-size: 0.85rem; border-bottom: 1px solid #eaeaea; padding-bottom: 1rem; margin-bottom: 1.25rem;">
                    <div>
                        <div style="margin-bottom: 0.35rem;"><span style="color: #6b7280;">Employee ID:</span> <strong id="ps_emp_id" style="color: #111827; font-family: monospace;">-</strong></div>
                        <div><span style="color: #6b7280;">Employee Name:</span> <strong id="ps_name" style="color: #111827;">-</strong></div>
                    </div>
                    <div style="text-align: right;">
                        <div style="margin-bottom: 0.35rem;"><span style="color: #6b7280;">Hourly Rate:</span> <strong id="ps_hourly_rate" style="color: #111827;">-</strong></div>
                        <div><span style="color: #6b7280;">Days Present:</span> <strong id="ps_days_present" style="color: #10b981;">-</strong></div>
                    </div>
                </div>

                <!-- Earnings and Deductions tables side-by-side or stacked -->
                <div style="display: flex; flex-direction: column; gap: 1rem; font-size: 0.85rem;">
                    <!-- Earnings Section -->
                    <div>
                        <table style="width: 100%; border-collapse: collapse;">
                            <thead>
                                <tr style="border-bottom: 1px solid #eaeaea; color: #374151;">
                                    <th style="text-align: left; padding: 0.5rem 0; font-weight: 700;">Earnings</th>
                                    <th style="text-align: right; padding: 0.5rem 0; font-weight: 700; width: 120px;">Amount (<span class="ps-currency-label"></span>)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td style="padding: 0.4rem 0; color: #4b5563;">Base Salary (incl. Paid Leaves)</td>
                                    <td id="ps_base_salary" style="text-align: right; padding: 0.4rem 0; font-weight: 600; color: #111827;">-</td>
                                </tr>
                                <tr>
                                    <td style="padding: 0.4rem 0; color: #4b5563;">Overtime Pay</td>
                                    <td id="ps_ot_pay" style="text-align: right; padding: 0.4rem 0; font-weight: 600; color: #111827;">-</td>
                                </tr>
                                <tr>
                                    <td style="padding: 0.4rem 0; color: #4b5563;">Attendance Incentive</td>
                                    <td id="ps_attn_incentive" style="text-align: right; padding: 0.4rem 0; font-weight: 600; color: #111827;">-</td>
                                </tr>
                                <tr>
                                    <td style="padding: 0.4rem 0; color: #4b5563;">Production Incentive</td>
                                    <td id="ps_prod_incentive" style="text-align: right; padding: 0.4rem 0; font-weight: 600; color: #111827;">-</td>
                                </tr>
                                <tr>
                                    <td style="padding: 0.4rem 0; color: #4b5563;">Other Allowances</td>
                                    <td id="ps_other_allowances" style="text-align: right; padding: 0.4rem 0; font-weight: 600; color: #111827;">-</td>
                                </tr>
                                <tr style="border-top: 1px solid #eaeaea; font-weight: 700; color: #111827;">
                                    <td style="padding: 0.5rem 0;">Gross Salary</td>
                                    <td id="ps_gross_salary" style="text-align: right; padding: 0.5rem 0; color: #111827;">-</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- Deductions Section -->
                    <div style="margin-top: 0.5rem;">
                        <table style="width: 100%; border-collapse: collapse;">
                            <thead>
                                <tr style="border-bottom: 1px solid #eaeaea; color: #374151;">
                                    <th style="text-align: left; padding: 0.5rem 0; font-weight: 700;">Deductions</th>
                                    <th style="text-align: right; padding: 0.5rem 0; font-weight: 700; width: 120px;">Amount (<span class="ps-currency-label"></span>)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td style="padding: 0.4rem 0; color: #4b5563;" id="lbl_ps_epf_ee">EPF (Employee share)</td>
                                    <td id="ps_epf_ee" style="text-align: right; padding: 0.4rem 0; font-weight: 600; color: #dc2626;">-</td>
                                </tr>
                                <tr>
                                    <td style="padding: 0.4rem 0; color: #4b5563;">No-Pay Cut</td>
                                    <td id="ps_no_pay" style="text-align: right; padding: 0.4rem 0; font-weight: 600; color: #dc2626;">-</td>
                                </tr>
                                <tr>
                                    <td style="padding: 0.4rem 0; color: #4b5563;">Other Deductions</td>
                                    <td id="ps_other_deductions" style="text-align: right; padding: 0.4rem 0; font-weight: 600; color: #dc2626;">-</td>
                                </tr>
                                <tr style="border-top: 1px solid #eaeaea; font-weight: 700; color: #dc2626;">
                                    <td style="padding: 0.5rem 0;">Total Deductions</td>
                                    <td id="ps_total_deductions" style="text-align: right; padding: 0.5rem 0;">-</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- Salary Advance Section -->
                    <div style="margin-top: 0.5rem; border-top: 1px solid #eaeaea; padding-top: 0.5rem;">
                        <table style="width: 100%; border-collapse: collapse;">
                            <tbody>
                                <tr>
                                    <td style="padding: 0.4rem 0; color: #4b5563; font-weight: 600;">Salary Advance</td>
                                    <td id="ps_salary_advance" style="text-align: right; padding: 0.4rem 0; font-weight: 700; color: #F59E0B; width: 120px;">-</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Net Salary Highlight Block -->
                <div style="margin-top: 1.5rem; background: #f5f3ff; border: 1.5px solid #ddd6fe; border-radius: 8px; padding: 0.75rem 1rem; display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.25rem;">
                    <span style="font-weight: 800; font-size: 0.95rem; color: #4c1d95; text-transform: uppercase; letter-spacing: 0.5px;">Net Paid Salary</span>
                    <span id="ps_net_salary" style="font-weight: 900; font-size: 1.3rem; color: #6d28d9;">-</span>
                </div>

                <!-- Employer Contributions Section -->
                <div style="background: #f9fafb; border: 1px solid #f3f4f6; border-radius: 8px; padding: 0.75rem; font-size: 0.75rem; color: #4b5563;">
                    <div style="font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280; margin-bottom: 0.35rem;">Employer Contributions (Statutory Info)</div>
                    <div style="display: flex; justify-content: space-between; margin-bottom: 0.2rem;">
                        <span id="lbl_ps_epf_er">Employer EPF Liability:</span>
                        <strong id="ps_epf_er">-</strong>
                    </div>
                    <div style="display: flex; justify-content: space-between;">
                        <span id="lbl_ps_etf_er">Employer ETF Liability:</span>
                        <strong id="ps_etf_er">-</strong>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer" style="padding: 1.25rem; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; gap: 0.75rem; background: var(--bg-dark); border-bottom-left-radius: 24px; border-bottom-right-radius: 24px;">
            <button class="btn" style="background: var(--border); color: var(--text-color);" onclick="closeModal('payslipModal')">Close</button>
            <button class="btn" style="background: #10B981; color: white;" onclick="printPayslip()"><i class="fas fa-print" style="margin-right: 0.5rem;"></i>Print Payslip</button>
        </div>
    </div>
</div>

<style>
.hist-accordion-body { display: none; }
.hist-accordion-body.hist-open { display: block !important; }
</style>

<script>
let currentPayrollData = [];

function toggleHistAcc(id) {
    const body    = document.getElementById(id);
    const chevron = document.getElementById('chevron-' + id);
    if (!body) return;
    const isOpen = body.classList.toggle('hist-open');
    if (chevron) chevron.style.transform = isOpen ? 'rotate(180deg)' : 'rotate(0deg)';
}

function updatePayrollCycleText() {
    const select = document.getElementById('payroll_cycle_period');
    const textSpan = document.getElementById('payroll_cycle_period_text');
    if (select && textSpan) {
        textSpan.textContent = select.options[select.selectedIndex]?.text || 'No Cycle Selected';
    }
}

function switchTab(tabId) {
    document.getElementById('tab-calculations-content').style.display = tabId === 'calculations' ? 'block' : 'none';
    document.getElementById('tab-history-content').style.display      = tabId === 'history'      ? 'block' : 'none';
    document.getElementById('tab-configuration-content').style.display = tabId === 'configuration' ? 'block' : 'none';

    document.getElementById('btn-tab-calculations').classList.toggle('active', tabId === 'calculations');
    document.getElementById('btn-tab-history').classList.toggle('active', tabId === 'history');
    document.getElementById('btn-tab-configuration').classList.toggle('active', tabId === 'configuration');

    document.getElementById('payroll_filters_wrapper').style.display = tabId === 'calculations' ? 'flex' : 'none';

    if (tabId === 'calculations') {
        initPayrollCycles().then(() => {
            loadPayroll();
        });
    } else if (tabId === 'history') {
        loadPayrollHistory();
    } else {
        loadConfiguration();
    }
}

async function loadPayroll() {
    const cycleSelect = document.getElementById('payroll_cycle_period');
    if (!cycleSelect || !cycleSelect.value) return;
    
    updatePayrollCycleText();
    
    const [year, month] = cycleSelect.value.split('-');
    
    const tbody = document.getElementById('payrollTableBody');
    tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; color: var(--text-muted); padding: 3rem;"><i class="fas fa-spinner fa-spin" style="margin-right: 0.5rem;"></i>Calculating and loading payroll...</td></tr>`;
    
    const res = await apiCall('payroll', { action: 'calculate', month: month, year: year });
    if (res.success) {
        currentPayrollData = res.payroll;
        renderPayrollTable();
    } else {
        notify(res.message, 'error');
        tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; color: var(--danger); padding: 3rem;">Error loading payroll records.</td></tr>`;
    }
}

async function loadPayrollHistory() {
    const container = document.getElementById('payrollHistoryContainer');
    container.innerHTML = `<div style="text-align:center;color:var(--text-muted);padding:3rem;">
        <i class="fas fa-spinner fa-spin" style="font-size:1.5rem;margin-bottom:0.75rem;display:block;"></i>
        Loading history...</div>`;

    const res = await apiCall('payroll', { action: 'get_payroll_history' });
    if (!res.success) {
        container.innerHTML = `<div style="text-align:center;color:var(--danger);padding:3rem;">Failed to load payroll history.</div>`;
        return;
    }

    if (!res.history || res.history.length === 0) {
        container.innerHTML = `<div style="text-align:center;color:var(--text-muted);padding:3rem;">
            <i class="fas fa-folder-open" style="font-size:2rem;opacity:0.4;display:block;margin-bottom:0.75rem;"></i>
            No payroll history found yet.</div>`;
        return;
    }

    const currency = window.APP_CONFIG ? window.APP_CONFIG.COMPANY_CURRENCY || '' : '';
    const fmt = v => parseFloat(v || 0).toFixed(2);

    container.innerHTML = res.history.map((cycle, idx) => {
        const allPaid      = cycle.employees.every(e => e.status === 'paid');
        const allConfirmed = cycle.employees.every(e => e.status === 'confirmed' || e.status === 'paid');
        const cycleStatus  = allPaid ? 'paid' : (allConfirmed ? 'confirmed' : 'mixed');
        const statusColor  = cycleStatus === 'paid' ? '#10B981' : (cycleStatus === 'confirmed' ? '#3B82F6' : '#F59E0B');
        const statusBg     = cycleStatus === 'paid' ? 'rgba(16,185,129,0.12)' : (cycleStatus === 'confirmed' ? 'rgba(59,130,246,0.12)' : 'rgba(245,158,11,0.12)');
        const statusLabel  = cycleStatus === 'paid' ? '\u{1F4B8} PAID' : (cycleStatus === 'confirmed' ? '\u2714 CONFIRMED' : 'MIXED');
        const accordionId  = `hist-acc-${idx}`;

        const empRows = cycle.employees.map(emp => {
            const sc = emp.status === 'paid' ? '#10B981' : (emp.status === 'confirmed' ? '#3B82F6' : '#F59E0B');
            const sb = emp.status === 'paid' ? 'rgba(16,185,129,0.1)' : (emp.status === 'confirmed' ? 'rgba(59,130,246,0.1)' : 'rgba(245,158,11,0.1)');
            const grossSal = parseFloat(emp.base_salary||0) + parseFloat(emp.ot_pay||0) + parseFloat(emp.allowances||0);
            return `
            <tr style="border-bottom:1px solid var(--border); font-size:0.82rem;">
                <td style="padding:0.55rem 0.5rem;font-family:monospace;color:var(--text-muted);">EMP-${String(emp.employee_id).padStart(4,'0')}</td>
                <td style="padding:0.55rem 0.5rem;font-weight:600;">${emp.name}</td>
                <td style="padding:0.55rem 0.5rem;text-align:center;">${emp.days_present} / ${emp.total_working_days}</td>
                <td style="padding:0.55rem 0.5rem;text-align:right;">${fmt(emp.base_salary)}</td>
                <td style="padding:0.55rem 0.5rem;text-align:right;">${fmt(emp.ot_pay)}</td>
                <td style="padding:0.55rem 0.5rem;text-align:right;">${fmt(grossSal)}</td>
                <td style="padding:0.55rem 0.5rem;text-align:right;color:#F59E0B;">${fmt(emp.salary_advance)}</td>
                <td style="padding:0.55rem 0.5rem;text-align:right;color:#EF4444;">${fmt(emp.deductions)}</td>
                <td style="padding:0.55rem 0.5rem;text-align:right;font-weight:700;color:var(--primary);">${fmt(emp.net_salary)}</td>
                <td style="padding:0.55rem 0.5rem;text-align:center;">
                    <span style="background:${sb};color:${sc};padding:0.2rem 0.45rem;border-radius:5px;font-size:0.7rem;font-weight:700;text-transform:uppercase;">${emp.status}</span>
                </td>
            </tr>`;
        }).join('');

        const grossTotal = parseFloat(cycle.total_base||0)+parseFloat(cycle.total_ot||0)+parseFloat(cycle.total_allowances||0);

        return `
        <div style="border:1px solid var(--border);border-radius:12px;margin-bottom:1rem;overflow:hidden;">
            <!-- Cycle Header -->
            <div onclick="toggleHistAcc('${accordionId}')"
                 style="display:flex;justify-content:space-between;align-items:center;padding:1rem 1.25rem;
                        background:var(--bg-dark);cursor:pointer;gap:1rem;flex-wrap:wrap;user-select:none;">
                <!-- Left -->
                <div style="display:flex;align-items:center;gap:0.75rem;flex-wrap:wrap;">
                    <i class="fas fa-calendar-week" style="color:var(--primary);font-size:1rem;"></i>
                    <span style="font-weight:700;font-size:0.95rem;color:var(--text-color);">
                        ${cycle.period_start}&nbsp;&rarr;&nbsp;${cycle.period_end}
                    </span>
                    <span style="background:${statusBg};color:${statusColor};padding:0.2rem 0.65rem;border-radius:20px;font-size:0.72rem;font-weight:700;">
                        ${statusLabel}
                    </span>
                    <span style="color:var(--text-muted);font-size:0.8rem;">
                        <i class="fas fa-users" style="margin-right:0.25rem;"></i>${cycle.employee_count} employees
                    </span>
                </div>
                <!-- Right -->
                <div style="display:flex;align-items:center;gap:1.5rem;flex-wrap:wrap;">
                    <div style="text-align:right;">
                        <div style="font-size:0.68rem;color:var(--text-muted);text-transform:uppercase;font-weight:600;">Gross Total</div>
                        <div style="font-weight:700;font-size:0.9rem;color:var(--text-color);">${currency} ${fmt(grossTotal)}</div>
                    </div>
                    <div style="text-align:right;">
                        <div style="font-size:0.68rem;color:var(--text-muted);text-transform:uppercase;font-weight:600;">Advances</div>
                        <div style="font-weight:700;font-size:0.9rem;color:#F59E0B;">${currency} ${fmt(cycle.total_advances)}</div>
                    </div>
                    <div style="text-align:right;">
                        <div style="font-size:0.68rem;color:var(--text-muted);text-transform:uppercase;font-weight:600;">Deductions</div>
                        <div style="font-weight:700;font-size:0.9rem;color:#EF4444;">${currency} ${fmt(cycle.total_deductions)}</div>
                    </div>
                    <div style="text-align:right;">
                        <div style="font-size:0.68rem;color:var(--primary);text-transform:uppercase;font-weight:700;">Net Payroll</div>
                        <div style="font-weight:800;font-size:1.05rem;color:var(--primary);">${currency} ${fmt(cycle.total_net)}</div>
                    </div>
                    <i id="chevron-${accordionId}" class="fas fa-chevron-down" style="color:var(--text-muted);transition:transform 0.3s;"></i>
                </div>
            </div>

            <!-- Expandable employee table -->
            <div id="${accordionId}" class="hist-accordion-body">
                <!-- Summary stats strip -->
                <div style="display:grid;grid-template-columns:repeat(5,1fr);border-bottom:1px solid var(--border);background:var(--bg-card);">
                    ${[
                        ['Base Salary',  fmt(cycle.total_base),    'var(--text-color)'],
                        ['OT Pay',       fmt(cycle.total_ot),      '#7C3AED'],
                        ['EPF Employee', fmt(cycle.total_epf_ee),  '#EF4444'],
                        ['EPF Employer', fmt(cycle.total_epf_er),  '#EF4444'],
                        ['ETF Employer', fmt(cycle.total_etf),     '#EF4444']
                    ].map(([label,val,color]) => `
                        <div style="padding:0.65rem 1rem;border-right:1px solid var(--border);">
                            <div style="font-size:0.68rem;color:var(--text-muted);text-transform:uppercase;font-weight:600;margin-bottom:0.2rem;">${label}</div>
                            <div style="font-weight:700;font-size:0.85rem;color:${color};">${currency} ${val}</div>
                        </div>`).join('')}
                </div>

                <div style="overflow-x:auto;">
                <table style="width:100%;border-collapse:collapse;min-width:820px;">
                    <thead>
                        <tr style="border-bottom:2px solid var(--border);text-align:left;background:var(--bg-dark);">
                            <th style="padding:0.6rem 0.5rem;font-size:0.78rem;">Emp ID</th>
                            <th style="padding:0.6rem 0.5rem;font-size:0.78rem;">Employee</th>
                            <th style="padding:0.6rem 0.5rem;text-align:center;font-size:0.78rem;">Attendance</th>
                            <th style="padding:0.6rem 0.5rem;text-align:right;font-size:0.78rem;">Base Salary</th>
                            <th style="padding:0.6rem 0.5rem;text-align:right;font-size:0.78rem;">OT Pay</th>
                            <th style="padding:0.6rem 0.5rem;text-align:right;font-size:0.78rem;">Gross Salary</th>
                            <th style="padding:0.6rem 0.5rem;text-align:right;font-size:0.78rem;">Advance</th>
                            <th style="padding:0.6rem 0.5rem;text-align:right;font-size:0.78rem;">Deductions</th>
                            <th style="padding:0.6rem 0.5rem;text-align:right;font-size:0.78rem;">Net Salary</th>
                            <th style="padding:0.6rem 0.5rem;text-align:center;font-size:0.78rem;">Status</th>
                        </tr>
                    </thead>
                    <tbody>${empRows}</tbody>
                </table>
                </div>
            </div>
        </div>`;
    }).join('');
}

function renderPayrollTable() {
    const tbody = document.getElementById('payrollTableBody');
    const btnMarkPaid = document.getElementById('btnMarkPaid');
    const statusLabel = document.getElementById('payrollStatusLabel');
    
    tbody.innerHTML = '';
    
    if (currentPayrollData.length === 0) {
        tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; color: var(--text-muted); padding: 3rem;">No employee records found.</td></tr>`;
        btnMarkPaid.style.display = 'none';
        statusLabel.innerHTML = '';
        return;
    }
    
    const currency = window.APP_CONFIG ? window.APP_CONFIG.COMPANY_CURRENCY || '$' : '$';
    document.querySelectorAll('.currency-label').forEach(el => {
        el.textContent = currency;
    });
    
    let allLocked = true;
    let anyDraft = false;
    
    currentPayrollData.forEach(row => {
        if (row.status !== 'confirmed' && row.status !== 'paid') allLocked = false;
        if (row.status === 'draft') anyDraft = true;
        
        const isLocked = row.status === 'confirmed' || row.status === 'paid';
        const statusColor = row.status === 'paid' ? '#10B981' : (row.status === 'confirmed' ? '#3B82F6' : '#F59E0B');
        const statusBg = row.status === 'paid' ? 'rgba(16, 185, 129, 0.1)' : (row.status === 'confirmed' ? 'rgba(59, 130, 246, 0.1)' : 'rgba(245, 158, 11, 0.1)');
        
        const allowances = parseFloat(row.attendance_incentive || 0) + parseFloat(row.production_incentive || 0) + parseFloat(row.other_allowances || 0);
        const grossSalary = parseFloat(row.base_salary || 0) + parseFloat(row.ot_pay || 0) + allowances;
        const salaryAdvance = parseFloat(row.salary_advance || 0);
        const totalDeductions = parseFloat(row.other_deductions || 0) + parseFloat(row.epf_employee_amount || 0) + parseFloat(row.no_pay || 0);
        
        const tr = document.createElement('tr');
        tr.style.borderBottom = '1px solid var(--border)';
        
        tr.innerHTML = `
            <td style="padding: 0.75rem 0.5rem; font-family: monospace; font-weight: 700; color: var(--text-muted);">EMP-${String(row.employee_id).padStart(4, '0')}</td>
            <td style="padding: 0.75rem 0.5rem; font-weight: 600;">${row.name}</td>
            <td style="padding: 0.75rem 0.5rem; text-align: right; font-weight: 600; color: var(--text-color);">${grossSalary.toFixed(2)}</td>
            <td style="padding: 0.75rem 0.5rem; text-align: right; font-weight: 600; color: #F59E0B;">${salaryAdvance.toFixed(2)}</td>
            <td style="padding: 0.75rem 0.5rem; text-align: right; font-weight: 600; color: #EF4444;">${totalDeductions.toFixed(2)}</td>
            <td style="padding: 0.75rem 0.5rem; text-align: right; font-weight: 800; color: var(--primary); font-size: 1.05rem;">${parseFloat(row.net_salary).toFixed(2)}</td>
            <td style="padding: 0.75rem 0.5rem; text-align: center;">
                <span class="badge" style="
                    background: ${statusBg};
                    color: ${statusColor};
                    padding: 0.25rem 0.5rem; border-radius: 6px; font-size: 0.75rem; text-transform: uppercase; font-weight: 600;
                ">${row.status}</span>
            </td>
            <td style="padding: 0.75rem 0.5rem; text-align: center; white-space: nowrap;">
                <div style="display: inline-flex; gap: 0.4rem; align-items: center; justify-content: center; min-width: 160px;">
                    <button class="btn btn-sm" style="background: var(--primary); color: white; padding: 0.3rem 0.65rem; font-size: 0.78rem; border-radius: 6px; white-space: nowrap; flex: 1;" onclick="openUpdateModal(${row.employee_id})">
                        <i class="fas fa-${isLocked ? 'eye' : 'edit'}"></i> ${isLocked ? 'View' : 'Update'}
                    </button>
                    ${(row.status === 'confirmed' || row.status === 'paid') ? `
                    <button class="btn btn-sm" style="background: #10B981; color: white; padding: 0.3rem 0.65rem; font-size: 0.78rem; border-radius: 6px; white-space: nowrap; flex: 1;" onclick="openPayslipModal(${row.employee_id})">
                        <i class="fas fa-file-invoice"></i> Payslip
                    </button>
                    ` : `<span style="flex: 1; display: inline-block;"></span>`}
                </div>
            </td>
        `;
        
        tbody.appendChild(tr);
    });
    
    const allPaid = currentPayrollData.every(r => r.status === 'paid');
    
    if (allLocked) {
        statusLabel.innerHTML = `<span style="color: #10B981;"><i class="fas fa-lock" style="margin-right: 0.25rem;"></i> Period Locked &amp; Confirmed</span>`;
        btnMarkPaid.style.display = 'none';
        document.getElementById('btnDownloadPayroll').style.display = 'inline-flex';
        document.getElementById('btnCyclePaid').style.display = allPaid ? 'none' : 'inline-flex';
    } else {
        statusLabel.innerHTML = `<span style="color: #F59E0B;"><i class="fas fa-unlock" style="margin-right: 0.25rem;"></i> Editing Calculations (Draft)</span>`;
        btnMarkPaid.style.display = 'block';
        document.getElementById('btnDownloadPayroll').style.display = 'none';
        document.getElementById('btnCyclePaid').style.display = 'none';
    }
}

function openModal(id) {
    document.getElementById(id).classList.add('active');
}

function closeModal(id) {
    document.getElementById(id).classList.remove('active');
}

let activeRow = null;
let payrollConfigCache = null;

async function openUpdateModal(employeeId) {
    const row = currentPayrollData.find(r => r.employee_id == employeeId);
    if (!row) return;
    
    activeRow = row;
    const currency = window.APP_CONFIG ? window.APP_CONFIG.COMPANY_CURRENCY || '$' : '$';
    const isLocked = row.status === 'confirmed' || row.status === 'paid';
    
    // Fetch config for EPF percentage
    if (!payrollConfigCache) {
        const res = await apiCall('payroll', { action: 'get_config' });
        if (res.success && res.config) {
            payrollConfigCache = res.config;
        }
    }
    let epfEePct = 0;
    if (payrollConfigCache) {
        epfEePct = parseFloat(payrollConfigCache.epf_employee_percent || 0);
    }
    document.getElementById('lbl_up_epf_ee').innerText = `EPF Employee (${epfEePct}%):`;
    
    // Set text elements
    document.getElementById('up_emp_id').innerText = `EMP-${String(row.employee_id).padStart(4, '0')}`;
    document.getElementById('up_name').innerText = row.name;
    document.getElementById('up_hourly_rate').innerText = `${currency} ${parseFloat(row.hourly_rate).toFixed(2)}`;
    document.getElementById('up_days_present').innerText = `${row.days_present} / ${row.total_working_days}`;
    document.getElementById('up_days_absent').innerText = row.days_absent;
    document.getElementById('up_reg_hours').innerText = parseFloat(row.regular_hours || 0).toFixed(1);
    document.getElementById('up_ot_hours').innerText = parseFloat(row.ot_hours || 0).toFixed(1);
    
    document.getElementById('up_base_salary').innerText = `${currency} ${parseFloat(row.base_salary).toFixed(2)}`;
    document.getElementById('up_ot_pay').innerText = `${currency} ${parseFloat(row.ot_pay || 0).toFixed(2)}`;
    document.getElementById('up_attn_incentive').innerText = `${currency} ${parseFloat(row.attendance_incentive || 0).toFixed(2)}`;
    document.getElementById('up_epf_ee').innerText = `${currency} ${parseFloat(row.epf_employee_amount || 0).toFixed(2)}`;
    
    // Dynamic per-day salary & no-pay calculation
    const baseSalaryVal = parseFloat(row.base_salary || 0);
    const totalWorkingDays = parseInt(row.total_working_days || 0);
    const perDaySalary = totalWorkingDays > 0 ? (baseSalaryVal / totalWorkingDays) : 0.00;
    const noPay = row.hasOwnProperty('no_pay') ? parseFloat(row.no_pay || 0) : (parseFloat(row.days_absent || 0) * perDaySalary);
    
    document.getElementById('up_no_pay').innerText = `${currency} ${noPay.toFixed(2)}`;
    
    // Set input values
    const prodInput = document.getElementById('up_prod_incentive');
    const otherAllowInput = document.getElementById('up_other_allowances');
    const otherDedInput = document.getElementById('up_other_deductions');
    
    prodInput.value = parseFloat(row.production_incentive || 0).toFixed(2);
    otherAllowInput.value = parseFloat(row.other_allowances || 0).toFixed(2);
    otherDedInput.value = parseFloat(row.other_deductions || 0).toFixed(2);
    
    // Initialize new advance form date with current local date-time
    const now = new Date();
    const tzoffset = now.getTimezoneOffset() * 60000;
    const localISOTime = (new Date(now - tzoffset)).toISOString().slice(0, 16);
    document.getElementById('new_advance_date').value = localISOTime;
    document.getElementById('new_advance_amount').value = '';
    
    // Handle status locking
    if (isLocked) {
        prodInput.disabled = true;
        otherAllowInput.disabled = true;
        otherDedInput.disabled = true;
        document.getElementById('up_new_advance_form').style.display = 'none';
        document.getElementById('btnSaveUpdate').style.display = 'none';
        document.getElementById('btnConfirmUpdate').style.display = 'none';
    } else {
        prodInput.disabled = false;
        otherAllowInput.disabled = false;
        otherDedInput.disabled = false;
        document.getElementById('up_new_advance_form').style.display = 'flex';
        document.getElementById('btnSaveUpdate').style.display = 'inline-block';
        document.getElementById('btnConfirmUpdate').style.display = 'inline-block';
    }
    
    // Load and render advances list dynamically
    loadAdvancesList(row.employee_id, isLocked);
    
    openModal('updatePayrollModal');
}

function formatDateTime(dtStr) {
    if (!dtStr) return '';
    const date = new Date(dtStr.replace(' ', 'T'));
    return date.toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' });
}

async function loadAdvancesList(employeeId, isLocked) {
    const cycleSelect = document.getElementById('payroll_cycle_period');
    const [year, month] = cycleSelect.value.split('-');
    const currency = window.APP_CONFIG ? window.APP_CONFIG.COMPANY_CURRENCY || '$' : '$';
    
    const container = document.getElementById('up_advances_list');
    container.innerHTML = '<div style="text-align: center; color: var(--text-muted); font-size: 0.8rem; padding: 0.5rem;"><i class="fas fa-spinner fa-spin"></i> Loading advances...</div>';
    
    const res = await apiCall('payroll', { action: 'get_advances', employee_id: employeeId, month: month, year: year });
    if (res.success) {
        const advances = res.advances || [];
        let total = 0;
        
        if (advances.length === 0) {
            container.innerHTML = '<div style="text-align: center; color: var(--text-muted); font-size: 0.8rem; padding: 0.5rem;">No advances recorded.</div>';
        } else {
            container.innerHTML = '';
            advances.forEach(adv => {
                total += parseFloat(adv.amount);
                const advRow = document.createElement('div');
                advRow.style.cssText = 'display: flex; justify-content: space-between; align-items: center; background: var(--bg-card); padding: 0.5rem; border-radius: 8px; border: 1px solid var(--border); font-size: 0.8rem;';
                advRow.innerHTML = `
                    <div>
                        <strong style="color: var(--text-color);">${currency} ${parseFloat(adv.amount).toFixed(2)}</strong>
                        <span style="color: var(--text-muted); margin-left: 0.5rem; font-size: 0.75rem;"><i class="far fa-clock"></i> ${formatDateTime(adv.advance_date)}</span>
                    </div>
                    ${isLocked ? '' : `
                    <button type="button" class="btn-icon" style="background: none; border: none; color: #EF4444; cursor: pointer; padding: 0.25rem; font-size: 0.85rem;" onclick="deleteAdvance(${adv.id}, ${employeeId})" title="Delete Advance">
                        <i class="fas fa-trash-alt"></i>
                    </button>
                    `}
                `;
                container.appendChild(advRow);
            });
        }
        
        document.getElementById('up_salary_advance_sum_badge').innerHTML = `Total: ${currency} ${total.toFixed(2)}`;
        if (activeRow && activeRow.employee_id == employeeId) {
            activeRow.salary_advance = total;
            recalculateUpdateModalLive();
        }
    } else {
        container.innerHTML = '<div style="text-align: center; color: var(--danger); font-size: 0.8rem; padding: 0.5rem;">Error loading advances.</div>';
    }
}

async function addNewAdvanceBtnClick() {
    if (!activeRow) return;
    const amountInput = document.getElementById('new_advance_amount');
    const dateInput = document.getElementById('new_advance_date');
    const amount = parseFloat(amountInput.value);
    
    if (isNaN(amount) || amount <= 0) {
        notify('Please enter a valid amount', 'error');
        return;
    }
    
    const cycleSelect = document.getElementById('payroll_cycle_period');
    const [year, month] = cycleSelect.value.split('-');
    
    const btn = document.getElementById('btnAddAdvance');
    setLoading(btn, true);
    
    const res = await apiCall('payroll', {
        action: 'add_advance',
        employee_id: activeRow.employee_id,
        amount: amount,
        advance_date: dateInput.value.replace('T', ' '),
        month: month,
        year: year
    });
    
    setLoading(btn, false);
    
    if (res.success) {
        notify(res.message, 'success');
        amountInput.value = '';
        const isLocked = activeRow.status === 'confirmed' || activeRow.status === 'paid';
        await loadAdvancesList(activeRow.employee_id, isLocked);
    } else {
        notify(res.message, 'error');
    }
}

async function deleteAdvance(advanceId, employeeId) {
    if (!confirm('Are you sure you want to delete this salary advance?')) return;
    
    const cycleSelect = document.getElementById('payroll_cycle_period');
    const [year, month] = cycleSelect.value.split('-');
    
    const res = await apiCall('payroll', {
        action: 'delete_advance',
        id: advanceId,
        employee_id: employeeId,
        month: month,
        year: year
    });
    
    if (res.success) {
        notify(res.message, 'success');
        const isLocked = activeRow && (activeRow.status === 'confirmed' || activeRow.status === 'paid');
        await loadAdvancesList(employeeId, isLocked);
    } else {
        notify(res.message, 'error');
    }
}

function recalculateUpdateModalLive() {
    if (!activeRow) return;
    
    const currency = window.APP_CONFIG ? window.APP_CONFIG.COMPANY_CURRENCY || '$' : '$';
    
    const baseSalary = parseFloat(activeRow.base_salary || 0);
    const otPay = parseFloat(activeRow.ot_pay || 0);
    const attnIncentive = parseFloat(activeRow.attendance_incentive || 0);
    const epfEe = parseFloat(activeRow.epf_employee_amount || 0);
    
    const prodIncentive = parseFloat(document.getElementById('up_prod_incentive').value) || 0;
    const otherAllow = parseFloat(document.getElementById('up_other_allowances').value) || 0;
    const salaryAdvance = parseFloat(activeRow.salary_advance || 0);
    const otherDeductions = parseFloat(document.getElementById('up_other_deductions').value) || 0;
    
    // Recalculate No-Pay
    const totalWorkingDays = parseInt(activeRow.total_working_days || 0);
    const perDaySalary = totalWorkingDays > 0 ? (baseSalary / totalWorkingDays) : 0.00;
    const noPay = activeRow.hasOwnProperty('no_pay') ? parseFloat(activeRow.no_pay || 0) : (parseFloat(activeRow.days_absent || 0) * perDaySalary);
    
    const grossSalary = baseSalary + otPay + attnIncentive + prodIncentive + otherAllow;
    const totalDeductions = epfEe + otherDeductions + noPay;
    const netSalary = grossSalary - salaryAdvance - totalDeductions;
    
    document.getElementById('up_live_gross').innerText = `${currency} ${grossSalary.toFixed(2)}`;
    document.getElementById('up_live_advance').innerText = `${currency} ${salaryAdvance.toFixed(2)}`;
    document.getElementById('up_live_deductions').innerText = `${currency} ${totalDeductions.toFixed(2)}`;
    document.getElementById('up_live_net').innerText = `${currency} ${netSalary.toFixed(2)}`;
}

async function saveUpdateModal(status = 'draft') {
    if (!activeRow) return;
    
    const btn = status === 'paid' ? document.getElementById('btnConfirmUpdate') : document.getElementById('btnSaveUpdate');
    setLoading(btn, true);
    
    const prodIncentive = parseFloat(document.getElementById('up_prod_incentive').value) || 0;
    const otherAllow = parseFloat(document.getElementById('up_other_allowances').value) || 0;
    const otherDeductions = parseFloat(document.getElementById('up_other_deductions').value) || 0;
    
    const cycleSelect = document.getElementById('payroll_cycle_period');
    const [year, month] = cycleSelect.value.split('-');
    
    const data = {
        action: 'save_adjustment',
        employee_id: activeRow.employee_id,
        month: month,
        year: year,
        production_incentive: prodIncentive,
        other_allowances: otherAllow,
        other_deductions: otherDeductions,
        status: status
    };
    
    const res = await apiCall('payroll', data);
    setLoading(btn, false);
    
    if (res.success) {
        notify(res.message, 'success');
        closeModal('updatePayrollModal');
        loadPayroll();
    } else {
        notify(res.message || 'Error updating adjustments', 'error');
    }
}

async function openPayslipModal(employeeId) {
    const row = currentPayrollData.find(r => r.employee_id == employeeId);
    if (!row) return;
    
    // Fetch config for EPF & ETF percentages
    if (!payrollConfigCache) {
        const res = await apiCall('payroll', { action: 'get_config' });
        if (res.success && res.config) {
            payrollConfigCache = res.config;
        }
    }
    let epfEePct = 0;
    let epfErPct = 0;
    let etfPct = 0;
    if (payrollConfigCache) {
        epfEePct = parseFloat(payrollConfigCache.epf_employee_percent || 0);
        epfErPct = parseFloat(payrollConfigCache.epf_employer_percent || 0);
        etfPct = parseFloat(payrollConfigCache.etf_percent || 0);
    }
    document.getElementById('lbl_ps_epf_ee').innerText = `EPF (Employee share ${epfEePct}%)`;
    document.getElementById('lbl_ps_epf_er').innerText = `Employer EPF Liability (${epfErPct}%):`;
    document.getElementById('lbl_ps_etf_er').innerText = `Employer ETF Liability (${etfPct}%):`;
    
    const currency = window.APP_CONFIG ? window.APP_CONFIG.COMPANY_CURRENCY || '$' : '$';
    const periodSelect = document.getElementById('payroll_cycle_period');
    const periodText = periodSelect.options[periodSelect.selectedIndex].text;
    
    // Set currency labels
    document.querySelectorAll('.ps-currency-label').forEach(el => {
        el.textContent = currency;
    });
    
    // Set texts
    document.getElementById('ps_period').innerText = `Pay Period: ${periodText}`;
    document.getElementById('ps_emp_id').innerText = `EMP-${String(row.employee_id).padStart(4, '0')}`;
    document.getElementById('ps_name').innerText = row.name;
    document.getElementById('ps_hourly_rate').innerText = `${currency} ${parseFloat(row.hourly_rate).toFixed(2)}`;
    document.getElementById('ps_days_present').innerText = `${row.days_present} / ${row.total_working_days}`;
    
    // Earnings
    document.getElementById('ps_base_salary').innerText = parseFloat(row.base_salary).toFixed(2);
    document.getElementById('ps_ot_pay').innerText = parseFloat(row.ot_pay || 0).toFixed(2);
    document.getElementById('ps_attn_incentive').innerText = parseFloat(row.attendance_incentive || 0).toFixed(2);
    document.getElementById('ps_prod_incentive').innerText = parseFloat(row.production_incentive || 0).toFixed(2);
    document.getElementById('ps_other_allowances').innerText = parseFloat(row.other_allowances || 0).toFixed(2);
    
    const allowances = parseFloat(row.attendance_incentive || 0) + parseFloat(row.production_incentive || 0) + parseFloat(row.other_allowances || 0);
    const grossSalary = parseFloat(row.base_salary) + parseFloat(row.ot_pay || 0) + allowances;
    document.getElementById('ps_gross_salary').innerText = grossSalary.toFixed(2);
    
    // Deductions
    const noPayVal = parseFloat(row.no_pay || 0);
    document.getElementById('ps_no_pay').innerText = noPayVal.toFixed(2);
    document.getElementById('ps_epf_ee').innerText = parseFloat(row.epf_employee_amount || 0).toFixed(2);
    document.getElementById('ps_salary_advance').innerText = parseFloat(row.salary_advance || 0).toFixed(2);
    document.getElementById('ps_other_deductions').innerText = parseFloat(row.other_deductions || 0).toFixed(2);
    
    const salaryAdvance = parseFloat(row.salary_advance || 0);
    const totalDeductions = parseFloat(row.epf_employee_amount || 0) + parseFloat(row.other_deductions || 0) + noPayVal;
    document.getElementById('ps_total_deductions').innerText = totalDeductions.toFixed(2);
    
    // Net Salary
    const netSalary = grossSalary - salaryAdvance - totalDeductions;
    document.getElementById('ps_net_salary').innerText = `${currency} ${netSalary.toFixed(2)}`;
    
    // Employer Contributions
    document.getElementById('ps_epf_er').innerText = `${currency} ${parseFloat(row.epf_employer_amount || 0).toFixed(2)}`;
    document.getElementById('ps_etf_er').innerText = `${currency} ${parseFloat(row.etf_amount || 0).toFixed(2)}`;
    
    openModal('payslipModal');
}

function printPayslip() {
    const printArea = document.getElementById('payslipPrintArea');
    
    const printWindow = window.open('', '_blank', 'width=800,height=600');
    printWindow.document.write(`
        <html>
        <head>
            <title>Employee Payslip</title>
            <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800;900&display=swap" rel="stylesheet">
            <style>
                body {
                    margin: 0;
                    padding: 20px;
                    background: #ffffff;
                    font-family: 'Inter', sans-serif;
                    -webkit-print-color-adjust: exact;
                    print-color-adjust: exact;
                }
                @media print {
                    body {
                        padding: 0;
                    }
                    .no-print {
                        display: none;
                    }
                }
            </style>
        </head>
        <body>
            ${printArea.innerHTML}
            <script>
                window.onload = function() {
                    window.print();
                    setTimeout(function() { window.close(); }, 500);
                };
            <\/script>
        </body>
        </html>
    `);
    printWindow.document.close();
}

async function processPayrollPayments() {
    const cycleSelect = document.getElementById('payroll_cycle_period');
    if (!cycleSelect || !cycleSelect.value) return;
    
    const [year, month] = cycleSelect.value.split('-');
    const cycleLabel = cycleSelect.options[cycleSelect.selectedIndex].text;
    
    const proceed = await confirmAction({
        title: 'Confirm Payroll Cycle',
        message: `Are you sure you want to lock and finalize payroll for cycle "${cycleLabel}"? All allowance and deduction inputs will be locked, and employees' status will change to CONFIRMED.`,
        confirmText: 'Confirm & Lock',
        confirmClass: 'var(--success)'
    });
    
    if (proceed) {
        const btn = document.getElementById('btnMarkPaid');
        setLoading(btn, true);
        
        const res = await apiCall('payroll', { action: 'mark_paid', month: month, year: year });
        setLoading(btn, false);
        
        if (res.success) {
            notify(res.message, 'success');
            loadPayroll();
        } else {
            notify(res.message, 'error');
        }
    }
}

async function markCyclePaid() {
    const cycleSelect = document.getElementById('payroll_cycle_period');
    if (!cycleSelect || !cycleSelect.value) return;

    const [year, month] = cycleSelect.value.split('-');
    const cycleLabel = cycleSelect.options[cycleSelect.selectedIndex].text;

    const proceed = await confirmAction({
        title: 'Mark Payroll Cycle as Paid',
        message: `Are you sure you want to mark all confirmed payroll records for cycle "${cycleLabel}" as PAID? This action cannot be undone.`,
        confirmText: 'Mark as Paid',
        confirmClass: '#10B981'
    });

    if (proceed) {
        const btn = document.getElementById('btnCyclePaid');
        setLoading(btn, true);

        const res = await apiCall('payroll', { action: 'mark_cycle_paid', month: month, year: year });
        setLoading(btn, false);

        if (res.success) {
            notify(res.message, 'success');
            loadPayroll();
        } else {
            notify(res.message, 'error');
        }
    }
}

async function downloadPayrollSheet() {
    const cycleSelect = document.getElementById('payroll_cycle_period');
    if (!cycleSelect || !cycleSelect.value) return;

    const [year, month] = cycleSelect.value.split('-');
    const cycleLabel = cycleSelect.options[cycleSelect.selectedIndex].text;

    const btn = document.getElementById('btnDownloadPayroll');
    setLoading(btn, true);

    const res = await apiCall('payroll', { action: 'export_payroll', month: month, year: year });
    setLoading(btn, false);

    if (!res.success || !res.records || res.records.length === 0) {
        notify(res.message || 'No confirmed payroll records to export.', 'error');
        return;
    }

    const currency = window.APP_CONFIG ? window.APP_CONFIG.COMPANY_CURRENCY || '' : '';
    const periodLabel = `${res.period_start} to ${res.period_end}`;

    // Build CSV content
    const headers = [
        'Emp ID', 'Employee Name', 'Hourly Rate',
        'Working Days', 'Days Present', 'Days Absent',
        'Regular Hours', 'OT Hours', 'OT Pay',
        'Base Salary', 'Attendance Incentive', 'Production Incentive',
        'Other Allowances', 'Total Allowances',
        'No-Pay Cut', 'EPF (Employee)', 'EPF (Employer)', 'ETF (Employer)',
        'Other Deductions', 'Total Deductions',
        'Salary Advance (Total)', 'Net Salary', 'Status'
    ];

    const rows = res.records.map(r => [
        `EMP-${String(r.employee_id).padStart(4, '0')}`,
        r.name,
        parseFloat(r.hourly_rate || 0).toFixed(2),
        r.total_working_days,
        r.days_present,
        r.days_absent,
        parseFloat(r.regular_hours || 0).toFixed(2),
        parseFloat(r.ot_hours || 0).toFixed(2),
        parseFloat(r.ot_pay || 0).toFixed(2),
        parseFloat(r.base_salary || 0).toFixed(2),
        parseFloat(r.attendance_incentive || 0).toFixed(2),
        parseFloat(r.production_incentive || 0).toFixed(2),
        parseFloat(r.other_allowances || 0).toFixed(2),
        parseFloat(r.allowances || 0).toFixed(2),
        parseFloat(r.no_pay || 0).toFixed(2),
        parseFloat(r.epf_employee_amount || 0).toFixed(2),
        parseFloat(r.epf_employer_amount || 0).toFixed(2),
        parseFloat(r.etf_amount || 0).toFixed(2),
        parseFloat(r.other_deductions || 0).toFixed(2),
        parseFloat(r.deductions || 0).toFixed(2),
        parseFloat(r.salary_advance || 0).toFixed(2),
        parseFloat(r.net_salary || 0).toFixed(2),
        r.status.toUpperCase()
    ]);

    // Add totals row
    const totalsRow = [
        '', 'TOTALS', '',
        '', '', '',
        '', '', rows.reduce((s, r) => s + parseFloat(r[8]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[9]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[10]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[11]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[12]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[13]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[14]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[15]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[16]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[17]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[18]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[19]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[20]), 0).toFixed(2),
        rows.reduce((s, r) => s + parseFloat(r[21]), 0).toFixed(2),
        ''
    ];

    const escape = v => `"${String(v).replace(/"/g, '""')}"`;

    const csvLines = [
        `"Payroll Sheet - ${cycleLabel}"`,
        `"Period: ${periodLabel}"`,
        `"Generated: ${new Date().toLocaleString()}"`,
        '',
        headers.map(escape).join(','),
        ...rows.map(r => r.map(escape).join(',')),
        totalsRow.map(escape).join(',')
    ];

    const csvContent = csvLines.join('\n');
    const bom = '\uFEFF'; // UTF-8 BOM for Excel compatibility
    const blob = new Blob([bom + csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.href = url;
    a.download = `Payroll_${res.period_start}_to_${res.period_end}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    notify('Payroll sheet downloaded successfully!', 'success');
}

async function loadConfiguration() {
    const res = await apiCall('payroll', { action: 'get_config' });
    if (res.success && res.config) {
        payrollConfigCache = res.config;
        document.getElementById('cfg_paid_working_days').value = res.config.paid_working_days !== null ? res.config.paid_working_days : '';
        document.getElementById('cfg_epf_employee_percent').value = parseFloat(res.config.epf_employee_percent).toFixed(2);
        document.getElementById('cfg_epf_employer_percent').value = parseFloat(res.config.epf_employer_percent).toFixed(2);
        document.getElementById('cfg_etf_percent').value = parseFloat(res.config.etf_percent).toFixed(2);
        document.getElementById('cfg_cycle_start_day').value = res.config.cycle_start_day;
        document.getElementById('cfg_cycle_end_day').value = res.config.cycle_end_day;
        document.getElementById('cfg_attendance_incentive_perfect').value = parseFloat(res.config.attendance_incentive_perfect || 0).toFixed(2);
        document.getElementById('cfg_attendance_incentive_one_absent').value = parseFloat(res.config.attendance_incentive_one_absent || 0).toFixed(2);
    } else {
        notify('Failed to load configuration settings.', 'error');
    }
}

async function saveConfiguration(event) {
    event.preventDefault();
    const btn = document.getElementById('btnSaveConfig');
    setLoading(btn, true);
    
    const paid_working_days = document.getElementById('cfg_paid_working_days').value;
    const epf_employee_percent = document.getElementById('cfg_epf_employee_percent').value;
    const epf_employer_percent = document.getElementById('cfg_epf_employer_percent').value;
    const etf_percent = document.getElementById('cfg_etf_percent').value;
    const cycle_start_day = document.getElementById('cfg_cycle_start_day').value;
    const cycle_end_day = document.getElementById('cfg_cycle_end_day').value;
    const attendance_incentive_perfect = document.getElementById('cfg_attendance_incentive_perfect').value;
    const attendance_incentive_one_absent = document.getElementById('cfg_attendance_incentive_one_absent').value;
    
    const data = {
        action: 'save_config',
        paid_working_days: paid_working_days === '' ? null : paid_working_days,
        epf_employee_percent: epf_employee_percent,
        epf_employer_percent: epf_employer_percent,
        etf_percent: etf_percent,
        cycle_start_day: cycle_start_day,
        cycle_end_day: cycle_end_day,
        attendance_incentive_perfect: attendance_incentive_perfect,
        attendance_incentive_one_absent: attendance_incentive_one_absent
    };
    
    const res = await apiCall('payroll', data);
    setLoading(btn, false);
    
    if (res.success) {
        notify(res.message, 'success');
        payrollConfigCache = null;
    } else {
        notify(res.message, 'error');
    }
}

async function initPayrollCycles() {
    const select = document.getElementById('payroll_cycle_period');
    if (!select) return;
    const previousValue = select.value || '';
    
    // Fetch config
    let startDay = 1;
    let endDay = 0;
    const res = await apiCall('payroll', { action: 'get_config' });
    if (res.success && res.config) {
        startDay = parseInt(res.config.cycle_start_day) || 1;
        endDay = parseInt(res.config.cycle_end_day) || 0;
    }
    
    select.innerHTML = '';
    
    const now = new Date();
    let currentYear = now.getFullYear();
    let currentMonth = now.getMonth() + 1; // 1-indexed
    const dayOfMonth = now.getDate();
    
    let targetMonth = currentMonth;
    let targetYear = currentYear;
    
    if (startDay > 1) {
        if (dayOfMonth >= startDay) {
            targetMonth = currentMonth + 1;
            if (targetMonth > 12) {
                targetMonth = 12;
                targetYear = currentYear;
            }
        }
    }
    
    let iterMonth = targetMonth;
    let iterYear = targetYear;
    
    const monthNames = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ];
    
    let hasMatchedPrevious = false;
    
    while (iterYear === currentYear) {
        let firstDay, lastDay;
        
        if (startDay === 1) {
            firstDay = new Date(iterYear, iterMonth - 1, 1);
            lastDay = new Date(iterYear, iterMonth, 0);
        } else {
            let prevM = iterMonth - 1;
            let prevY = iterYear;
            if (prevM === 0) {
                prevM = 12;
                prevY = iterYear - 1;
            }
            firstDay = new Date(prevY, prevM - 1, startDay);
            
            let actualEndDay = endDay > 0 ? endDay : (startDay - 1);
            let daysInIterMonth = new Date(iterYear, iterMonth, 0).getDate();
            if (actualEndDay > daysInIterMonth) {
                actualEndDay = daysInIterMonth;
            }
            lastDay = new Date(iterYear, iterMonth - 1, actualEndDay);
        }
        
        const option = document.createElement('option');
        option.value = `${iterYear}-${iterMonth}`;
        
        const startStr = `${monthNames[firstDay.getMonth()]} ${firstDay.getDate()}, ${firstDay.getFullYear()}`;
        const endStr = `${monthNames[lastDay.getMonth()]} ${lastDay.getDate()}, ${lastDay.getFullYear()}`;
        option.text = `${startStr} - ${endStr}`;
        
        if (option.value === previousValue) {
            option.selected = true;
            hasMatchedPrevious = true;
        } else if (select.options.length === 0 && !previousValue) {
            option.selected = true;
        }
        
        select.appendChild(option);
        
        iterMonth--;
        if (iterMonth === 0) {
            iterMonth = 12;
            iterYear--;
        }
    }
    
    if (previousValue && !hasMatchedPrevious && select.options.length > 0) {
        select.options[0].selected = true;
    }
    updatePayrollCycleText();
}

// Initialize
document.addEventListener('DOMContentLoaded', async () => {
    await initPayrollCycles();
    await loadPayroll();
});
</script>
