<?php
include '../../includes/header.php';
require_once __DIR__ . '/_module.php';

payrollRequireAdmin($auth);

$payroll = new Payroll($conn);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_payslip_id'])) {
    $psId = (int)$_POST['edit_payslip_id'];
    $ok = $psId > 0 && $payroll->updatePayslip($psId, $_POST);
    $runId = isset($_GET['run_id']) ? '?run_id=' . (int)$_GET['run_id'] : '';
    header('Location: payslips.php' . $runId . ($ok ? '&msg=updated' : '&msg=error'));
    exit();
}

$payslips = $payroll->getPayslips(isset($_GET['run_id']) ? (int)$_GET['run_id'] : null);

payrollModuleStyles();
?>

<div class="container-fluid px-4">
    <?php payrollModuleNav('payslips'); ?>

    <div class="payroll-page-head">
        <div>
            <h1>Payslips</h1>
            <p>Review employee payroll statements, deductions, and net pay by run.</p>
        </div>
        <div class="no-print">
            <a href="pay_runs.php" class="btn btn-outline-secondary"><i class="fas fa-file-invoice-dollar"></i> Pay Runs</a>
            <button type="button" class="btn btn-outline-secondary" onclick="window.print()"><i class="fas fa-print"></i> Print</button>
        </div>
    </div>

    <?php if (isset($_GET['msg'])): ?>
        <div class="alert alert-<?php echo $_GET['msg'] === 'updated' ? 'success' : 'danger'; ?> alert-dismissible fade show no-print" role="alert">
            <?php echo $_GET['msg'] === 'updated' ? 'Payslip updated successfully.' : 'Failed to update payslip. Please try again.'; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php payrollMigrationNotice($payroll, ['payroll_payslips'], 'Payslip storage requires the professional payroll schema.'); ?>

    <div class="payroll-panel">
        <div class="table-responsive">
            <table class="table table-bordered payroll-table">
                <thead>
                    <tr>
                        <th>Run</th>
                        <th>Employee</th>
                        <th>Basic</th>
                        <th>Allowances</th>
                        <th>Gross</th>
                        <th>PAYE</th>
                        <th>Loans</th>
                        <th>Deductions</th>
                        <th>Net</th>
                        <th>Status</th>
                        <th class="no-print">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($payslips)): ?>
                        <?php foreach ($payslips as $payslip): ?>
                            <tr>
                                <td><?php echo payrollText($payslip['run_number'] ?? ''); ?></td>
                                <td><?php echo payrollText($payslip['employee_fullname'] ?? ''); ?></td>
                                <td><?php echo payrollMoney($payslip['basic_salary'] ?? 0); ?></td>
                                <td><?php echo payrollMoney($payslip['allowances'] ?? 0); ?></td>
                                <td><?php echo payrollMoney($payslip['gross_pay'] ?? 0); ?></td>
                                <td><?php echo payrollMoney($payslip['tax_amount'] ?? 0); ?></td>
                                <td><?php echo payrollMoney($payslip['loan_deduction'] ?? 0); ?></td>
                                <td><?php echo payrollMoney($payslip['total_deductions'] ?? 0); ?></td>
                                <td><?php echo payrollMoney($payslip['net_pay'] ?? 0); ?></td>
                                <td><?php echo payrollStatusBadge($payslip['payment_status'] ?? 'unpaid'); ?></td>
                                <td class="no-print">
                                    <?php $psData = htmlspecialchars(json_encode([
                                            'payslip_id'      => $payslip['payslip_id'] ?? '',
                                            'run_number'      => $payslip['run_number'] ?? '',
                                            'pay_date'        => $payslip['pay_date'] ?? '',
                                            'pay_period_start'=> $payslip['pay_period_start'] ?? '',
                                            'pay_period_end'  => $payslip['pay_period_end'] ?? '',
                                            'currency_code'   => $payslip['currency_code'] ?? 'MWK',
                                            'employee_fullname'=> $payslip['employee_fullname'] ?? '',
                                            'employee_position'=> $payslip['employee_position'] ?? '',
                                            'employee_code'   => $payslip['employee_code'] ?? '',
                                            'department_name' => $payslip['department_name'] ?? '',
                                            'branch_name'     => $payslip['branch_name'] ?? '',
                                            'branch_logo'     => Branding::branchLogoUrl($payslip),
                                            'company_name'    => Branding::branchCompanyName($payslip),
                                            'basic_salary'    => $payslip['basic_salary'] ?? 0,
                                            'allowances'      => $payslip['allowances'] ?? 0,
                                            'overtime_pay'    => $payslip['overtime_pay'] ?? 0,
                                            'gross_pay'       => $payslip['gross_pay'] ?? 0,
                                            'pension_employee'=> $payslip['pension_employee'] ?? 0,
                                            'tax_amount'      => $payslip['tax_amount'] ?? 0,
                                            'loan_deduction'  => $payslip['loan_deduction'] ?? 0,
                                            'other_deductions'=> $payslip['other_deductions'] ?? 0,
                                            'total_deductions'=> $payslip['total_deductions'] ?? 0,
                                            'net_pay'         => $payslip['net_pay'] ?? 0,
                                            'payment_status'  => $payslip['payment_status'] ?? 'unpaid',
                                        ]), ENT_QUOTES, 'UTF-8'); ?>
                                    <button type="button" class="btn btn-sm btn-primary view-payslip-btn"
                                        data-payslip='<?php echo $psData; ?>'>
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                    <button type="button" class="btn btn-sm btn-secondary edit-payslip-btn"
                                        data-payslip='<?php echo $psData; ?>'>
                                        <i class="fas fa-edit"></i> Edit
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="11" class="text-center">No payslips found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php payrollModuleEnd(); ?>
</div>

