<?php
require_once 'config/db.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
requireAdminPage();

$preselect_loan = intval($_GET['loan_id'] ?? 0);

$active_loans = fetchAll($conn,
    "SELECT l.id, l.loan_amount, l.balance, l.installment_amount, l.penalty, l.status, l.due_date,
            b.first_name, b.last_name
     FROM loans l JOIN borrowers b ON l.borrower_id=b.id
     WHERE l.status IN ('released','overdue')
     ORDER BY l.status='overdue' DESC, b.first_name ASC",
    [], "");

// Block direct URL access for pending/paid loans
if ($preselect_loan) {
    $check = fetchOne($conn, "SELECT status FROM loans WHERE id=?", [$preselect_loan], "i");
    if ($check && !in_array($check['status'], ['released', 'overdue'])) {
        header('Location: /cash_lending/loan-details.php?id=' . $preselect_loan . '&error=' . urlencode('This loan must be released before recording a payment.'));
        exit();
    }
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $loan_id        = intval($_POST['loan_id'] ?? 0);
    $payment_date   = $_POST['payment_date'] ?? date('Y-m-d');
    $amount         = floatval($_POST['amount'] ?? 0);
    $penalty_paid   = floatval($_POST['penalty_paid'] ?? 0);
    $payment_method = htmlspecialchars($_POST['payment_method'] ?? '', ENT_QUOTES);
    $notes          = htmlspecialchars($_POST['notes'] ?? '', ENT_QUOTES);
    $payment_type   = in_array($_POST['payment_type'] ?? '', ['regular','interest_only'])
                        ? $_POST['payment_type'] : 'regular';

    if (!$loan_id)    $errors[] = 'Please select a loan';
    if ($amount <= 0) $errors[] = 'Amount must be greater than 0';

    if (empty($errors)) {
        try {
            $payment_id = recordPayment($conn, $loan_id, $payment_date, $amount,
                                         $penalty_paid, $payment_method, $notes,
                                         $_SESSION['user_id'], $payment_type);
            logActivity($conn, $_SESSION['user_id'], 'record_payment',
                "Payment ₱$amount for loan ID $loan_id");
            header('Location: /cash_lending/receipt.php?id='.$payment_id);
            exit();
        } catch (Exception $e) {
            $errors[] = 'Error: '.$e->getMessage();
        }
    }
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>
<div class="row mb-4">
    <div class="col-lg-8"><h3><i class="fas fa-money-bill-wave"></i> Record Payment</h3></div>
</div>

<div class="row">
<div class="col-lg-7">
<div class="card">
<div class="card-body p-4">

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger"><ul class="mb-0">
        <?php foreach($errors as $e): ?><li><?php echo htmlspecialchars($e); ?></li><?php endforeach; ?>
    </ul></div>
<?php endif; ?>

<form method="POST">
    <div class="mb-3">
        <label class="form-label fw-semibold">Loan / Borrower <span class="text-danger">*</span></label>
        <select class="form-select" name="loan_id" id="loanSelect" required onchange="fillLoanInfo(this)">
            <option value="">-- Select Loan --</option>
            <?php foreach ($active_loans as $l):
                $overdue_label = $l['status']==='overdue' ? ' ⚠️ OVERDUE' : '';
            ?>
                <option value="<?php echo $l['id']; ?>"
                        data-installment="<?php echo $l['installment_amount']; ?>"
                        data-balance="<?php echo $l['balance']; ?>"
                        data-penalty="<?php echo calculatePenalty($l); ?>"
                        data-status="<?php echo $l['status']; ?>"
                        <?php echo ($preselect_loan===$l['id']||($_POST['loan_id']??0)==$l['id'])?'selected':''; ?>>
                    <?php echo htmlspecialchars($l['first_name'].' '.$l['last_name']); ?>
                    — Balance ₱<?php echo number_format($l['balance'],2); ?><?php echo $overdue_label; ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>

    <!-- Loan info panel -->
    <div id="loanInfoPanel" class="alert alert-info py-2 d-none mb-3">
        <div class="row text-center">
            <div class="col-4">
                <div class="small text-muted">Balance</div>
                <div class="fw-bold" id="infoBalance">—</div>
            </div>
            <div class="col-4">
                <div class="small text-muted">Installment</div>
                <div class="fw-bold" id="infoInstall">—</div>
            </div>
            <div class="col-4">
                <div class="small text-muted">Penalty</div>
                <div class="fw-bold text-danger" id="infoPenalty">—</div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6 mb-3">
            <label class="form-label fw-semibold">Payment Date <span class="text-danger">*</span></label>
            <input type="date" class="form-control" name="payment_date"
                   value="<?php echo htmlspecialchars($_POST['payment_date']??date('Y-m-d')); ?>" required>
        </div>
        <div class="col-md-6 mb-3">
            <label class="form-label fw-semibold">Payment Method</label>
            <select class="form-select" name="payment_method">
                <option value="">— Select —</option>
                <?php foreach(['Cash','GCash','Bank Transfer','Check','Others'] as $m): ?>
                    <option value="<?php echo $m; ?>"
                        <?php echo ($_POST['payment_method']??'')===$m?'selected':''; ?>><?php echo $m; ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6 mb-3">
            <label class="form-label fw-semibold">Amount <span class="text-danger">*</span></label>
            <div class="input-group">
                <span class="input-group-text">₱</span>
                <input type="number" class="form-control" name="amount" id="amountField"
                       step="0.01" min="0.01" required
                       value="<?php echo htmlspecialchars($_POST['amount']??''); ?>"
                       placeholder="0.00">
            </div>
        </div>
        <div class="col-md-6 mb-3">
            <label class="form-label fw-semibold">Penalty Paid</label>
            <div class="input-group">
                <span class="input-group-text">₱</span>
                <input type="number" class="form-control" name="penalty_paid" id="penaltyField"
                       step="0.01" min="0"
                       value="<?php echo htmlspecialchars($_POST['penalty_paid']??'0'); ?>"
                       placeholder="0.00">
            </div>
            <small class="text-muted">Auto-filled if overdue</small>
        </div>
    </div>

    <div class="mb-3">
        <label class="form-label fw-semibold">Payment Type</label>
        <div class="d-flex gap-3">
            <div class="form-check">
                <input class="form-check-input" type="radio" name="payment_type"
                       id="typeRegular" value="regular" checked
                       onchange="togglePaymentType(this.value)">
                <label class="form-check-label" for="typeRegular">
                    <strong>Regular</strong>
                    <small class="text-muted d-block">Reduces principal balance</small>
                </label>
            </div>
            <div class="form-check">
                <input class="form-check-input" type="radio" name="payment_type"
                       id="typeInterest" value="interest_only"
                       onchange="togglePaymentType(this.value)">
                <label class="form-check-label" for="typeInterest">
                    <strong>Interest Only</strong>
                    <small class="text-muted d-block">Principal stays unchanged</small>
                </label>
            </div>
        </div>
        <div id="interestOnlyNotice" class="alert alert-warning py-2 mt-2 d-none" style="font-size:13px;">
            <i class="fas fa-info-circle"></i>
            <strong>Interest-only payment</strong> — The principal balance will <u>not</u> be reduced.
            This payment covers interest charges only.
        </div>
    </div>

    <div class="mb-3">
        <label class="form-label fw-semibold">Notes</label>
        <textarea class="form-control" name="notes" rows="2"><?php echo htmlspecialchars($_POST['notes']??''); ?></textarea>
    </div>

    <div class="d-flex gap-2">
        <button type="submit" class="btn btn-success px-4">
            <i class="fas fa-save"></i> Save Payment
        </button>
        <a href="/cash_lending/payments.php" class="btn btn-outline-secondary">
            <i class="fas fa-times"></i> Cancel
        </a>
    </div>
</form>
</div>
</div>
</div>
</div>

<script>
const fmt = v => '₱' + parseFloat(v).toLocaleString('en-PH',{minimumFractionDigits:2,maximumFractionDigits:2});

function fillLoanInfo(sel) {
    const opt = sel.options[sel.selectedIndex];
    if (!opt || !opt.value) {
        document.getElementById('loanInfoPanel').classList.add('d-none');
        return;
    }
    const install = opt.dataset.installment;
    const balance = opt.dataset.balance;
    const penalty = opt.dataset.penalty;

    document.getElementById('infoBalance').textContent  = fmt(balance);
    document.getElementById('infoInstall').textContent  = fmt(install);
    document.getElementById('infoPenalty').textContent  = penalty > 0 ? fmt(penalty) : 'None';
    document.getElementById('loanInfoPanel').classList.remove('d-none');
    document.getElementById('amountField').value  = parseFloat(install).toFixed(2);
    document.getElementById('penaltyField').value = parseFloat(penalty).toFixed(2);
}

window.addEventListener('DOMContentLoaded', () => {
    const sel = document.getElementById('loanSelect');
    if (sel && sel.value) fillLoanInfo(sel);
});

function togglePaymentType(val) {
    const notice = document.getElementById('interestOnlyNotice');
    if (val === 'interest_only') {
        notice.classList.remove('d-none');
    } else {
        notice.classList.add('d-none');
    }
}
</script>
<?php include 'includes/footer.php'; ?>
