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

// 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'");
}

$id   = intval($_GET['id'] ?? 0);
$loan = fetchOne($conn,
    "SELECT l.*, b.first_name, b.last_name, b.contact, b.address, b.photo, b.id_type, b.id_number
     FROM loans l JOIN borrowers b ON l.borrower_id=b.id WHERE l.id=?",
    [$id], "i");
if (!$loan) { header('Location: /cash_lending/loans.php'); exit(); }

$payments = fetchAll($conn,
    "SELECT * FROM payments WHERE loan_id=? ORDER BY payment_date ASC",
    [$id], "i");

$schedule = generateAmortizationSchedule($loan);
$penalty  = calculatePenalty($loan);

// map paid dates
$paid_dates = [];
foreach ($payments as $p) {
    $paid_dates[$p['payment_date']] = true;
}

$badge = match($loan['status']) {
    'paid'     => 'bg-success',
    'overdue'  => 'bg-danger',
    'released' => 'bg-primary',
    'approved' => 'bg-info',
    default    => 'bg-warning text-dark',
};

$initials  = urlencode($loan['first_name'].'+'. $loan['last_name']);
$photo_src = !empty($loan['photo']) && file_exists($loan['photo'])
    ? '/cash_lending/'.$loan['photo']
    : "https://ui-avatars.com/api/?name={$initials}&size=80&background=0d6efd&color=fff&rounded=true";

include 'includes/header.php';
include 'includes/sidebar.php';
?>
<div class="row mb-4">
    <div class="col">
        <a href="/cash_lending/loans.php" class="btn btn-outline-secondary btn-sm mb-2">
            <i class="fas fa-arrow-left"></i> Back to Loans
        </a>
        <h3><i class="fas fa-file-contract"></i> Loan Details</h3>
    </div>
</div>

