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

payrollRequireAdmin($auth);

$payroll = new Payroll($conn);
$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_paye_tax_bands') {
    $bands = [];
    foreach ($_POST['band_label'] ?? [] as $index => $label) {
        $bands[] = [
            'band_label' => $label,
            'band_limit' => $_POST['band_limit'][$index] ?? '',
            'tax_rate' => $_POST['tax_rate'][$index] ?? '',
        ];
    }

    if ($payroll->savePayeTaxBands($bands, $_SESSION['user_id'] ?? null)) {
        $success = 'PAYE tax bands updated successfully.';
    } else {
        $error = 'Failed to update PAYE tax bands. Confirm the payroll_paye_tax_bands table is installed and the values are valid.';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_pension_formula') {
    if ($payroll->savePensionFormula($_POST)) {
        $success = 'Pension formula updated successfully.';
    } else {
        $error = 'Failed to update pension formula. Confirm the payroll_deductions table is installed and the values are valid.';
    }
}

$payeTaxBands = $payroll->getPayeTaxBands();
$pensionFormula = $payroll->getPensionFormula();
$requiredTables = [
    'hr_departments',
    'hr_positions',
    'hr_leave_types',
    'hr_leave_requests',
    'hr_attendance',
    'payroll_runs',
    'payroll_payslips',
    'payroll_deductions',
    'payroll_paye_tax_bands',
    'hr_audit_log',
];

payrollModuleStyles();
?>

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

    <div class="payroll-page-head">
        <div>
            <h1>HR - Payroll Setup</h1>
            <p>Database readiness and implementation checklist for the professional payroll module.</p>
        </div>
        <a href="index.php" class="btn btn-outline-secondary no-print"><i class="fas fa-arrow-left"></i> Overview</a>
    </div>

    <div class="payroll-panel">
        <div class="payroll-panel-title"><h2>Schema Readiness</h2></div>
        <div class="table-responsive">
            <table class="table table-bordered payroll-table">
                <thead>
                    <tr>
                        <th>Table</th>
                        <th>Status</th>
                        <th>Purpose</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($requiredTables as $table): ?>
                        <tr>
                            <td><code><?php echo htmlspecialchars($table); ?></code></td>
                            <td><?php echo $payroll->tableExists($table) ? '<span class="badge bg-success">Installed</span>' : '<span class="badge bg-warning text-dark">Missing</span>'; ?></td>
                            <td>
                                <?php
                                $purpose = [
                                    'hr_departments' => 'Departments and reporting structure',
                                    'hr_positions' => 'Job roles and job levels',
                                    'hr_leave_types' => 'Annual, sick, unpaid, and statutory leave categories',
                                    'hr_leave_requests' => 'Leave applications and approvals',
                                    'hr_attendance' => 'Attendance, time, overtime, and absence records',
                                    'payroll_runs' => 'Payroll periods, approvals, and totals',
                                    'payroll_payslips' => 'Employee payslip archive',
                                    'payroll_deductions' => 'Statutory and voluntary deduction catalogue',
                                    'payroll_paye_tax_bands' => 'Configurable monthly PAYE income bands and rates',
                                    'hr_audit_log' => 'Audit history for HR/payroll changes',
                                ];
                                echo htmlspecialchars($purpose[$table] ?? '');
                                ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php if ($success): ?>
        <div class="alert alert-success mt-3"><?php echo htmlspecialchars($success); ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-danger mt-3"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <div class="payroll-panel mt-3">
        <div class="payroll-panel-title"><h2>Pension Formula</h2></div>
        <form method="POST">
            <input type="hidden" name="action" value="save_pension_formula">
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label" for="deduction_type">Formula</label>
                    <select class="form-control" id="deduction_type" name="deduction_type">
                        <?php $pensionType = $pensionFormula['deduction_type'] ?? 'percentage_of_basic'; ?>
                        <option value="percentage_of_basic" <?php echo $pensionType === 'percentage_of_basic' ? 'selected' : ''; ?>>Percentage of Basic Salary</option>
                        <option value="percentage_of_gross" <?php echo $pensionType === 'percentage_of_gross' ? 'selected' : ''; ?>>Percentage of Gross Pay</option>
                        <option value="fixed_amount" <?php echo $pensionType === 'fixed_amount' ? 'selected' : ''; ?>>Fixed Monthly Amount</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label" for="rate">Rate (%)</label>
                    <input type="number" step="0.01" min="0" class="form-control" id="rate" name="rate" value="<?php echo htmlspecialchars($pensionFormula['rate'] ?? 0); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label" for="amount">Fixed Amount</label>
                    <input type="number" step="0.01" min="0" class="form-control" id="amount" name="amount" value="<?php echo htmlspecialchars($pensionFormula['amount'] ?? 0); ?>">
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="checkbox" id="is_active" name="is_active" value="1" <?php echo !empty($pensionFormula['is_active']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="is_active">Active</label>
                    </div>
                </div>
            </div>
            <div class="text-muted mt-2">This pension deduction is applied when new draft pay runs are created.</div>
            <button type="submit" class="btn btn-primary mt-3" <?php echo $payroll->tableExists('payroll_deductions') ? '' : 'disabled'; ?>><i class="fas fa-save"></i> Save Pension Formula</button>
        </form>
    </div>
    <div class="payroll-panel mt-3">
        <div class="payroll-panel-title"><h2>PAYE Adjustments</h2></div>
        <form method="POST">
            <input type="hidden" name="action" value="save_paye_tax_bands">
            <div class="table-responsive">
                <table class="table table-bordered payroll-table mb-0">
                    <thead>
                        <tr>
                            <th>Band</th>
                            <th>Monthly Income Amount</th>
                            <th>Rate (%)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($payeTaxBands as $index => $band): ?>
                            <tr>
                                <td>
                                    <input type="text" class="form-control" name="band_label[]" value="<?php echo htmlspecialchars($band['band_label'] ?? ''); ?>" required>
                                </td>
                                <td>
                                    <input type="number" step="0.01" min="0" class="form-control" name="band_limit[]" value="<?php echo htmlspecialchars($band['band_limit'] ?? ''); ?>" placeholder="Leave blank for excess band">
                                </td>
                                <td>
                                    <input type="number" step="0.01" min="0" class="form-control" name="tax_rate[]" value="<?php echo htmlspecialchars($band['tax_rate'] ?? 0); ?>" required>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <button type="submit" class="btn btn-primary mt-3" <?php echo $payroll->tableExists('payroll_paye_tax_bands') ? '' : 'disabled'; ?>><i class="fas fa-save"></i> Save PAYE Bands</button>
        </form>
    </div>

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

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