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

payrollRequireAdmin($auth);

$payroll = new Payroll($conn);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete') {
    $deleteId = (int)($_POST['loan_id'] ?? 0);
    if ($deleteId > 0) {
        $payroll->deleteLoan($deleteId);
    }
    header('Location: loans.php?deleted=1');
    exit;
}

$loans = $payroll->getLoans();
$summary = $payroll->getPayrollSummary();

payrollModuleStyles();
?>

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

    <div class="payroll-page-head">
        <div>
            <h1>Employee Loans</h1>
            <p>Track salary advances, emergency loans, deductions, and outstanding balances.</p>
        </div>
        <div class="no-print">
            <a href="../dashboard/admin.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Admin Dashboard</a>
            <a href="add_loan_form.php" class="btn btn-primary"><i class="fas fa-plus"></i> New Loan</a>
        </div>
    </div>

    <?php if (isset($_GET['deleted'])): ?>
        <div class="alert alert-success">Loan record deleted successfully.</div>
    <?php endif; ?>
    <?php if (isset($_GET['updated'])): ?>
        <div class="alert alert-success">Loan record updated successfully.</div>
    <?php endif; ?>

    <div class="payroll-metrics">
        <div class="payroll-metric"><strong>Active Loans</strong><span><?php echo number_format($summary['active_loans']); ?></span></div>
        <div class="payroll-metric"><strong>Outstanding Balance</strong><span><?php echo payrollMoney($summary['loan_balance']); ?></span></div>
    </div>

    <div class="payroll-panel">
        <div class="payroll-panel-title">
            <h2>Loan Register</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 table-hover payroll-table">
                <thead>
                    <tr>
                        <th>Employee</th>
                        <th>Date</th>
                        <th>Type</th>
                        <th>Principal</th>
                        <th>Paid</th>
                        <th>Balance</th>
                        <th>Status</th>
                        <th class="no-print">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($loans)): ?>
                        <?php foreach ($loans as $loan): ?>
                            <?php
                                $principal = (float)($loan['loan_amount'] ?? 0);
                                $paid = (float)($loan['loan_total_paid'] ?? 0);
                                $balance = max(0, $principal - $paid);
                            ?>
                            <tr>
                                <td>
                                    <strong><?php echo payrollText($loan['employee_fullname'] ?? ('Employee #' . ($loan['employee_id'] ?? ''))); ?></strong><br>
                                    <small class="text-muted"><?php echo payrollText($loan['employee_position'] ?? ''); ?></small>
                                </td>
                                <td><?php echo payrollText($loan['loan_date'] ?? ''); ?></td>
                                <td><?php echo payrollText(str_replace('_', ' ', $loan['loan_type'] ?? '')); ?></td>
                                <td><?php echo payrollMoney($principal); ?></td>
                                <td><?php echo payrollMoney($paid); ?></td>
                                <td><?php echo payrollMoney($balance); ?></td>
                                <td><?php echo payrollStatusBadge($loan['loan_status'] ?? ''); ?></td>
                                <td class="no-print" style="white-space:nowrap;">
                                    <a href="view_loan.php?id=<?php echo (int)$loan['record_id']; ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-eye"></i> View</a>
                                    <a href="edit_loan_form.php?id=<?php echo (int)$loan['record_id']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-edit"></i> Edit</a>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this loan record? This cannot be undone.');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="loan_id" value="<?php echo (int)$loan['record_id']; ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i> Delete</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="8" class="text-center">No employee loans found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

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

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