<?php
function psDate($d) {
    if (!$d) return '—';
    $p = explode('-', $d);
    if (count($p) === 3) {
        $m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
        return $p[2] . ' ' . $m[(int)$p[1] - 1] . ' ' . $p[0];
    }
    return $d;
}
function psMoney($amount, $cur = 'MWK') {
    return htmlspecialchars($cur) . ' ' . number_format((float)$amount, 2);
}
?>

<!-- Print-all payslips (hidden on screen, shown on print) -->
<div id="print-all-payslips">
<?php if (!empty($payslips)): ?>
    <?php foreach ($payslips as $ps): ?>
    <?php $cur = htmlspecialchars($ps['currency_code'] ?? 'MWK'); ?>
    <div class="print-payslip-page">
        <div class="payslip-doc">

            <div class="payslip-header">
                <div class="payslip-logo-area">
                    <img id="ps-logo" src="<?php echo htmlspecialchars(Branding::logoUrl()); ?>" alt="Logo" class="payslip-logo">
                </div>
                <div class="payslip-company-info">
                <div id="ps-company-name" class="payslip-company-name"><?php echo htmlspecialchars(Branding::companyName()); ?></div>
                    <div class="payslip-doc-title">PAYSLIP / SALARY ADVICE</div>
                </div>
            </div>

            <div class="payslip-divider"></div>

            <div class="payslip-meta-row">
                <div class="payslip-meta-item">
                    <span class="payslip-meta-label">Payslip Ref</span>
                    <span class="payslip-meta-value"><?php echo payrollText($ps['run_number'] ?? ''); ?></span>
                </div>
                <div class="payslip-meta-item">
                    <span class="payslip-meta-label">Pay Period</span>
                    <span class="payslip-meta-value"><?php echo psDate($ps['pay_period_start'] ?? ''); ?> – <?php echo psDate($ps['pay_period_end'] ?? ''); ?></span>
                </div>
                <div class="payslip-meta-item">
                    <span class="payslip-meta-label">Pay Date</span>
                    <span class="payslip-meta-value"><?php echo psDate($ps['pay_date'] ?? ''); ?></span>
                </div>
                <div class="payslip-meta-item">
                    <span class="payslip-meta-label">Currency</span>
                    <span class="payslip-meta-value"><?php echo $cur; ?></span>
                </div>
            </div>

            <div class="payslip-divider"></div>

            <div class="payslip-section-title">Employee Details</div>
            <div class="payslip-employee-grid">
                <div class="payslip-employee-item">
                    <span class="payslip-meta-label">Full Name</span>
                    <span class="payslip-meta-value"><?php echo payrollText($ps['employee_fullname'] ?? ''); ?></span>
                </div>
                <div class="payslip-employee-item">
                    <span class="payslip-meta-label">Employee Code</span>
                    <span class="payslip-meta-value"><?php echo payrollText($ps['employee_code'] ?? ''); ?></span>
                </div>
                <div class="payslip-employee-item">
                    <span class="payslip-meta-label">Position</span>
                    <span class="payslip-meta-value"><?php echo payrollText($ps['employee_position'] ?? ''); ?></span>
                </div>
                <div class="payslip-employee-item">
                    <span class="payslip-meta-label">Department</span>
                    <span class="payslip-meta-value"><?php echo payrollText($ps['department_name'] ?? ''); ?></span>
                </div>
                <div class="payslip-employee-item">
                    <span class="payslip-meta-label">Branch</span>
                    <span class="payslip-meta-value"><?php echo payrollText($ps['branch_name'] ?? ''); ?></span>
                </div>
                <div class="payslip-employee-item">
                    <span class="payslip-meta-label">Payment Status</span>
                    <span class="payslip-meta-value"><?php echo strtoupper(htmlspecialchars($ps['payment_status'] ?? 'unpaid')); ?></span>
                </div>
            </div>

            <div class="payslip-divider"></div>

            <div class="payslip-columns">
                <div class="payslip-col">
                    <div class="payslip-section-title">Earnings</div>
                    <table class="payslip-table">
                        <tbody>
                            <tr><td>Basic Salary</td><td class="text-end"><?php echo psMoney($ps['basic_salary'] ?? 0, $cur); ?></td></tr>
                            <tr><td>Allowances</td><td class="text-end"><?php echo psMoney($ps['allowances'] ?? 0, $cur); ?></td></tr>
                            <tr><td>Overtime Pay</td><td class="text-end"><?php echo psMoney($ps['overtime_pay'] ?? 0, $cur); ?></td></tr>
                            <tr class="payslip-subtotal">
                                <td><strong>Gross Pay</strong></td>
                                <td class="text-end"><strong><?php echo psMoney($ps['gross_pay'] ?? 0, $cur); ?></strong></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="payslip-col">
                    <div class="payslip-section-title">Deductions</div>
                    <table class="payslip-table">
                        <tbody>
                            <tr><td>PAYE Tax</td><td class="text-end"><?php echo psMoney($ps['tax_amount'] ?? 0, $cur); ?></td></tr>
                            <tr><td>Pension</td><td class="text-end"><?php echo psMoney($ps['pension_employee'] ?? 0, $cur); ?></td></tr>
                            <tr><td>Loan Deduction</td><td class="text-end"><?php echo psMoney($ps['loan_deduction'] ?? 0, $cur); ?></td></tr>
                            <tr><td>Other Deductions</td><td class="text-end"><?php echo psMoney($ps['other_deductions'] ?? 0, $cur); ?></td></tr>
                            <tr class="payslip-subtotal">
                                <td><strong>Total Deductions</strong></td>
                                <td class="text-end"><strong><?php echo psMoney($ps['total_deductions'] ?? 0, $cur); ?></strong></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="payslip-net-pay-row">
                <span class="payslip-net-label">NET PAY</span>
                <span class="payslip-net-value"><?php echo psMoney($ps['net_pay'] ?? 0, $cur); ?></span>
            </div>

            <div class="payslip-footer-note">
                This is a computer-generated payslip and does not require a physical signature.
            </div>

        </div>
    </div>
    <?php endforeach; ?>
