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

payrollRequireAdmin($auth);

$payroll = new Payroll($conn);
$id = (int)($_GET['id'] ?? 0);

if ($id <= 0) {
    header('Location: loans.php');
    exit;
}

$loan = $payroll->getLoansByID($id);
if (!$loan) {
    header('Location: loans.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $loan_type     = trim($_POST['loan_type'] ?? '');
    $loan_amount   = (float)($_POST['loan_amount'] ?? 0);
    $interest_rate = (float)($_POST['interest_rate'] ?? 0);
    $loan_months   = (int)($_POST['loan_months'] ?? 0);
    $loans_starts  = trim($_POST['loans_starts'] ?? '');
    $loan_status   = trim($_POST['loan_status'] ?? 'pending');

    if ($loan_amount > 0 && $loan_months > 0 && $payroll->updateLoan($id, $loan_type, $loan_amount, $interest_rate, $loan_months, $loans_starts, $loan_status)) {
        header('Location: loans.php?updated=1');
        exit;
    }

    $error = 'Failed to update the loan. Please check the values and try again.';
}

payrollModuleStyles();
?>

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

    <div class="payroll-page-head">
        <div>
            <h1>Edit Loan</h1>
            <p>Updating loan record for <strong><?php echo payrollText($loan['employee_fullname'] ?? ''); ?></strong>.</p>
        </div>
        <a href="loans.php" class="btn btn-outline-secondary no-print"><i class="fas fa-arrow-left"></i> Back to Loans</a>
    </div>

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

    <div class="payroll-panel">
        <form method="POST">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">Employee</label>
                    <input type="text" class="form-control" value="<?php echo payrollText($loan['employee_fullname'] ?? ''); ?>" disabled>
                </div>
                <div class="col-md-6">
                    <label for="loan_type" class="form-label">Loan Type</label>
                    <select class="form-control" id="loan_type" name="loan_type" required>
                        <?php
                        $types = ['salary_advance' => 'Salary Advance', 'emergency_loan' => 'Emergency Loan', 'personal_loan' => 'Personal Loan', 'educational_loan' => 'Educational Loan'];
                        foreach ($types as $val => $label):
                        ?>
                            <option value="<?php echo $val; ?>" <?php echo ($loan['loan_type'] ?? '') === $val ? 'selected' : ''; ?>>
                                <?php echo $label; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="loan_amount" class="form-label">Loan Amount</label>
                    <input type="number" step="0.01" min="0.01" class="form-control" id="loan_amount" name="loan_amount"
                           value="<?php echo htmlspecialchars($loan['loan_amount'] ?? ''); ?>" required>
                </div>
                <div class="col-md-4">
                    <label for="interest_rate" class="form-label">Interest Rate (%)</label>
                    <input type="number" step="0.01" min="0" class="form-control" id="interest_rate" name="interest_rate"
                           value="<?php echo htmlspecialchars($loan['interest_rate'] ?? '0'); ?>" required>
                </div>
                <div class="col-md-4">
                    <label for="loan_months" class="form-label">Repayment Months</label>
                    <input type="number" min="1" class="form-control" id="loan_months" name="loan_months"
                           value="<?php echo htmlspecialchars($loan['loan_months'] ?? ''); ?>" required>
                </div>
                <div class="col-md-6">
                    <label for="loans_starts" class="form-label">Deduction Starts</label>
                    <input type="date" class="form-control" id="loans_starts" name="loans_starts"
                           value="<?php echo htmlspecialchars($loan['loans_starts'] ?? ''); ?>" required>
                </div>
                <div class="col-md-6">
                    <label for="loan_status" class="form-label">Status</label>
                    <select class="form-control" id="loan_status" name="loan_status" required>
                        <?php
                        $statuses = ['pending' => 'Pending', 'approved' => 'Approved', 'closed' => 'Closed', 'paid' => 'Paid'];
                        foreach ($statuses as $val => $label):
                        ?>
                            <option value="<?php echo $val; ?>" <?php echo ($loan['loan_status'] ?? '') === $val ? 'selected' : ''; ?>>
                                <?php echo $label; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php if (!empty($loan['loan_total_paid']) && (float)$loan['loan_total_paid'] > 0): ?>
                <div class="col-12">
                    <div class="alert alert-info mb-0">
                        <i class="fas fa-info-circle"></i>
                        This loan has <strong><?php echo payrollMoney($loan['loan_total_paid']); ?></strong> already paid.
                        Changing the loan amount will affect the outstanding balance.
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <div class="mt-4">
                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Changes</button>
                <a href="loans.php" class="btn btn-outline-secondary">Cancel</a>
            </div>
        </form>
    </div>

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

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