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

// Auto-migrate: add renewed_from column if it doesn't exist yet
$col = $conn->query("SHOW COLUMNS FROM loans LIKE 'renewed_from'");
if ($col && $col->num_rows === 0) {
    $conn->query("ALTER TABLE loans ADD COLUMN renewed_from INT DEFAULT NULL AFTER status");
    $conn->query("ALTER TABLE loans ADD CONSTRAINT fk_renewed_from FOREIGN KEY (renewed_from) REFERENCES loans(id) ON DELETE SET NULL");
}

// Auto-migrate: add 'released' to status enum if not present
$enumRow = $conn->query("SHOW COLUMNS FROM loans LIKE 'status'")->fetch_assoc();
if ($enumRow && strpos($enumRow['Type'], 'released') === false) {
    $conn->query("ALTER TABLE loans MODIFY COLUMN status ENUM('pending','approved','released','paid','overdue') DEFAULT 'pending'");
}

$settings  = getSettings($conn);
$origin_id = intval($_GET['loan_id'] ?? 0);
if (!$origin_id) { header('Location: /cash_lending/loans.php'); exit(); }

// Load original loan
$origin = fetchOne($conn,
    "SELECT l.*, b.first_name, b.last_name
     FROM loans l JOIN borrowers b ON l.borrower_id = b.id
     WHERE l.id = ?", [$origin_id], "i");

if (!$origin) { header('Location: /cash_lending/loans.php'); exit(); }

// Only allow renewal on approved, overdue, or paid loans — and only if interest is paid
$renewal_check = canRenewLoan($conn, $origin);
if (!$renewal_check['allowed']) {
    header('Location: /cash_lending/loan-details.php?id=' . $origin_id . '&error=' . urlencode($renewal_check['reason']));
    exit();
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $loan_amount   = floatval($_POST['loan_amount']   ?? 0);
    $interest_rate = floatval($_POST['interest_rate'] ?? 0);
    $term          = intval($_POST['term']            ?? 0);
    $payment_mode  = $_POST['payment_mode']           ?? 'monthly';
    $penalty       = floatval($_POST['penalty']       ?? 0);
    $release_date  = date('Y-m-d'); // placeholder; overwritten on approval
    $due_date      = date('Y-m-d'); // placeholder; overwritten on approval

    if ($loan_amount <= 0) $errors[] = 'Loan amount must be greater than 0';
    if ($term <= 0)        $errors[] = 'Term must be greater than 0';
    if (!in_array($payment_mode, ['daily','weekly','monthly'])) $errors[] = 'Invalid payment mode';

    if (empty($errors)) {
        try {
            // Roll outstanding balance into new loan only if checkbox is checked
            $outstanding = floatval($origin['balance']);
            if ($outstanding > 0 && isset($_POST['roll_balance'])) {
                $loan_amount += $outstanding;
            }

            $new_loan_id = addLoan(
                $conn,
                $origin['borrower_id'],
                $loan_amount,
                $interest_rate,
                $term,
                $release_date,
                $due_date,
                $payment_mode,
                $penalty,
                $origin_id   // renewed_from
            );

            // Mark the original loan as paid since it is being renewed
            executeQuery($conn,
                "UPDATE loans SET status = 'paid' WHERE id = ?",
                [$origin_id], "i");

            logActivity($conn, $_SESSION['user_id'], 'renew_loan',
                "Renewal of loan #$origin_id — marked as paid. New loan #$new_loan_id for ₱$loan_amount");
            header('Location: /cash_lending/loan-details.php?id=' . $new_loan_id . '&success=renewed');
            exit();
        } catch (Exception $e) {
            $errors[] = 'Error: ' . $e->getMessage();
        }
    }
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<div class="row mb-4">
    <div class="col">
        <a href="/cash_lending/loan-details.php?id=<?php echo $origin_id; ?>"
           class="btn btn-outline-secondary btn-sm mb-2">
            <i class="fas fa-arrow-left"></i> Back to Loan #<?php echo $origin_id; ?>
        </a>
        <h3><i class="fas fa-sync-alt"></i> Renew Loan</h3>
        <p class="text-muted mb-0">
            Borrower: <strong><?php echo htmlspecialchars($origin['first_name'] . ' ' . $origin['last_name']); ?></strong>
            &nbsp;·&nbsp; Original Loan #<?php echo $origin_id; ?>
            &nbsp;·&nbsp; <span class="badge bg-secondary"><?php echo ucfirst($origin['status']); ?></span>
        </p>
    </div>
</div>

<div class="row">
<div class="col-lg-7">

<!-- Original loan summary -->
<div class="card mb-4 border-0" style="background:#f8faff;">
    <div class="card-body py-3">
        <div class="row text-center">
            <div class="col-4">
                <div class="text-muted small">Original Amount</div>
                <div class="fw-bold">₱<?php echo number_format($origin['loan_amount'], 2); ?></div>
            </div>
            <div class="col-4">
                <div class="text-muted small">Balance Remaining</div>
                <div class="fw-bold <?php echo $origin['balance'] > 0 ? 'text-danger' : 'text-success'; ?>">
                    ₱<?php echo number_format($origin['balance'], 2); ?>
                </div>
            </div>
            <div class="col-4">
                <div class="text-muted small">Original Term</div>
                <div class="fw-bold">
                    <?php echo $origin['term']; ?>
                    <?php echo $origin['payment_mode'] === 'daily' ? 'days' : ($origin['payment_mode'] === 'weekly' ? 'weeks' : 'months'); ?>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card">
<div class="card-header">
    <h5 class="mb-0"><i class="fas fa-sync-alt"></i> Renewal Details</h5>
    <small class="text-muted">Loan will be submitted as <strong>Pending</strong> and requires admin approval.</small>
</div>
<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">
        <input type="hidden" name="borrower_id" value="<?php echo $origin['borrower_id']; ?>">

        <?php if ($origin['balance'] > 0): ?>
        <div class="alert alert-warning mb-3">
            <i class="fas fa-exclamation-triangle"></i>
            <strong>Outstanding balance of ₱<?php echo number_format($origin['balance'], 2); ?></strong>
            has been automatically added to the new loan amount below.
            The old loan will be marked as <strong>paid</strong> upon renewal.
        </div>
        <div class="form-check mb-3">
            <input class="form-check-input" type="checkbox" name="ignore_balance" id="ignoreBalance"
                   onchange="toggleBalanceRollover(this)">
            <label class="form-check-label" for="ignoreBalance">
                Do <strong>not</strong> roll outstanding balance into new loan
                (write off ₱<?php echo number_format($origin['balance'], 2); ?>)
            </label>
        </div>
        <?php endif; ?>

        <!-- Borrower (locked) -->
        <div class="mb-3">
            <label class="form-label fw-semibold">Borrower</label>
            <input type="text" class="form-control"
                   value="<?php echo htmlspecialchars($origin['first_name'] . ' ' . $origin['last_name']); ?>"
                   disabled style="background:#f8f9fa;">
        </div>

        <div class="row">
            <div class="col-md-6 mb-3">
                <label class="form-label fw-semibold">New Loan Amount <span class="text-danger">*</span></label>
                <div class="input-group">
                    <span class="input-group-text">₱</span>
                    <input type="number" class="form-control" name="loan_amount" id="loanAmount"
                           step="0.01" min="1" required oninput="calculateLoan()"
                           value="<?php echo htmlspecialchars($_POST['loan_amount'] ?? $origin['loan_amount']); ?>">
                </div>
            </div>
            <div class="col-md-6 mb-3">
                <label class="form-label fw-semibold">Interest Rate (% monthly)</label>
                <input type="number" class="form-control" name="interest_rate" id="interestRate"
                       step="0.01" min="0" oninput="calculateLoan()"
                       value="<?php echo htmlspecialchars($_POST['interest_rate'] ?? $origin['interest_rate']); ?>">
            </div>
        </div>

        <div class="row">
            <div class="col-md-6 mb-3">
                <label class="form-label fw-semibold">Term <span class="text-danger">*</span></label>
                <div class="input-group">
                    <input type="number" class="form-control" name="term" id="term"
                           min="1" required oninput="calculateLoan()"
                           value="<?php echo htmlspecialchars($_POST['term'] ?? $origin['term']); ?>">
                    <span class="input-group-text" id="termUnit">months</span>
                </div>
            </div>
            <div class="col-md-6 mb-3">
                <label class="form-label fw-semibold">Payment Mode</label>
                <select class="form-select" name="payment_mode" id="paymentMode" onchange="calculateLoan()">
                    <?php foreach (['monthly'=>'Monthly','weekly'=>'Weekly','daily'=>'Daily'] as $v => $l): ?>
                        <option value="<?php echo $v; ?>"
                            <?php echo (($_POST['payment_mode'] ?? $origin['payment_mode']) === $v) ? 'selected' : ''; ?>>
                            <?php echo $l; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <div class="mb-3">
            <label class="form-label fw-semibold">Penalty Rate (%)</label>
            <input type="number" class="form-control" name="penalty" step="0.01" min="0"
                   value="<?php echo htmlspecialchars($_POST['penalty'] ?? $origin['penalty']); ?>">
        </div>

        <!-- Live preview -->
        <div class="card border-primary mb-4" id="calcPreview">
            <div class="card-body py-2">
                <div class="row text-center">
                    <div class="col-4">
                        <div class="text-muted small">Total Interest</div>
                        <div class="fw-bold text-warning" id="previewInterest">—</div>
                    </div>
                    <div class="col-4">
                        <div class="text-muted small">Total Payable</div>
                        <div class="fw-bold text-primary" id="previewTotal">—</div>
                    </div>
                    <div class="col-4">
                        <div class="text-muted small">Per <span id="previewModeLabel">Month</span></div>
                        <div class="fw-bold text-success" id="previewInstall">—</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="alert alert-info py-2" style="font-size:13px;">
            <i class="fas fa-info-circle"></i>
            Release date and due date will be set automatically when admin approves this renewal.
        </div>

        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-sync-alt"></i> Submit Renewal
            </button>
            <a href="/cash_lending/loan-details.php?id=<?php echo $origin_id; ?>"
               class="btn btn-outline-secondary">Cancel</a>
        </div>
    </form>
</div>
</div>
</div>

<div class="col-lg-5">
    <div class="card border-0" style="background:#fffbeb;">
        <div class="card-body">
            <h6 class="fw-bold mb-3"><i class="fas fa-lightbulb text-warning"></i> Renewal Notes</h6>
            <ul class="text-muted small mb-0" style="line-height:2;">
                <li>The new loan is linked to the original Loan #<?php echo $origin_id; ?></li>
                <li>It will stay <strong>Pending</strong> until an admin approves it</li>
                <li>Release date is set on approval date</li>
                <li>You can adjust the amount, term, and rate for the renewal</li>
                <?php if ($origin['balance'] > 0): ?>
                <li class="text-danger">Original loan still has ₱<?php echo number_format($origin['balance'],2); ?> balance</li>
                <?php endif; ?>
            </ul>
        </div>
    </div>
</div>
</div>

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

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

function calculateLoan() {
    const amount = parseFloat(document.getElementById('loanAmount').value) || 0;
    const rate   = parseFloat(document.getElementById('interestRate').value) || 0;
    const term   = parseInt(document.getElementById('term').value) || 0;
    const mode   = document.getElementById('paymentMode').value;

    document.getElementById('termUnit').textContent =
        mode === 'daily' ? 'days' : mode === 'weekly' ? 'weeks' : 'months';
    document.getElementById('previewModeLabel').textContent =
        mode === 'daily' ? 'Day' : mode === 'weekly' ? 'Week' : 'Month';

    if (!amount || !term) return;

    let termInMonths;
    if (mode === 'daily')       termInMonths = term / 30;
    else if (mode === 'weekly') termInMonths = (term * 7) / 30;
    else                        termInMonths = term;

    const interest   = amount * (rate / 100) * termInMonths;
    const total      = amount + interest;
    const installAmt = total / term;

    document.getElementById('previewInterest').textContent = fmt(interest);
    document.getElementById('previewTotal').textContent    = fmt(total);
    document.getElementById('previewInstall').textContent  = fmt(installAmt);
}

document.addEventListener('DOMContentLoaded', calculateLoan);

function toggleBalanceRollover(checkbox) {
    const outstanding = <?php echo floatval($origin['balance'] ?? 0); ?>;
    const amtInput = document.getElementById('loanAmount');
    let current = parseFloat(amtInput.value) || 0;
    if (checkbox.checked) {
        // Remove the outstanding balance from the amount
        amtInput.value = Math.max(0, current - outstanding).toFixed(2);
    } else {
        // Add the outstanding balance back
        amtInput.value = (current + outstanding).toFixed(2);
    }
    calculateLoan();
}
</script>