<?php endif; ?>
</div>

<!-- Edit Payslip Modal -->
<div class="modal fade" id="editPayslipModal" tabindex="-1" aria-labelledby="editPayslipModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editPayslipModalLabel">Edit Payslip</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" id="editPayslipForm">
                <input type="hidden" name="edit_payslip_id" id="ep-id">
                <div class="modal-body">
                    <div class="mb-3 text-muted small" id="ep-employee-label"></div>
                    <div class="row g-3">
                        <div class="col-12">
                            <h6 class="text-uppercase fw-bold" style="font-size:11px;letter-spacing:.08em;color:#495057;background:#f8f9fa;padding:5px 8px;border-left:3px solid #1a1a2e;">Earnings</h6>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Basic Salary</label>
                            <input type="number" step="0.01" min="0" class="form-control ep-calc" name="basic_salary" id="ep-basic">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Allowances</label>
                            <input type="number" step="0.01" min="0" class="form-control ep-calc" name="allowances" id="ep-allowances">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Overtime Pay</label>
                            <input type="number" step="0.01" min="0" class="form-control ep-calc" name="overtime_pay" id="ep-overtime">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Gross Pay</label>
                            <input type="text" class="form-control bg-light" id="ep-gross-display" readonly tabindex="-1">
                        </div>
                        <div class="col-12">
                            <h6 class="text-uppercase fw-bold mt-2" style="font-size:11px;letter-spacing:.08em;color:#495057;background:#f8f9fa;padding:5px 8px;border-left:3px solid #1a1a2e;">Deductions</h6>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">PAYE Tax</label>
                            <input type="number" step="0.01" min="0" class="form-control ep-calc" name="tax_amount" id="ep-tax">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Pension</label>
                            <input type="number" step="0.01" min="0" class="form-control ep-calc" name="pension_employee" id="ep-pension">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Loan Deduction</label>
                            <input type="number" step="0.01" min="0" class="form-control ep-calc" name="loan_deduction" id="ep-loan">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Other Deductions</label>
                            <input type="number" step="0.01" min="0" class="form-control ep-calc" name="other_deductions" id="ep-other">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Total Deductions</label>
                            <input type="text" class="form-control bg-light" id="ep-totalded-display" readonly tabindex="-1">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold">Net Pay</label>
                            <input type="text" class="form-control bg-light fw-bold" id="ep-net-display" readonly tabindex="-1">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Payment Status</label>
                            <select class="form-select" name="payment_status" id="ep-status">
                                <option value="unpaid">Unpaid</option>
                                <option value="paid">Paid</option>
                                <option value="cancelled">Cancelled</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Payslip Modal -->