<?php if (($_GET['success'] ?? '') === 'renewed'): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
    <i class="fas fa-sync-alt"></i> <strong>Renewal submitted!</strong>
    The renewal loan has been created and is pending admin approval.
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<?php if (!empty($_GET['error'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($_GET['error']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="row">
<!-- Left column -->
<div class="col-lg-8">

    <!-- Loan summary card -->
    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Loan Summary</h5>
            <span class="badge <?php echo $badge; ?> fs-6"><?php echo ucfirst($loan['status']); ?></span>
        </div>

        <?php
        // Show renewal chain notices (guard: only query if renewed_from column exists)
        $renewal_notice = '';
        $hasRenewedCol = $conn->query("SHOW COLUMNS FROM loans LIKE 'renewed_from'")->num_rows > 0;
        if ($hasRenewedCol) {
            if (!empty($loan['renewed_from'])) {
                $pid = $loan['renewed_from'];
                $renewal_notice = '<div class="alert alert-info py-2 px-3 mb-0 rounded-0" style="font-size:13px;">'
                    . '<i class="fas fa-sync-alt"></i> This is a renewal of '
                    . '<a href="/cash_lending/loan-details.php?id=' . $pid . '" class="fw-bold">Loan #' . $pid . '</a>'
                    . '</div>';
            }
            $renewed_into = fetchOne($conn, "SELECT id FROM loans WHERE renewed_from = ?", [$id], "i");
            if ($renewed_into) {
                $rid = $renewed_into['id'];
                $renewal_notice .= '<div class="alert alert-warning py-2 px-3 mb-0 rounded-0" style="font-size:13px;">'
                    . '<i class="fas fa-arrow-right"></i> Renewed into '
                    . '<a href="/cash_lending/loan-details.php?id=' . $rid . '" class="fw-bold">Loan #' . $rid . '</a>'
                    . '</div>';
            }
        }
        echo $renewal_notice;
        ?>
        <div class="card-body">
            <div class="row g-3">
                <?php foreach ([
                    ['Loan Amount',   '₱'.number_format($loan['loan_amount'],2),    'primary'],
                    ['Total Payable', '₱'.number_format($loan['total_payable'],2),  'info'],
                    ['Balance',       '₱'.number_format($loan['balance'],2),        'danger'],
                    ['Installment',   '₱'.number_format($loan['installment_amount'],2),'warning'],
                ] as [$lbl,$val,$clr]): ?>
                <div class="col-sm-6 col-md-3">
                    <div class="border rounded-3 p-3 text-center">
                        <div class="text-muted small"><?php echo $lbl; ?></div>
                        <div class="fw-bold fs-5 text-<?php echo $clr; ?>"><?php echo $val; ?></div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php if ($penalty > 0): ?>
            <div class="alert alert-danger mt-3 mb-0 py-2">
                <i class="fas fa-exclamation-triangle"></i>
                <strong>Overdue Penalty:</strong> ₱<?php echo number_format($penalty,2); ?>
                (<?php echo $loan['penalty']; ?>% of balance)
            </div>
            <?php endif; ?>
            <hr>
            <div class="row">
                <?php foreach ([
                    ['Application Date', date('M d, Y', strtotime($loan['created_at']))],
                    ['Interest Rate', $loan['interest_rate'].'%'],
                    ['Payment Mode',  ucfirst($loan['payment_mode'])],
                    ['Release Date',  in_array($loan['status'], ['pending','approved']) ? '— (set on release)' : date('M d, Y', strtotime($loan['release_date']))],
                    ['Due Date',      in_array($loan['status'], ['pending','approved']) ? '— (set on release)' : date('M d, Y', strtotime($loan['due_date']))],
                ] as [$lbl,$val]): ?>
                <div class="col-sm-6 mb-2">
                    <small class="text-muted"><?php echo $lbl; ?></small>
                    <div class="fw-semibold"><?php echo htmlspecialchars($val); ?></div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="card-footer d-flex gap-2 flex-wrap">
            <?php if (in_array($loan['status'], ['released', 'overdue'])): ?>
                <a href="/cash_lending/add-payment.php?loan_id=<?php echo $id; ?>"
                   class="btn btn-success"><i class="fas fa-money-bill-wave"></i> Record Payment</a>
            <?php endif; ?>
            <?php if ($loan['status'] === 'pending'): ?>
                <button class="btn btn-info text-white" onclick="approveLoan(<?php echo $id; ?>)">
                    <i class="fas fa-check"></i> Approve Loan
                </button>
            <?php endif; ?>
            <?php if ($loan['status'] === 'approved'): ?>
                <button class="btn btn-primary" onclick="releaseLoan(<?php echo $id; ?>)">
                    <i class="fas fa-hand-holding-usd"></i> Mark as Released
                </button>
            <?php endif; ?>
            <?php
            $renewal = canRenewLoan($conn, $loan);
            if ($renewal['allowed']): ?>
                <a href="/cash_lending/renew-loan.php?loan_id=<?php echo $id; ?>"
                   class="btn btn-warning"><i class="fas fa-sync-alt"></i> Renew Loan</a>
            <?php elseif (in_array($loan['status'], ['released','overdue','paid'])): ?>
                <button class="btn btn-warning" disabled
                        title="<?php echo htmlspecialchars($renewal['reason']); ?>">
                    <i class="fas fa-sync-alt"></i> Renew Loan
                </button>
            <?php endif; ?>
            <?php if (in_array($loan['status'], ['released','overdue','paid']) && !$renewal['allowed']): ?>
                <div class="alert alert-warning py-2 mt-2 mb-0" style="font-size:13px;">
                    <i class="fas fa-lock"></i> <strong>Renewal blocked:</strong>
                    <?php echo htmlspecialchars($renewal['reason']); ?>
                </div>
            <?php endif; ?>
            <a href="/cash_lending/receipt.php?loan_id=<?php echo $id; ?>" target="_blank"
               class="btn btn-outline-secondary"><i class="fas fa-print"></i> Print</a>
        </div>
    </div>

    <!-- Amortization schedule -->
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-calendar-alt"></i> Payment Schedule</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive" style="max-height:320px;overflow-y:auto;">
                <table class="table table-sm mb-0">
                    <thead class="sticky-top bg-light">
                        <tr>
                            <th>#</th>
                            <th>Due Date</th>
                            <th>Amount</th>
                            <th>Remaining</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($schedule as $s):
                            $is_paid = isset($paid_dates[$s['due_date']]);
                            $is_overdue = !$is_paid && $s['due_date'] < date('Y-m-d');
                        ?>
                        <tr class="<?php echo $is_paid?'table-success':($is_overdue?'table-danger':''); ?>">
                            <td><?php echo $s['term']; ?></td>
                            <td><?php echo date('M d, Y', strtotime($s['due_date'])); ?></td>
                            <td>₱<?php echo number_format($s['amount'],2); ?></td>
                            <td>₱<?php echo number_format($s['balance'],2); ?></td>
                            <td>
                                <?php if ($is_paid): ?>
                                    <span class="badge bg-success">Paid</span>
                                <?php elseif ($is_overdue): ?>
                                    <span class="badge bg-danger">Overdue</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Pending</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Payment history -->
    <div class="card">
        <div class="card-header"><h5 class="mb-0"><i class="fas fa-receipt"></i> Payment History</h5></div>
        <div class="card-body p-0">
            <?php if (!empty($payments)): ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr><th>Receipt #</th><th>Date</th><th>Amount</th><th>Penalty</th><th>Method</th><th></th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($payments as $p): ?>
                        <tr>
                            <td><code><?php echo htmlspecialchars($p['receipt_number']); ?></code></td>
                            <td><?php echo date('M d, Y', strtotime($p['payment_date'])); ?></td>
                            <td class="text-success fw-bold">₱<?php echo number_format($p['amount'],2); ?></td>
                            <td><?php echo $p['penalty_paid']>0?'<span class="text-danger">₱'.number_format($p['penalty_paid'],2).'</span>':'—'; ?></td>
                            <td><?php echo htmlspecialchars($p['payment_method']??'—'); ?></td>
                            <td class="d-flex gap-1">
                                <a href="/cash_lending/receipt.php?id=<?php echo $p['id']; ?>"
                                   target="_blank" class="btn btn-sm btn-outline-secondary" title="Print Receipt">
                                    <i class="fas fa-receipt"></i>
                                </a>
                                <?php if (isAdmin()): ?>
                                <button class="btn btn-sm btn-outline-danger"
                                        title="Void this payment"
                                        onclick="voidPayment(<?php echo $p['id']; ?>, '<?php echo date('M d, Y', strtotime($p['payment_date'])); ?>', <?php echo $p['amount']; ?>)">
                                    <i class="fas fa-ban"></i>
                                </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php else: ?>
                <div class="p-4 text-center text-muted">No payments recorded yet</div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Right column — borrower info -->
<div class="col-lg-4">
    <div class="card mb-4">
        <div class="card-header"><h5 class="mb-0">Borrower</h5></div>
        <div class="card-body text-center">
            <img src="<?php echo htmlspecialchars($photo_src); ?>"
                 style="width:80px;height:80px;border-radius:50%;object-fit:cover;
                        border:3px solid #0d6efd;" class="mb-3" alt="">
            <h5 class="mb-1"><?php echo htmlspecialchars($loan['first_name'].' '.$loan['last_name']); ?></h5>
            <div class="text-muted small mb-3"><?php echo htmlspecialchars($loan['contact']); ?></div>
            <table class="table table-sm text-start">
                <tr><td class="text-muted">Address</td><td><?php echo htmlspecialchars($loan['address']); ?></td></tr>
                <tr><td class="text-muted">ID Type</td><td><?php echo htmlspecialchars($loan['id_type']); ?></td></tr>
                <tr><td class="text-muted">ID #</td><td><?php echo htmlspecialchars($loan['id_number']); ?></td></tr>
            </table>
            <a href="/cash_lending/edit-borrower.php?id=<?php echo $loan['borrower_id']; ?>"
               class="btn btn-outline-primary btn-sm w-100">
                <i class="fas fa-edit"></i> Edit Borrower
            </a>
        </div>
    </div>

    <!-- Progress -->
    <?php
    $paid_total = array_sum(array_column($payments,'amount'));
    $progress   = $loan['total_payable'] > 0 ? min(100, round($paid_total/$loan['total_payable']*100)) : 0;
    ?>
    <div class="card">
        <div class="card-header"><h5 class="mb-0">Repayment Progress</h5></div>
        <div class="card-body">
            <div class="d-flex justify-content-between mb-1">
                <small>₱<?php echo number_format($paid_total,2); ?> paid</small>
                <small><?php echo $progress; ?>%</small>
            </div>
            <div class="progress" style="height:12px;border-radius:8px;">
                <div class="progress-bar <?php echo $progress>=100?'bg-success':'bg-primary'; ?>"
                     style="width:<?php echo $progress; ?>%;border-radius:8px;"></div>
            </div>
            <div class="text-muted small mt-1 text-end">
                of ₱<?php echo number_format($loan['total_payable'],2); ?> total
            </div>
        </div>
    </div>
</div>
</div>

<script>
function approveLoan(id) {
    if (!confirm('Approve this loan?')) return;
    fetch('/cash_lending/api/approve-loan.php', {
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'id='+id
    }).then(r=>r.json()).then(d=>{ if(d.success) location.reload(); else alert(d.message); });
}

function releaseLoan(id) {
    if (!confirm('Mark this loan as Released? This means the cash has been handed to the borrower.')) return;
    fetch('/cash_lending/api/release-loan.php', {
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'id='+id
    }).then(r=>r.json()).then(d=>{ if(d.success) location.reload(); else alert(d.message); });
}

function voidPayment(id, date, amount) {
    if (!confirm('Void payment of ₱' + parseFloat(amount).toLocaleString('en-PH', {minimumFractionDigits:2}) + ' on ' + date + '?\n\nThis will restore the loan balance and cannot be undone.')) return;
    fetch('/cash_lending/api/void-payment.php', {
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'id='+id
    }).then(r=>r.json()).then(d=>{ if(d.success) location.reload(); else alert(d.message); });
}
</script>
<?php include 'includes/footer.php'; ?>
