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

payrollRequireAdmin($auth);

$payroll        = new Payroll($conn);
$payRuns        = $payroll->getPayRuns();
$runBillAmounts = $payroll->getPayRunBillAmounts();

$error = '';
$filterStatus = $_GET['status'] ?? '';
$filterType   = $_GET['type'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $data = [
            'payroll_run_id'   => (int)($_POST['payroll_run_id'] ?? 0) ?: null,
            'bill_type'        => $_POST['bill_type'] ?? 'Other',
            'description'      => trim($_POST['description'] ?? ''),
            'amount'           => (float)($_POST['amount'] ?? 0),
            'due_date'         => trim($_POST['due_date'] ?? ''),
            'reference_number' => trim($_POST['reference_number'] ?? ''),
            'branch_id'        => null,
        ];

        if ($data['description'] === '' || $data['amount'] <= 0) {
            $error = 'Description and a valid amount are required.';
        } elseif (!in_array($data['bill_type'], ['PAYE', 'Pension', 'Union Fee', 'Other'])) {
            $error = 'Invalid bill type.';
        } else {
            $id = $payroll->saveRemittance($data, (int)$_SESSION['user_id']);
            if ($id) {
                header('Location: payroll_bills.php?added=1');
                exit();
            } else {
                $error = 'Failed to record bill. Run the database migration first.';
            }
        }
    } elseif ($action === 'mark_paid') {
        $remId     = (int)($_POST['remittance_id'] ?? 0);
        $payDate   = trim($_POST['payment_date'] ?? date('Y-m-d'));
        $reference = trim($_POST['reference_number'] ?? '');
        if ($remId > 0 && $payDate) {
            if ($payroll->markRemittancePaid($remId, $payDate, $reference)) {
                header('Location: payroll_bills.php?paid=1');
                exit();
            } else {
                $error = 'Failed to mark bill as paid.';
            }
        }
    } elseif ($action === 'delete') {
        $remId = (int)($_POST['remittance_id'] ?? 0);
        if ($remId > 0 && $payroll->deleteRemittance($remId)) {
            header('Location: payroll_bills.php?deleted=1');
            exit();
        } else {
            $error = 'Could not delete — only pending bills can be removed.';
        }
    }
}

$filters = [];
if ($filterStatus) $filters['status']    = $filterStatus;
if ($filterType)   $filters['bill_type'] = $filterType;
$remittances = $payroll->getRemittances($filters);
$summary     = $payroll->getRemittanceSummary();

payrollModuleStyles();
?>

<?php if (isset($_GET['added'])): ?>
<div class="alert alert-success alert-dismissible fade show mx-4 mt-3" role="alert">
    Bill recorded successfully. <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if (isset($_GET['paid'])): ?>
<div class="alert alert-success alert-dismissible fade show mx-4 mt-3" role="alert">
    Bill marked as paid. <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if (isset($_GET['deleted'])): ?>