<div class="modal fade" id="payslipModal" tabindex="-1" aria-labelledby="payslipModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header no-print">
                <h5 class="modal-title" id="payslipModalLabel">Employee Payslip</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-0">
                <div id="payslip-document" class="payslip-doc">

                    <!-- Company Header -->
                    <div class="payslip-header">
                        <div class="payslip-logo-area">
                            <img id="ep-logo" src="<?php echo htmlspecialchars(Branding::logoUrl()); ?>" alt="Logo" class="payslip-logo">
                        </div>
                        <div class="payslip-company-info">
                            <div id="ep-company-name" class="payslip-company-name"><?php echo htmlspecialchars(Branding::companyName()); ?></div>
                            <div class="payslip-doc-title">PAYSLIP / SALARY ADVICE</div>
                        </div>
                    </div>

                    <div class="payslip-divider"></div>

                    <!-- Run & Period Info -->
                    <div class="payslip-meta-row">
                        <div class="payslip-meta-item">
                            <span class="payslip-meta-label">Payslip Ref</span>
                            <span class="payslip-meta-value" id="ps-run-number">—</span>
                        </div>
                        <div class="payslip-meta-item">
                            <span class="payslip-meta-label">Pay Period</span>
                            <span class="payslip-meta-value" id="ps-pay-period">—</span>
                        </div>
                        <div class="payslip-meta-item">
                            <span class="payslip-meta-label">Pay Date</span>
                            <span class="payslip-meta-value" id="ps-pay-date">—</span>
                        </div>
                        <div class="payslip-meta-item">
                            <span class="payslip-meta-label">Currency</span>
                            <span class="payslip-meta-value" id="ps-currency">MWK</span>
                        </div>
                    </div>

                    <div class="payslip-divider"></div>

                    <!-- Employee Details -->
                    <div class="payslip-section-title">Employee Details</div>
                    <div class="payslip-employee-grid">
                        <div class="payslip-employee-item">
                            <span class="payslip-meta-label">Full Name</span>
                            <span class="payslip-meta-value" id="ps-fullname">—</span>
                        </div>
                        <div class="payslip-employee-item">
                            <span class="payslip-meta-label">Employee Code</span>
                            <span class="payslip-meta-value" id="ps-code">—</span>
                        </div>
                        <div class="payslip-employee-item">
                            <span class="payslip-meta-label">Position</span>
                            <span class="payslip-meta-value" id="ps-position">—</span>
                        </div>
                        <div class="payslip-employee-item">
                            <span class="payslip-meta-label">Department</span>
                            <span class="payslip-meta-value" id="ps-department">—</span>
                        </div>
                        <div class="payslip-employee-item">
                            <span class="payslip-meta-label">Branch</span>
                            <span class="payslip-meta-value" id="ps-branch">—</span>
                        </div>
                        <div class="payslip-employee-item">
                            <span class="payslip-meta-label">Payment Status</span>
                            <span class="payslip-meta-value" id="ps-status">—</span>
                        </div>
                    </div>

                    <div class="payslip-divider"></div>

                    <!-- Earnings & Deductions -->
                    <div class="payslip-columns">
                        <div class="payslip-col">
                            <div class="payslip-section-title">Earnings</div>
                            <table class="payslip-table">
                                <tbody>
                                    <tr>
                                        <td>Basic Salary</td>
                                        <td class="text-end" id="ps-basic">—</td>
                                    </tr>
                                    <tr>
                                        <td>Allowances</td>
                                        <td class="text-end" id="ps-allowances">—</td>
                                    </tr>
                                    <tr>
                                        <td>Overtime Pay</td>
                                        <td class="text-end" id="ps-overtime">—</td>
                                    </tr>
                                    <tr class="payslip-subtotal">
                                        <td><strong>Gross Pay</strong></td>
                                        <td class="text-end"><strong id="ps-gross">—</strong></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="payslip-col">
                            <div class="payslip-section-title">Deductions</div>
                            <table class="payslip-table">
                                <tbody>
                                    <tr>
                                        <td>PAYE Tax</td>
                                        <td class="text-end" id="ps-tax">—</td>
                                    </tr>
                                    <tr>
                                        <td>Pension</td>
                                        <td class="text-end" id="ps-pension">—</td>
                                    </tr>
                                    <tr>
                                        <td>Loan Deduction</td>
                                        <td class="text-end" id="ps-loan">—</td>
                                    </tr>
                                    <tr>
                                        <td>Other Deductions</td>
                                        <td class="text-end" id="ps-other">—</td>
                                    </tr>
                                    <tr class="payslip-subtotal">
                                        <td><strong>Total Deductions</strong></td>
                                        <td class="text-end"><strong id="ps-total-ded">—</strong></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Net Pay -->
                    <div class="payslip-net-pay-row">
                        <span class="payslip-net-label">NET PAY</span>
                        <span class="payslip-net-value" id="ps-net">—</span>
                    </div>

                    <!-- Footer note -->
                    <div class="payslip-footer-note">
                        This is a computer-generated payslip and does not require a physical signature.
                    </div>

                </div>
            </div>
            <div class="modal-footer no-print">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" onclick="printPayslip()"><i class="fas fa-print"></i> Print Payslip</button>
            </div>
        </div>
    </div>
