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

$page_title = 'Record Payment';
$active_nav = 'payments';
$errors = [];
$success = '';

// Pre-fill loan if coming from loan details
$preselect_loan = intval($_GET['loan_id'] ?? 0);

// Get active loans for dropdown
$active_loans = fetchAll($conn,
    "SELECT l.id, l.loan_amount, l.balance, l.installment_amount, 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 b.first_name ASC",
    [], ""
);

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);

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

    if (empty($errors)) {
        try {
            $payment_type = in_array($_POST['payment_type'] ?? '', ['regular','interest_only']) ? $_POST['payment_type'] : 'regular';
            recordPayment($conn, $loan_id, $payment_date, $amount, $penalty_paid, $payment_method, $notes, $_SESSION['user_id'], $payment_type);
            header('Location: /cash_lending/mobile/payments.php?success=1');
            exit();
        } catch (Exception $e) {
            $errors[] = 'Error: ' . $e->getMessage();
        }
    }
}

include 'header.php';
?>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <i class="fas fa-exclamation-circle"></i>
        <?php echo implode('<br>', array_map('htmlspecialchars', $errors)); ?>
    </div>
<?php endif; ?>

<form method="POST">
    <div class="form-group">
        <label class="form-label">Loan / Borrower <span class="required">*</span></label>
        <select class="form-select" name="loan_id" required id="loanSelect" onchange="fillInstallment(this)">
            <option value="">— Select Loan —</option>
            <?php foreach ($active_loans as $l): ?>
                <option value="<?php echo $l['id']; ?>"
                        data-installment="<?php echo $l['installment_amount']; ?>"
                        data-balance="<?php echo $l['balance']; ?>"
                        <?php echo ($preselect_loan === $l['id'] || ($_POST['loan_id']??0) == $l['id']) ? 'selected':''; ?>>
                    <?php echo htmlspecialchars($l['first_name'] . ' ' . $l['last_name']); ?>
                    — ₱<?php echo number_format($l['balance'],2); ?> balance
                </option>
            <?php endforeach; ?>
        </select>
    </div>

    <div class="form-group">
        <label class="form-label">Payment Date <span class="required">*</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="form-group">
        <label class="form-label">Amount <span class="required">*</span></label>
        <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 class="form-group">
        <label class="form-label">Penalty (if any)</label>
        <input type="number" class="form-control" name="penalty_paid"
               step="0.01" min="0" value="<?php echo htmlspecialchars($_POST['penalty_paid'] ?? '0'); ?>">
    </div>

    <div class="form-group">
        <label class="form-label">Payment Method</label>
        <select class="form-select" name="payment_method">
            <option value="">— Select —</option>
            <?php foreach (['Cash','GCash','Bank Transfer','Others'] as $m): ?>
                <option value="<?php echo $m; ?>" <?php echo ($_POST['payment_method']??'') === $m ? 'selected':''; ?>><?php echo $m; ?></option>
            <?php endforeach; ?>
        </select>
    </div>

    <div class="form-group">
        <label class="form-label">Payment Type</label>
        <div style="display:flex;gap:0;border:1.5px solid var(--border);border-radius:10px;overflow:hidden;">
            <label id="lblRegular"
                   style="flex:1;padding:11px 8px;text-align:center;cursor:pointer;
                          background:var(--primary);color:#fff;font-size:13px;font-weight:700;
                          transition:all .15s;">
                <input type="radio" name="payment_type" value="regular" checked
                       style="display:none;" onchange="togglePayType(this.value)">
                <i class="fas fa-money-bill-wave"></i> Regular
            </label>
            <label id="lblInterest"
                   style="flex:1;padding:11px 8px;text-align:center;cursor:pointer;
                          background:#fff;color:var(--muted);font-size:13px;font-weight:700;
                          border-left:1.5px solid var(--border);transition:all .15s;">
                <input type="radio" name="payment_type" value="interest_only"
                       style="display:none;" onchange="togglePayType(this.value)">
                <i class="fas fa-percentage"></i> Interest Only
            </label>
        </div>
        <div id="interestNotice" style="display:none;margin-top:8px;padding:10px 12px;
             background:#fef3c7;border-radius:8px;font-size:12px;color:#92400e;font-weight:600;">
            <i class="fas fa-info-circle"></i>
            Principal balance will NOT be reduced. Interest charges only.
        </div>
    </div>

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

    <div class="d-flex gap-2 mt-3">
        <button type="submit" class="btn btn-success w-100"><i class="fas fa-save"></i> Save</button>
        <a href="/cash_lending/mobile/payments.php" class="btn btn-outline w-100"><i class="fas fa-times"></i> Cancel</a>
    </div>
</form>

<script>
function fillInstallment(sel) {
    const opt = sel.options[sel.selectedIndex];
    if (opt && opt.dataset.installment) {
        document.getElementById('amountField').value = parseFloat(opt.dataset.installment).toFixed(2);
    }
}
// Auto-fill on page load if pre-selected
window.addEventListener('DOMContentLoaded', () => {
    const sel = document.getElementById('loanSelect');
    if (sel && sel.value) fillInstallment(sel);
});

function togglePayType(val) {
    const isInterest = val === 'interest_only';
    document.getElementById('lblRegular').style.background   = isInterest ? '#fff'          : 'var(--primary)';
    document.getElementById('lblRegular').style.color        = isInterest ? 'var(--muted)'  : '#fff';
    document.getElementById('lblInterest').style.background  = isInterest ? 'var(--primary)': '#fff';
    document.getElementById('lblInterest').style.color       = isInterest ? '#fff'          : 'var(--muted)';
    document.getElementById('interestNotice').style.display  = isInterest ? 'block'         : 'none';
}
</script>

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