<div class="alert alert-info alert-dismissible fade show mx-4 mt-3" role="alert">
    Bill deleted. <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

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

    <div class="payroll-page-head">
        <div>
            <h1>Payroll Bills</h1>
            <p>Record and track PAYE, Pension, and Union fee remittances.</p>
        </div>
        <div class="no-print">
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addBillModal">
                <i class="fas fa-plus"></i> Record Bill
            </button>
        </div>
    </div>

    <?php payrollMigrationNotice($payroll, ['payroll_remittances'], 'Run database_migrations/payroll_remittances.sql to enable payroll bills tracking.'); ?>

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

    <div class="payroll-metrics">
        <div class="payroll-metric">
            <strong>Pending Bills</strong>
            <span><?php echo number_format($summary['pending_count']); ?></span>
        </div>
        <div class="payroll-metric">
            <strong>Pending Amount</strong>
            <span><?php echo payrollMoney($summary['pending_total']); ?></span>
        </div>
        <div class="payroll-metric">
            <strong>Total Paid (all time)</strong>
            <span><?php echo payrollMoney($summary['paid_total']); ?></span>
        </div>
        <?php if ($summary['overdue_count'] > 0): ?>
        <div class="payroll-metric" style="border-color:#dc3545;">
            <strong style="color:#dc3545;">Overdue</strong>
            <span style="color:#dc3545;"><?php echo number_format($summary['overdue_count']); ?></span>
        </div>
        <?php endif; ?>
    </div>

    <!-- Filters -->
    <form method="GET" class="payroll-panel mb-3 no-print">
        <div class="row g-2 align-items-end">
            <div class="col-auto">
                <label class="form-label mb-1">Status</label>
                <select name="status" class="form-select form-select-sm">
                    <option value="">All</option>
                    <?php foreach (['pending' => 'Pending', 'paid' => 'Paid', 'overdue' => 'Overdue'] as $v => $l): ?>
                        <option value="<?php echo $v; ?>"<?php echo $filterStatus === $v ? ' selected' : ''; ?>><?php echo $l; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-auto">
                <label class="form-label mb-1">Type</label>
                <select name="type" class="form-select form-select-sm">
                    <option value="">All</option>
                    <?php foreach (['PAYE', 'Pension', 'Union Fee', 'Other'] as $t): ?>
                        <option value="<?php echo $t; ?>"<?php echo $filterType === $t ? ' selected' : ''; ?>><?php echo $t; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-sm btn-outline-secondary">Filter</button>
                <a href="payroll_bills.php" class="btn btn-sm btn-link">Clear</a>
            </div>
        </div>
    </form>

    <div class="payroll-panel">
        <div class="payroll-panel-title">
            <h2>Bills</h2>
            <button type="button" class="btn btn-outline-secondary btn-sm no-print" onclick="window.print()"><i class="fas fa-print"></i> Print</button>
        </div>
        <div class="table-responsive">
            <table class="table table-bordered payroll-table">
                <thead>
                    <tr>
                        <th>Type</th>
                        <th>Description</th>
                        <th>Pay Run</th>
                        <th>Amount</th>
                        <th>Due Date</th>
                        <th>Status</th>
                        <th>Payment Date</th>
                        <th>Reference</th>
                        <th class="no-print">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($remittances)): ?>
                        <tr><td colspan="9" class="text-center text-muted">No bills recorded yet.</td></tr>
                    <?php else: ?>
                        <?php foreach ($remittances as $rem): ?>
                            <?php
                                $isOverdue = $rem['payment_status'] === 'pending'
                                    && !empty($rem['due_date'])
                                    && $rem['due_date'] < date('Y-m-d');
                                $statusLabel = $isOverdue ? 'overdue' : $rem['payment_status'];
                                $badgeClass = match($statusLabel) {
                                    'paid'    => 'bg-success',
                                    'overdue' => 'bg-danger',
                                    default   => 'bg-warning text-dark',
                                };
                            ?>
                            <tr<?php echo $isOverdue ? ' class="table-danger"' : ''; ?>>
                                <td><span class="badge bg-secondary"><?php echo payrollText($rem['bill_type']); ?></span></td>
                                <td><?php echo payrollText($rem['description']); ?></td>
                                <td><?php echo $rem['run_number'] ? payrollText($rem['run_number']) : '<span class="text-muted">—</span>'; ?></td>
                                <td><strong><?php echo payrollMoney($rem['amount']); ?></strong></td>
                                <td><?php echo $rem['due_date'] ? payrollText($rem['due_date']) : '—'; ?></td>
                                <td><span class="badge <?php echo $badgeClass; ?>"><?php echo ucfirst($statusLabel); ?></span></td>
                                <td><?php echo $rem['payment_date'] ? payrollText($rem['payment_date']) : '—'; ?></td>
                                <td><?php echo $rem['reference_number'] ? payrollText($rem['reference_number']) : '—'; ?></td>
                                <td class="no-print">
                                    <?php if ($rem['payment_status'] === 'pending'): ?>
                                        <button type="button" class="btn btn-sm btn-success mark-paid-btn"
                                            data-bs-toggle="modal" data-bs-target="#markPaidModal"
                                            data-id="<?php echo (int)$rem['remittance_id']; ?>"
                                            data-desc="<?php echo htmlspecialchars($rem['description'], ENT_QUOTES); ?>"
                                            data-amount="<?php echo htmlspecialchars($rem['amount'], ENT_QUOTES); ?>">
                                            <i class="fas fa-check"></i> Mark Paid
                                        </button>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('Delete this bill?')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="remittance_id" value="<?php echo (int)$rem['remittance_id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                                        </form>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

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