</div>

<style>
.payslip-doc {
    background: #fff;
    font-family: 'Segoe UI', Arial, sans-serif;
    font-size: 13px;
    color: #212529;
    padding: 32px 36px;
}

.payslip-header {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 12px;
}

.payslip-logo {
    height: 60px;
    width: auto;
    object-fit: contain;
}

.payslip-company-name {
    font-size: 20px;
    font-weight: 700;
    color: #1a1a2e;
    letter-spacing: 0.02em;
}

.payslip-doc-title {
    font-size: 12px;
    letter-spacing: 0.12em;
    color: #6c757d;
    text-transform: uppercase;
    margin-top: 2px;
}

.payslip-divider {
    border-top: 2px solid #1a1a2e;
    margin: 12px 0;
}

.payslip-meta-row {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
    margin: 12px 0;
}

.payslip-meta-item, .payslip-employee-item {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.payslip-meta-label {
    font-size: 10px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    color: #6c757d;
}

.payslip-meta-value {
    font-size: 13px;
    color: #212529;
    font-weight: 500;
}

.payslip-section-title {
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: #495057;
    background: #f8f9fa;
    padding: 5px 8px;
    margin-bottom: 6px;
    border-left: 3px solid #1a1a2e;
}

.payslip-employee-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px 24px;
    margin: 10px 0;
}

.payslip-columns {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin: 10px 0;
}

.payslip-table {
    width: 100%;
    border-collapse: collapse;
}

.payslip-table td {
    padding: 5px 4px;
    border-bottom: 1px solid #f0f0f0;
    font-size: 13px;
}

.payslip-subtotal td {
    border-top: 1.5px solid #dee2e6;
    border-bottom: 1.5px solid #dee2e6;
    background: #f8f9fa;
    padding-top: 6px;
    padding-bottom: 6px;
}

.payslip-net-pay-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #1a1a2e;
    color: #fff;
    padding: 14px 16px;
    margin-top: 16px;
    border-radius: 2px;
}

.payslip-net-label {
    font-size: 14px;
    font-weight: 700;
    letter-spacing: 0.1em;
}

.payslip-net-value {
    font-size: 20px;
    font-weight: 700;
    letter-spacing: 0.02em;
}

.payslip-footer-note {
    font-size: 10px;
    color: #adb5bd;
    text-align: center;
    margin-top: 20px;
    padding-top: 10px;
    border-top: 1px solid #dee2e6;
}

@media screen {
    #print-all-payslips { display: none; }
}

@media print {
    .modal, .modal-backdrop, .navbar, .payroll-sidebar,
    .payroll-page-head, .payroll-panel, .no-print,
    .modal-header, .modal-footer { display: none !important; }

    .payroll-shell, .payroll-main, .container-fluid,
    .app-page-container { display: block !important; padding: 0 !important; margin: 0 !important; }

    #print-all-payslips { display: block !important; }

    .print-payslip-page { page-break-after: always; }
    .print-payslip-page:last-child { page-break-after: avoid; }

    .payslip-doc { padding: 16px; }
}
</style>