<!-- Add Bill Modal -->
<div class="modal fade" id="addBillModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="add">
                <div class="modal-header">
                    <h5 class="modal-title">Record Payroll Bill</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Bill Type</label>
                            <select id="addBillType" name="bill_type" class="form-select" required>
                                <option value="PAYE">PAYE</option>
                                <option value="Pension">Pension</option>
                                <option value="Union Fee">Union Fee</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Pay Run (optional)</label>
                            <select id="addBillRun" name="payroll_run_id" class="form-select">
                                <option value="">Not linked</option>
                                <?php foreach ($payRuns as $run): ?>
                                    <option value="<?php echo (int)$run['payroll_run_id']; ?>">
                                        <?php echo htmlspecialchars($run['run_number'] . ' (' . $run['pay_period_start'] . ')'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Description</label>
                            <input type="text" name="description" id="addBillDesc" class="form-control" placeholder="e.g. PAYE for June 2026" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Amount (MWK)</label>
                            <input type="number" step="0.01" min="0.01" name="amount" id="addBillAmount" class="form-control" required>
                            <small id="addBillAmountHint" class="form-text text-muted d-none">Auto-filled from pay run payslips.</small>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Due Date</label>
                            <input type="date" name="due_date" class="form-control">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Reference Number</label>
                            <input type="text" name="reference_number" class="form-control" placeholder="Receipt / payment ref">
                        </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 Bill</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Mark Paid Modal -->
<div class="modal fade" id="markPaidModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="mark_paid">
                <input type="hidden" name="remittance_id" id="markPaidId">
                <div class="modal-header">
                    <h5 class="modal-title">Mark Bill as Paid</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p id="markPaidDesc" class="text-muted mb-3"></p>
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Payment Date</label>
                            <input type="date" name="payment_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Reference Number</label>
                            <input type="text" name="reference_number" class="form-control" placeholder="Receipt / payment ref">
                        </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-success"><i class="fas fa-check"></i> Confirm Payment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.getElementById('markPaidModal').addEventListener('show.bs.modal', function (e) {
    var btn = e.relatedTarget;
    document.getElementById('markPaidId').value = btn.dataset.id;
    document.getElementById('markPaidDesc').textContent =
        btn.dataset.desc + ' — MWK ' + parseFloat(btn.dataset.amount).toLocaleString(undefined, {minimumFractionDigits: 2});
});

var runAmounts = <?php echo json_encode($runBillAmounts); ?>;

function updateBillAmount() {
    var runId  = parseInt(document.getElementById('addBillRun').value) || 0;
    var type   = document.getElementById('addBillType').value;
    var amtEl  = document.getElementById('addBillAmount');
    var hint   = document.getElementById('addBillAmountHint');
    var descEl = document.getElementById('addBillDesc');

    if (!runId || !runAmounts[runId]) {
        hint.classList.add('d-none');
        return;
    }

    var data   = runAmounts[runId];
    var filled = type === 'PAYE' ? data.paye : (type === 'Pension' ? data.pension : 0);

    if (filled > 0) {
        amtEl.value = filled.toFixed(2);
        hint.classList.remove('d-none');
    } else {
        hint.classList.add('d-none');
    }

    if (descEl.value === '') {
        var runText = document.getElementById('addBillRun').options[document.getElementById('addBillRun').selectedIndex].text;
        descEl.value = type + ' — ' + runText;
    }
}

document.getElementById('addBillRun').addEventListener('change', updateBillAmount);
document.getElementById('addBillType').addEventListener('change', updateBillAmount);
</script>

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