<script>
document.querySelectorAll('.view-payslip-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var data = JSON.parse(this.getAttribute('data-payslip'));

        function fmt(amount, currency) {
            currency = currency || 'MWK';
            return currency + ' ' + parseFloat(amount || 0).toLocaleString('en-MW', {minimumFractionDigits: 2, maximumFractionDigits: 2});
        }

        function fmtDate(d) {
            if (!d) return '—';
            var parts = d.split('-');
            if (parts.length === 3) {
                var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
                return parts[2] + ' ' + months[parseInt(parts[1], 10) - 1] + ' ' + parts[0];
            }
            return d;
        }

        var cur = data.currency_code || 'MWK';
        var periodStart = fmtDate(data.pay_period_start);
        var periodEnd   = fmtDate(data.pay_period_end);
        var period = (data.pay_period_start && data.pay_period_end)
            ? periodStart + ' – ' + periodEnd
            : '—';

        document.getElementById('ps-run-number').textContent  = data.run_number || '—';
        document.getElementById('ps-pay-period').textContent  = period;
        document.getElementById('ps-pay-date').textContent    = fmtDate(data.pay_date);
        document.getElementById('ps-currency').textContent    = cur;

        document.getElementById('ps-fullname').textContent    = data.employee_fullname || '—';
        document.getElementById('ps-code').textContent        = data.employee_code || '—';
        document.getElementById('ps-position').textContent    = data.employee_position || '—';
        document.getElementById('ps-department').textContent  = data.department_name || '—';
        document.getElementById('ps-branch').textContent      = data.branch_name || '—';
        document.getElementById('ps-logo').src                = data.branch_logo || <?php echo json_encode(Branding::logoUrl()); ?>;
        document.getElementById('ps-company-name').textContent = data.company_name || <?php echo json_encode(Branding::companyName()); ?>;

        var status = (data.payment_status || 'unpaid').toUpperCase();
        document.getElementById('ps-status').textContent = status;

        document.getElementById('ps-basic').textContent       = fmt(data.basic_salary, cur);
        document.getElementById('ps-allowances').textContent  = fmt(data.allowances, cur);
        document.getElementById('ps-overtime').textContent    = fmt(data.overtime_pay, cur);
        document.getElementById('ps-gross').textContent       = fmt(data.gross_pay, cur);

        document.getElementById('ps-tax').textContent         = fmt(data.tax_amount, cur);
        document.getElementById('ps-pension').textContent     = fmt(data.pension_employee, cur);
        document.getElementById('ps-loan').textContent        = fmt(data.loan_deduction, cur);
        document.getElementById('ps-other').textContent       = fmt(data.other_deductions, cur);
        document.getElementById('ps-total-ded').textContent   = fmt(data.total_deductions, cur);

        document.getElementById('ps-net').textContent         = fmt(data.net_pay, cur);

        var modal = new bootstrap.Modal(document.getElementById('payslipModal'));
        modal.show();
    });
});

document.querySelectorAll('.edit-payslip-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var data = JSON.parse(this.getAttribute('data-payslip'));
        document.getElementById('ep-logo').src = data.branch_logo || <?php echo json_encode(Branding::logoUrl()); ?>;
        document.getElementById('ep-company-name').textContent = data.company_name || <?php echo json_encode(Branding::companyName()); ?>;
        var cur = data.currency_code || 'MWK';

        document.getElementById('ep-id').value           = data.payslip_id || '';
        document.getElementById('ep-employee-label').textContent =
            (data.employee_fullname || '') + ' — Run ' + (data.run_number || '') + ' (' + cur + ')';

        document.getElementById('ep-basic').value        = parseFloat(data.basic_salary || 0).toFixed(2);
        document.getElementById('ep-allowances').value   = parseFloat(data.allowances || 0).toFixed(2);
        document.getElementById('ep-overtime').value     = parseFloat(data.overtime_pay || 0).toFixed(2);
        document.getElementById('ep-tax').value          = parseFloat(data.tax_amount || 0).toFixed(2);
        document.getElementById('ep-pension').value      = parseFloat(data.pension_employee || 0).toFixed(2);
        document.getElementById('ep-loan').value         = parseFloat(data.loan_deduction || 0).toFixed(2);
        document.getElementById('ep-other').value        = parseFloat(data.other_deductions || 0).toFixed(2);
        document.getElementById('ep-status').value       = data.payment_status || 'unpaid';

        epRecalc();

        var modal = new bootstrap.Modal(document.getElementById('editPayslipModal'));
        modal.show();
    });
});

function epRecalc() {
    var basic      = parseFloat(document.getElementById('ep-basic').value) || 0;
    var allowances = parseFloat(document.getElementById('ep-allowances').value) || 0;
    var overtime   = parseFloat(document.getElementById('ep-overtime').value) || 0;
    var tax        = parseFloat(document.getElementById('ep-tax').value) || 0;
    var pension    = parseFloat(document.getElementById('ep-pension').value) || 0;
    var loan       = parseFloat(document.getElementById('ep-loan').value) || 0;
    var other      = parseFloat(document.getElementById('ep-other').value) || 0;

    var gross    = basic + allowances + overtime;
    var totalDed = tax + pension + loan + other;
    var net      = gross - totalDed;

    document.getElementById('ep-gross-display').value    = gross.toLocaleString('en-MW', {minimumFractionDigits:2, maximumFractionDigits:2});
    document.getElementById('ep-totalded-display').value = totalDed.toLocaleString('en-MW', {minimumFractionDigits:2, maximumFractionDigits:2});
    document.getElementById('ep-net-display').value      = net.toLocaleString('en-MW', {minimumFractionDigits:2, maximumFractionDigits:2});
}

document.querySelectorAll('.ep-calc').forEach(function(el) {
    el.addEventListener('input', epRecalc);
});

function printPayslip() {
    var doc = document.getElementById('payslip-document').innerHTML;
    var win = window.open('', '_blank', 'width=900,height=1100');
    win.document.write('<!DOCTYPE html><html lang="en"><head>');
    win.document.write('<meta charset="UTF-8">');
    win.document.write('<title>Payslip</title>');
    win.document.write('<style>');
    win.document.write('@page { size: A4 portrait; margin: 14mm 15mm 14mm 15mm; }');
    win.document.write('* { box-sizing: border-box; margin: 0; padding: 0; }');
    win.document.write('body { font-family: "Segoe UI", Arial, sans-serif; font-size: 12pt; color: #212529; background: #fff; }');
    win.document.write('.payslip-doc { width: 100%; max-width: 180mm; margin: 0 auto; }');
    win.document.write('.payslip-header { display: flex; align-items: center; gap: 16px; margin-bottom: 10px; }');
    win.document.write('.payslip-logo { height: 55pt; width: auto; object-fit: contain; }');
    win.document.write('.payslip-company-name { font-size: 17pt; font-weight: 700; color: #1a1a2e; }');
    win.document.write('.payslip-doc-title { font-size: 9pt; letter-spacing: 0.12em; color: #6c757d; text-transform: uppercase; margin-top: 2px; }');
    win.document.write('.payslip-divider { border-top: 2pt solid #1a1a2e; margin: 10px 0; }');
    win.document.write('.payslip-meta-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin: 10px 0; }');
    win.document.write('.payslip-meta-item, .payslip-employee-item { display: flex; flex-direction: column; gap: 2px; }');
    win.document.write('.payslip-meta-label { font-size: 7.5pt; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; color: #6c757d; }');
    win.document.write('.payslip-meta-value { font-size: 10pt; color: #212529; font-weight: 500; }');
    win.document.write('.payslip-section-title { font-size: 8pt; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; color: #495057; background: #f8f9fa; padding: 4px 8px; margin-bottom: 6px; border-left: 3pt solid #1a1a2e; }');
    win.document.write('.payslip-employee-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px 20px; margin: 8px 0; }');
    win.document.write('.payslip-columns { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 8px 0; }');
    win.document.write('.payslip-table { width: 100%; border-collapse: collapse; }');
    win.document.write('.payslip-table td { padding: 4pt 3pt; border-bottom: 0.5pt solid #e9ecef; font-size: 10pt; }');
    win.document.write('.payslip-table td.text-end { text-align: right; }');
    win.document.write('.payslip-subtotal td { border-top: 1pt solid #adb5bd; border-bottom: 1pt solid #adb5bd; background: #f8f9fa; padding-top: 5pt; padding-bottom: 5pt; }');
    win.document.write('.payslip-net-pay-row { display: flex; align-items: center; justify-content: space-between; background: #1a1a2e; color: #fff; padding: 12pt 14pt; margin-top: 14px; }');
    win.document.write('.payslip-net-label { font-size: 12pt; font-weight: 700; letter-spacing: 0.1em; }');
    win.document.write('.payslip-net-value { font-size: 17pt; font-weight: 700; }');
    win.document.write('.payslip-footer-note { font-size: 8pt; color: #adb5bd; text-align: center; margin-top: 18px; padding-top: 8px; border-top: 0.5pt solid #dee2e6; }');
    win.document.write('</style></head><body>');
    win.document.write('<div class="payslip-doc">' + doc + '</div>');
    win.document.write('</body></html>');
    win.document.close();
    win.onload = function() {
        win.focus();
        win.print();
        win.onafterprint = function() { win.close(); };
    };
}
</script>

<?php include '../../includes/footer.php'; ?>
