<?php
/**
 * Pinjaman (Loans) Management
 * Koperasi Management System
 */

$pageTitle = 'Pinjaman';
$pageSubtitle = 'Kelola pinjaman anggota koperasi';

require_once __DIR__ . '/config/database.php';
$db = getDB();

// Safe migration for renaming bunga to jasa
try {
    // Check if bunga_persen column exists
    $checkColumn = $db->query("SHOW COLUMNS FROM pinjaman LIKE 'bunga_persen'")->fetch();
    if ($checkColumn) {
        $db->exec("ALTER TABLE pinjaman CHANGE bunga_persen jasa_persen DECIMAL(5, 2) NOT NULL DEFAULT 1.00");
    }
    
    // Check if bunga_pinjaman setting exists
    $checkSetting = $db->prepare("SELECT * FROM pengaturan WHERE kunci = 'bunga_pinjaman'");
    $checkSetting->execute();
    if ($checkSetting->fetch()) {
        $db->exec("UPDATE pengaturan SET kunci = 'jasa_pinjaman', deskripsi = 'jasa pinjaman per bulan (%)' WHERE kunci = 'bunga_pinjaman'");
    }

    // Ensure table is named tabungan_siswa (undo accidental rename to tajasan_siswa)
    $checkTable = $db->query("SHOW TABLES LIKE 'tajasan_siswa'")->fetch();
    if ($checkTable) {
        $db->exec("RENAME TABLE tajasan_siswa TO tabungan_siswa");
    }

    // New migration: Separate Pokok and Jasa
    $columns = $db->query("SHOW COLUMNS FROM pinjaman")->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array('sisa_pokok', $columns)) {
        $db->exec("ALTER TABLE pinjaman ADD COLUMN sisa_pokok DECIMAL(15, 2) NOT NULL DEFAULT 0 AFTER sisa_pinjaman");
    }
    if (!in_array('sisa_jasa', $columns)) {
        $db->exec("ALTER TABLE pinjaman ADD COLUMN sisa_jasa DECIMAL(15, 2) NOT NULL DEFAULT 0 AFTER sisa_pokok");
    }

    // Initialize existing records if sisa_pokok is still 0 but sisa_pinjaman is not
    // We assume if sisa_pokok AND sisa_jasa are both 0, they haven't been initialized
    $db->exec("UPDATE pinjaman SET sisa_pokok = jumlah_pinjaman, sisa_jasa = total_bayar - jumlah_pinjaman WHERE sisa_pokok = 0 AND sisa_jasa = 0 AND status != 'lunas' AND sisa_pinjaman > 0");

    $angColumns = $db->query("SHOW COLUMNS FROM angsuran")->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array('bayar_pokok', $angColumns)) {
        $db->exec("ALTER TABLE angsuran ADD COLUMN bayar_pokok DECIMAL(15, 2) NOT NULL DEFAULT 0 AFTER jumlah_bayar");
    }
    if (!in_array('bayar_jasa', $angColumns)) {
        $db->exec("ALTER TABLE angsuran ADD COLUMN bayar_jasa DECIMAL(15, 2) NOT NULL DEFAULT 0 AFTER bayar_pokok");
    }
} catch (PDOException $e) { /* silent fail for safety but PDO specific */ }
catch (Exception $e) { /* catch all */ }

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $anggotaId = $_POST['anggota_id'] ?? '';
        if (empty($anggotaId)) {
            $typed = $_POST['anggota_search'] ?? 'kosong';
            setFlash('danger', "Gagal: Anggota harus dipilih dari daftar. Anda mengetik '$typed' tapi belum memilih dari daftar yang muncul.");
            header('Location: pinjaman.php');
            exit;
        }
        $no_pinjaman = generateNumber('PNJ', 'pinjaman', 'no_pinjaman');
        $jumlah = (float)str_replace('.', '', $_POST['jumlah_pinjaman']);
        $jasa = (float)$_POST['jasa_persen'];
        $lama = (int)$_POST['lama_angsuran'];
        $totaljasa = $jumlah * ($jasa / 100) * $lama;
        $totalBayar = $jumlah + $totaljasa;
        $angsuranPerBulan = ceil($totalBayar / $lama);
        
        $tanggalPinjaman = $_POST['tanggal_pinjaman'];
        $jatuhTempo = date('Y-m-d', strtotime("+$lama months", strtotime($tanggalPinjaman)));
        
        $stmt = $db->prepare("INSERT INTO pinjaman (anggota_id, no_pinjaman, jumlah_pinjaman, jasa_persen, lama_angsuran, jumlah_angsuran, total_bayar, sisa_pinjaman, sisa_pokok, sisa_jasa, tanggal_pinjaman, tanggal_jatuh_tempo, catatan, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $_POST['anggota_id'],
            $no_pinjaman,
            $jumlah,
            $jasa,
            $lama,
            $angsuranPerBulan,
            $totalBayar,
            $totalBayar, // combined sisa
            $jumlah,      // sisa_pokok
            $totaljasa,  // sisa_jasa
            $tanggalPinjaman,
            $jatuhTempo,
            sanitize($_POST['catatan'] ?? ''),
            $_SESSION['user_id']
        ]);
        setFlash('success', "Pinjaman $no_pinjaman berhasil diajukan.");
        header('Location: pinjaman.php');
        exit;
    }
    
    if ($action === 'approve') {
        $stmt = $db->prepare("UPDATE pinjaman SET status = 'disetujui', disetujui_oleh = ?, tanggal_persetujuan = CURDATE() WHERE id = ?");
        $stmt->execute([$_SESSION['user_id'], $_POST['id']]);
        setFlash('success', 'Pinjaman berhasil disetujui.');
        header('Location: pinjaman.php');
        exit;
    }
    
    if ($action === 'reject') {
        $stmt = $db->prepare("UPDATE pinjaman SET status = 'ditolak' WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        setFlash('success', 'Pinjaman telah ditolak.');
        header('Location: pinjaman.php');
        exit;
    }
    
    if ($action === 'bayar') {
        $pinjamanId = $_POST['pinjaman_id'];
        $jumlahBayar = (float)str_replace('.', '', $_POST['jumlah_bayar']);
        
        // Get current loan info
        $loan = $db->prepare("SELECT * FROM pinjaman WHERE id = ?");
        $loan->execute([$pinjamanId]);
        $loanData = $loan->fetch();
        
        if ($loanData) {
            // Count existing installments
            $angsuranKe = $db->prepare("SELECT COUNT(*) FROM angsuran WHERE pinjaman_id = ?");
            $angsuranKe->execute([$pinjamanId]);
            $nomorAngsuran = $angsuranKe->fetchColumn() + 1;
            
            // Calculate Split: prioritize Jasa first (or fixed jasa per month)
            // Monthly Jasa = Initial Principal * (Rate / 100)
            $jasaPerBulan = $loanData['jumlah_pinjaman'] * ($loanData['jasa_persen'] / 100);
            $bayarJasa = min($jumlahBayar, $loanData['sisa_jasa'], $jasaPerBulan);
            $bayarPokok = $jumlahBayar - $bayarJasa;

            // Insert installment
            $stmt = $db->prepare("INSERT INTO angsuran (pinjaman_id, angsuran_ke, jumlah_bayar, bayar_pokok, bayar_jasa, tanggal_bayar, keterangan, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $pinjamanId,
                $nomorAngsuran,
                $jumlahBayar,
                $bayarPokok,
                $bayarJasa,
                $_POST['tanggal_bayar'],
                sanitize($_POST['keterangan'] ?? "Angsuran ke-$nomorAngsuran"),
                $_SESSION['user_id']
            ]);
            
            // Update remaining balances
            $newSisaPokok = max(0, $loanData['sisa_pokok'] - $bayarPokok);
            $newSisaJasa = max(0, $loanData['sisa_jasa'] - $bayarJasa);
            $newSisaTotal = $newSisaPokok + $newSisaJasa;
            $newStatus = $newSisaTotal <= 0 ? 'lunas' : 'disetujui';

            $update = $db->prepare("UPDATE pinjaman SET sisa_pinjaman = ?, sisa_pokok = ?, sisa_jasa = ?, status = ? WHERE id = ?");
            $update->execute([$newSisaTotal, $newSisaPokok, $newSisaJasa, $newStatus, $pinjamanId]);
            
            setFlash('success', "Angsuran ke-$nomorAngsuran berhasil dicatat (Pokok: " . formatRupiah($bayarPokok) . ", Jasa: " . formatRupiah($bayarJasa) . ").");
        }
        header('Location: pinjaman.php?detail=' . $pinjamanId);
        exit;
    }
    
    if ($action === 'edit') {
        $id = $_POST['id'];
        $jumlah = (float)str_replace('.', '', $_POST['jumlah_pinjaman']);
        $jasa = (float)$_POST['jasa_persen'];
        $lama = (int)$_POST['lama_angsuran'];
        $totaljasa = $jumlah * ($jasa / 100) * $lama;
        $totalBayar = $jumlah + $totaljasa;
        $angsuranPerBulan = ceil($totalBayar / $lama);
        
        $tanggalPinjaman = $_POST['tanggal_pinjaman'];
        $jatuhTempo = date('Y-m-d', strtotime("+$lama months", strtotime($tanggalPinjaman)));
        
        $sisaPokokManual = isset($_POST['sisa_pokok']) ? (float)str_replace('.', '', $_POST['sisa_pokok']) : $jumlah;
        $sisaJasaManual = isset($_POST['sisa_jasa']) ? (float)str_replace('.', '', $_POST['sisa_jasa']) : $totaljasa;
        $sisaTotalManual = $sisaPokokManual + $sisaJasaManual;
        
        $stmt = $db->prepare("UPDATE pinjaman SET anggota_id = ?, jumlah_pinjaman = ?, jasa_persen = ?, lama_angsuran = ?, jumlah_angsuran = ?, total_bayar = ?, sisa_pinjaman = ?, sisa_pokok = ?, sisa_jasa = ?, tanggal_pinjaman = ?, tanggal_jatuh_tempo = ?, catatan = ? WHERE id = ?");
        $stmt->execute([
            $_POST['anggota_id'],
            $jumlah,
            $jasa,
            $lama,
            $angsuranPerBulan,
            $totalBayar,
            $sisaTotalManual, // sisa gabungan
            $sisaPokokManual, // sisa pokok
            $sisaJasaManual,  // sisa jasa
            $tanggalPinjaman,
            $jatuhTempo,
            sanitize($_POST['catatan'] ?? ''),
            $id
        ]);
        setFlash('success', 'Data pinjaman berhasil diperbarui.');
        header('Location: pinjaman.php');
        exit;
    }
    
    if ($action === 'delete') {
        $stmt = $db->prepare("DELETE FROM pinjaman WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        setFlash('success', 'Pinjaman berhasil dihapus.');
        header('Location: pinjaman.php');
        exit;
    }
    
    if ($action === 'bulk_delete') {
        $ids = $_POST['ids'] ?? [];
        if (!empty($ids)) {
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $stmt = $db->prepare("DELETE FROM pinjaman WHERE id IN ($placeholders)");
            $stmt->execute($ids);
            setFlash('success', 'Pinjaman berhasil dihapus (' . count($ids) . ' data).');
        }
        header('Location: pinjaman.php');
        exit;
    }
}

// Edit data for modal
$editData = null;
if (isset($_GET['edit'])) {
    $editStmt = $db->prepare("SELECT * FROM pinjaman WHERE id = ? AND status IN ('pending', 'disetujui')");
    $editStmt->execute([$_GET['edit']]);
    $editData = $editStmt->fetch();
    if (!$editData) {
        setFlash('danger', 'Pinjaman tidak ditemukan atau sudah tidak dapat diedit.');
        header('Location: pinjaman.php');
        exit;
    }
}

// Detail view
$detailData = null;
$angsuranList = [];
if (isset($_GET['detail'])) {
    $detailStmt = $db->prepare("SELECT p.*, a.nama, a.no_anggota, a.telepon FROM pinjaman p JOIN anggota a ON p.anggota_id = a.id WHERE p.id = ?");
    $detailStmt->execute([$_GET['detail']]);
    $detailData = $detailStmt->fetch();
    
    if ($detailData) {
        $angPaidStmt = $db->prepare("SELECT COUNT(*) FROM angsuran WHERE pinjaman_id = ?");
        $angPaidStmt->execute([$detailData['id']]);
        $detailData['ang_paid'] = $angPaidStmt->fetchColumn();
        
        $angsuranStmt = $db->prepare("SELECT * FROM angsuran WHERE pinjaman_id = ? ORDER BY angsuran_ke ASC");
        $angsuranStmt->execute([$_GET['detail']]);
        $angsuranList = $angsuranStmt->fetchAll();
    }
}

// List filters
$search = $_GET['search'] ?? '';
$statusFilter = $_GET['status'] ?? '';
$bulanFilter = $_GET['bulan'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 10;
$offset = ($page - 1) * $perPage;

// Helper function to format month
$where = "WHERE 1=1";
$params = [];

if ($search) {
    $where .= " AND (a.nama LIKE ? OR p.no_pinjaman LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($statusFilter) {
    $where .= " AND p.status = ?";
    $params[] = $statusFilter;
}
if ($bulanFilter) {
    $where .= " AND DATE_FORMAT(p.tanggal_pinjaman, '%Y-%m') = ?";
    $params[] = $bulanFilter;
}

$countStmt = $db->prepare("SELECT COUNT(*) FROM pinjaman p JOIN anggota a ON p.anggota_id = a.id $where");
$countStmt->execute($params);
$totalRows = $countStmt->fetchColumn();
$totalPages = ceil($totalRows / $perPage);

$stmt = $db->prepare("
    SELECT p.*, a.nama, a.no_anggota, a.telepon,
           (SELECT COUNT(*) FROM angsuran WHERE pinjaman_id = p.id) as ang_paid
    FROM pinjaman p 
    JOIN anggota a ON p.anggota_id = a.id 
    $where 
    ORDER BY p.created_at DESC 
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$pinjamanList = $stmt->fetchAll();

// Handle AJAX request for member loan recap
if (isset($_GET['ajax_rekap_anggota'])) {
    header('Content-Type: application/json');
    $aid = intval($_GET['ajax_rekap_anggota']);
    
    $stmt = $db->prepare("
        SELECT p.*, 
            (SELECT COUNT(*) FROM angsuran a WHERE a.pinjaman_id = p.id) as jml_angsuran
        FROM pinjaman p 
        WHERE p.anggota_id = ? 
        ORDER BY p.tanggal_pinjaman DESC
    ");
    $stmt->execute([$aid]);
    $loans = $stmt->fetchAll();
    
    $nameStmt = $db->prepare("SELECT nama, no_anggota FROM anggota WHERE id = ?");
    $nameStmt->execute([$aid]);
    $info = $nameStmt->fetch();
    
    $totalPinjam = 0; $totalSisa = 0;
    foreach ($loans as $l) {
        $totalPinjam += $l['jumlah_pinjaman'];
        $totalSisa += $l['sisa_pinjaman'];
    }
    
    echo json_encode(['nama' => $info['nama'], 'no_anggota' => $info['no_anggota'], 'loans' => $loans, 'total_pinjam' => $totalPinjam, 'total_sisa' => $totalSisa]);
    exit;
}

// Calculate summary statistics
$summaryStmt = $db->prepare("
    SELECT 
        SUM(p.jumlah_pinjaman) as total_pinjam,
        SUM(p.total_bayar - p.sisa_pinjaman) as total_bayar,
        SUM(p.sisa_pinjaman) as total_sisa,
        SUM(p.sisa_pokok) as total_sisa_pokok,
        SUM(p.sisa_jasa) as total_sisa_jasa
    FROM pinjaman p 
    JOIN anggota a ON p.anggota_id = a.id 
    $where
");
$summaryStmt->execute($params);
$summary = $summaryStmt->fetch();

$anggotaList = $db->query("SELECT id, no_anggota, nama FROM anggota WHERE status='aktif' ORDER BY nama")->fetchAll();
$jasaDefault = getSetting('jasa_pinjaman', 1);

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

<?php if ($detailData): ?>
<!-- Detail View -->
<div class="d-flex justify-content-between align-items-center mb-2">
    <a href="pinjaman.php" class="btn btn-outline"><i class="fas fa-arrow-left"></i> Kembali</a>
    <?php
    $telepon = $detailData['telepon'] ?? '';
    $waNumber = preg_replace('/[^0-9]/', '', $telepon);
    if (strlen($waNumber) > 0 && $waNumber[0] === '0') {
        $waNumber = '62' . substr($waNumber, 1);
    }
    if ($waNumber): 
        // Re-use logic for detailed WA message
        $p = $detailData; // map to p for copy-paste convenience
        $waMsg = "Halo *" . $p['nama'] . "*, Informasi Pinjaman Koperasi:\n";
        $waMsg .= "No Pinj: *" . $p['no_pinjaman'] . "*\n";
        $waMsg .= "Total Pinjam: *" . formatRupiah($p['jumlah_pinjaman']) . "*\n";
        $waMsg .= "Sisa Tagihan: *" . formatRupiah($p['sisa_pinjaman']) . "*\n";
        $waMsg .= "----------------------------\n";
        $waMsg .= "*JADWAL ANGSURAN:*\n\n";
        
        $sisaP = $p['jumlah_pinjaman'];
        $jasaP = $p['jumlah_pinjaman'] * ($p['jasa_persen'] / 100);
        $pokokP = ceil($p['jumlah_pinjaman'] / $p['lama_angsuran']);
        $tglM = new DateTime($p['tanggal_pinjaman']);
        $tglM->modify('+1 month');
        $nowDate = new DateTime();
        $nowDate->modify('first day of this month');
        $bulanIndoWA = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'];
        
        for ($i = 1; $i <= $p['lama_angsuran']; $i++) {
            $bP = ($i == $p['lama_angsuran']) ? $sisaP : min($pokokP, $sisaP);
            $bJ = $jasaP;
            $tot = $bP + $bJ;
            $sisaP = max(0, $sisaP - $bP);
            
            $stText = 'Belum';
            if ($i <= $p['ang_paid']) {
                $stText = 'Lunas ✅';
            } else {
                $checkD = clone $tglM;
                $checkD->modify('first day of this month');
                if ($checkD < $nowDate) $stText = 'Terlambat ⚠';
            }
            
            $blnName = $bulanIndoWA[(int)$tglM->format('n') - 1];
            $waMsg .= "$i. $blnName " . $tglM->format('Y') . ": *" . formatRupiah($tot) . "*\n";
            $waMsg .= "- Pokok: " . formatRupiah($bP) . ", Jasa: " . formatRupiah($bJ) . "\n";
            $waMsg .= "- Sisa: " . formatRupiah($sisaP) . " ($stText)\n\n";
            $tglM->modify('+1 month');
        }
        $waMsg .= "----------------------------\n";
        $waMsg .= "Mohon lakukan pembayaran tepat waktu. Terima kasih.";
    ?>
    <button type="button" 
            onclick='openWhatsappModal("<?= $waNumber ?>", <?= htmlspecialchars(json_encode($waMsg), ENT_QUOTES, 'UTF-8') ?>)'
            class="btn btn-success">
        <i class="fab fa-whatsapp"></i> Kirim WhatsApp
    </button>
    <?php endif; ?>
</div>

<div class="card mb-3">
    <div class="card-header">
        <h2><i class="fas fa-file-invoice-dollar" style="color: var(--warning-500); margin-right: 8px;"></i>Detail Pinjaman <?= htmlspecialchars($detailData['no_pinjaman']) ?></h2>
        <?php
        $badgeClass = match($detailData['status']) {
            'pending' => 'badge-warning',
            'disetujui' => 'badge-success',
            'ditolak' => 'badge-danger',
            'lunas' => 'badge-info',
            default => 'badge-primary'
        };
        ?>
        <span class="badge <?= $badgeClass ?>" style="font-size: 0.85rem; padding: 6px 14px;"><?= ucfirst($detailData['status']) ?></span>
    </div>
    <div class="card-body">
        <div class="detail-grid">
            <div class="detail-item">
                <div class="detail-label">Anggota</div>
                <div class="detail-value"><?= htmlspecialchars($detailData['nama']) ?></div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Jumlah Pinjaman</div>
                <div class="detail-value"><?= formatRupiah($detailData['jumlah_pinjaman']) ?></div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Jasa Pinjaman</div>
                <div class="detail-value"><?= $detailData['jasa_persen'] ?>% / bulan</div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Lama Angsuran</div>
                <div class="detail-value"><?= $detailData['lama_angsuran'] ?> bulan</div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Angsuran / Bulan</div>
                <div class="detail-value"><?= formatRupiah($detailData['jumlah_angsuran']) ?></div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Total Bayar</div>
                <div class="detail-value"><?= formatRupiah($detailData['total_bayar']) ?></div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Kekurangan Pokok</div>
                <div class="detail-value text-danger fw-bold"><?= formatRupiah($detailData['sisa_pokok'] ?? 0) ?></div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Kekurangan Jasa</div>
                <div class="detail-value text-warning fw-bold"><?= formatRupiah($detailData['sisa_jasa'] ?? 0) ?></div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Total Kekurangan</div>
                <div class="detail-value text-muted"><?= formatRupiah($detailData['sisa_pinjaman'] ?? 0) ?></div>
            </div>
            <div class="detail-item">
                <div class="detail-label">Tanggal Pinjaman</div>
                <div class="detail-value"><?= formatTanggal($detailData['tanggal_pinjaman']) ?></div>
            </div>
        </div>

        <?php if ($detailData['status'] === 'disetujui' || $detailData['status'] === 'lunas'): ?>
            <!-- Progress Bar -->
            <?php
            $totalPaid = $detailData['total_bayar'] - $detailData['sisa_pinjaman'];
            $progressPct = $detailData['total_bayar'] > 0 ? ($totalPaid / $detailData['total_bayar']) * 100 : 0;
            ?>
            <div class="mt-3">
                <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                    <span class="text-muted" style="font-size: 0.85rem;">Progress Pembayaran</span>
                    <span class="fw-bold" style="font-size: 0.85rem;"><?= number_format($progressPct, 1) ?>%</span>
                </div>
                <div class="progress-bar-container">
                    <div class="progress-bar <?= $progressPct >= 100 ? 'success' : '' ?>" style="width: <?= min(100, $progressPct) ?>%;"></div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php if ($detailData['status'] === 'pending'): ?>
    <div class="d-flex gap-1 mb-3">
        <form method="POST" style="display:inline;" onsubmit="return confirm('Setujui pinjaman ini?');">
            <input type="hidden" name="action" value="approve">
            <input type="hidden" name="id" value="<?= $detailData['id'] ?>">
            <button type="submit" class="btn btn-success"><i class="fas fa-check"></i> Setujui</button>
        </form>
        <form method="POST" style="display:inline;" onsubmit="return confirm('Tolak pinjaman ini?');">
            <input type="hidden" name="action" value="reject">
            <input type="hidden" name="id" value="<?= $detailData['id'] ?>">
            <button type="submit" class="btn btn-danger"><i class="fas fa-times"></i> Tolak</button>
        </form>
    </div>
<?php endif; ?>

<!-- Installments -->
<div class="card">
    <div class="card-header">
        <h2><i class="fas fa-list-ol" style="color: var(--primary-500); margin-right: 8px;"></i>Riwayat Angsuran</h2>
        <?php if ($detailData['status'] === 'disetujui'): ?>
            <button class="btn btn-primary btn-sm" onclick="openModal('bayarModal')">
                <i class="fas fa-plus"></i> Bayar Angsuran
            </button>
        <?php endif; ?>
    </div>
    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Tanggal Bayar</th>
                    <th class="text-right">Pokok</th>
                    <th class="text-right">jasa</th>
                    <th class="text-right">Total</th>
                    <th>Keterangan</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($angsuranList)): ?>
                    <tr><td colspan="6" class="text-center text-muted" style="padding: 30px;">Belum ada angsuran</td></tr>
                <?php else: ?>
                    <?php foreach ($angsuranList as $ang): ?>
                        <tr>
                            <td><span class="badge badge-primary">Ke-<?= $ang['angsuran_ke'] ?></span></td>
                            <td><?= formatTanggal($ang['tanggal_bayar']) ?></td>
                            <td class="text-right"><?= formatRupiah($ang['bayar_pokok'] ?? 0) ?></td>
                            <td class="text-right"><?= formatRupiah($ang['bayar_jasa'] ?? 0) ?></td>
                            <td class="text-right fw-bold text-success"><?= formatRupiah($ang['jumlah_bayar']) ?></td>
                            <td><?= htmlspecialchars($ang['keterangan'] ?? '-') ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Jadwal Angsuran Lengkap -->
<?php
// Generate full installment schedule
$jadwal = [];
$sisaPinjaman = $detailData['jumlah_pinjaman'];
$jasaPerBulan = $detailData['jumlah_pinjaman'] * ($detailData['jasa_persen'] / 100);
$pokokPerBulan = ceil($detailData['jumlah_pinjaman'] / $detailData['lama_angsuran']);
$angsuranPerBulan = $detailData['jumlah_angsuran'];

// First angsuran = next month after tanggal_pinjaman
$tglPinjaman = new DateTime($detailData['tanggal_pinjaman']);
$tglMulai = clone $tglPinjaman;
$tglMulai->modify('+1 month');

for ($i = 1; $i <= $detailData['lama_angsuran']; $i++) {
    $bayarPokok = ($i == $detailData['lama_angsuran']) ? $sisaPinjaman : min($pokokPerBulan, $sisaPinjaman);
    $bayarJasa = $jasaPerBulan;
    $totalBayar = $bayarPokok + $bayarJasa;
    $sisaPinjaman = max(0, $sisaPinjaman - $bayarPokok);
    
    $jadwal[] = [
        'ke' => $i,
        'bulan' => clone $tglMulai,
        'bayar_pokok' => $bayarPokok,
        'bayar_jasa' => $bayarJasa,
        'total' => $totalBayar,
        'sisa' => $sisaPinjaman,
    ];
    $tglMulai->modify('+1 month');
}

// Map paid installments by angsuran_ke
$paidMap = [];
foreach ($angsuranList as $ang) {
    $paidMap[$ang['angsuran_ke']] = $ang;
}
$bulanIndo2 = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'];
?>
<div class="card mt-3">
    <div class="card-header">
        <h2><i class="fas fa-calendar-alt" style="color: var(--success-500); margin-right: 8px;"></i>Jadwal Angsuran Lengkap</h2>
        <span style="font-size:0.8rem;color:var(--gray-500);">Mulai: <?= $bulanIndo2[(int)$detailData['tanggal_pinjaman'] ? (int)date('n', strtotime($detailData['tanggal_pinjaman'])) - 1 : 0] ?> → Angsuran 1 mulai <?= $bulanIndo2[$jadwal[0]['bulan']->format('n')-1] . ' ' . $jadwal[0]['bulan']->format('Y') ?></span>
    </div>
    <div class="table-responsive">
        <table class="data-table" style="font-size:0.85rem;">
            <thead>
                <tr>
                    <th style="text-align:center;width:50px;">Ke</th>
                    <th>Bulan</th>
                    <th class="text-right">Pokok</th>
                    <th class="text-right">Jasa</th>
                    <th class="text-right">Total Bayar</th>
                    <th class="text-right">Sisa Pinjaman</th>
                    <th style="text-align:center;">Status</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($jadwal as $j): ?>
                <?php
                    $isPaid = isset($paidMap[$j['ke']]);
                    $now = new DateTime();
                    $isOverdue = !$isPaid && $j['bulan'] < $now;
                    $rowStyle = $isPaid ? 'background:rgba(34,197,94,0.07);' : ($isOverdue ? 'background:rgba(239,68,68,0.06);' : '');
                ?>
                <tr style="<?= $rowStyle ?>">
                    <td style="text-align:center;">
                        <span class="badge <?= $isPaid ? 'badge-success' : ($isOverdue ? 'badge-danger' : 'badge-primary') ?>"><?= $j['ke'] ?></span>
                    </td>
                    <td style="font-weight:600;"><?= $bulanIndo2[$j['bulan']->format('n')-1] . ' ' . $j['bulan']->format('Y') ?></td>
                    <td class="text-right"><?= formatRupiah($j['bayar_pokok']) ?></td>
                    <td class="text-right" style="color:var(--warning-600);"><?= formatRupiah($j['bayar_jasa']) ?></td>
                    <td class="text-right fw-bold"><?= formatRupiah($j['total']) ?></td>
                    <td class="text-right" style="color:var(--danger-600);font-weight:700;"><?= formatRupiah($j['sisa']) ?></td>
                    <td style="text-align:center;">
                        <?php if ($isPaid): ?>
                            <span style="color:var(--success-600);font-size:0.8rem;font-weight:700;"><i class="fas fa-check-circle"></i> Lunas</span>
                        <?php elseif ($isOverdue): ?>
                            <span style="color:var(--danger-600);font-size:0.8rem;font-weight:700;"><i class="fas fa-exclamation-circle"></i> Terlambat</span>
                        <?php else: ?>
                            <span style="color:var(--gray-400);font-size:0.8rem;"><i class="fas fa-clock"></i> Belum</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr style="background:var(--gray-50);font-weight:700;">
                    <td colspan="2" style="text-align:right;font-size:0.8rem;color:var(--gray-600);">TOTAL</td>
                    <td class="text-right" style="color:var(--primary-600);"><?= formatRupiah($detailData['jumlah_pinjaman']) ?></td>
                    <td class="text-right" style="color:var(--warning-600);"><?= formatRupiah($jasaPerBulan * $detailData['lama_angsuran']) ?></td>
                    <td class="text-right" style="color:var(--success-600);"><?= formatRupiah($detailData['total_bayar']) ?></td>
                    <td class="text-right">-</td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

<!-- Bayar Modal -->
<?php if ($detailData['status'] === 'disetujui'): ?>
<div class="modal" id="bayarModal">
    <div class="modal-header">
        <h3><i class="fas fa-money-bill-wave" style="color: var(--success-500); margin-right: 8px;"></i>Bayar Angsuran</h3>
        <button class="modal-close" onclick="closeModal('bayarModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="bayar">
        <input type="hidden" name="pinjaman_id" value="<?= $detailData['id'] ?>">
        <div class="modal-body">
            <div class="alert alert-info" style="font-size: 0.85rem;">
                <i class="fas fa-info-circle"></i>
                Angsuran: <strong><?= formatRupiah($detailData['jumlah_angsuran']) ?></strong><br>
                Kekurangan Pokok: <strong class="text-danger"><?= formatRupiah($detailData['sisa_pokok'] ?? 0) ?></strong> · 
                Kekurangan Jasa: <strong class="text-warning"><?= formatRupiah($detailData['sisa_jasa'] ?? 0) ?></strong>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Jumlah Bayar (Rp) <span class="required">*</span></label>
                    <input type="text" name="jumlah_bayar" class="form-control" required 
                           value="<?= number_format($detailData['jumlah_angsuran'], 0, '', '.') ?>"
                           oninput="formatCurrencyInput(this)">
                </div>
                <div class="form-group">
                    <label>Tanggal Bayar <span class="required">*</span></label>
                    <input type="date" name="tanggal_bayar" class="form-control" required value="<?= date('Y-m-d') ?>">
                </div>
            </div>
            <div class="form-group">
                <label>Keterangan</label>
                <input type="text" name="keterangan" class="form-control" placeholder="Catatan (opsional)">
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('bayarModal')">Batal</button>
            <button type="submit" class="btn btn-success"><i class="fas fa-save"></i> Bayar</button>
        </div>
    </form>
</div>
<?php endif; ?>

<?php else: ?>
<!-- List View -->
<div class="card">
    <div class="card-header">
        <div class="toolbar" style="width: 100%;">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" placeholder="Cari pinjaman..." value="<?= htmlspecialchars($search) ?>"
                       onkeydown="if(event.key==='Enter') { window.location='pinjaman.php?search='+this.value; }">
            </div>
            <div class="filter-group">
                <select onchange="window.location='pinjaman.php?status='+this.value+'&search=<?= urlencode($search) ?>&bulan=<?= urlencode($bulanFilter) ?>'">
                    <option value="">Semua Status</option>
                    <option value="pending" <?= $statusFilter === 'pending' ? 'selected' : '' ?>>Pending</option>
                    <option value="disetujui" <?= $statusFilter === 'disetujui' ? 'selected' : '' ?>>Disetujui</option>
                    <option value="lunas" <?= $statusFilter === 'lunas' ? 'selected' : '' ?>>Lunas</option>
                    <option value="ditolak" <?= $statusFilter === 'ditolak' ? 'selected' : '' ?>>Ditolak</option>
                </select>
                <select onchange="window.location='pinjaman.php?bulan='+this.value+'&search=<?= urlencode($search) ?>&status=<?= urlencode($statusFilter) ?>'">
                    <option value="">Semua Bulan</option>
                    <?php 
                    $currentYear = date('Y');
                    $currentMonth = date('m');
                    for ($y = $currentYear; $y >= 2020; $y--) {
                        $startMonth = ($y === $currentYear) ? $currentMonth : 12;
                        for ($m = $startMonth; $m >= 1; $m--) {
                            $monthValue = sprintf('%04d-%02d', $y, $m);
                            $monthLabel = formatBulan($monthValue);
                            $selected = ($bulanFilter === $monthValue) ? 'selected' : '';
                    ?>
                        <option value="<?= $monthValue ?>" <?= $selected ?>><?= $monthLabel ?></option>
                    <?php
                        }
                    }
                    ?>
                </select>
            </div>
            <div style="margin-left: auto; display: flex; gap: 10px;">
                <form id="bulkDeleteForm" method="POST" style="display:none;" onsubmit="return submitBulkDelete(event);">
                    <input type="hidden" name="action" value="bulk_delete">
                    <input type="hidden" id="bulkIds" name="ids" value="">
                    <button type="submit" class="btn" style="background:var(--danger-500); color:white; border-color:var(--danger-600);">
                        <i class="fas fa-trash-alt"></i> Hapus Terpilih (<span id="selectedCount">0</span>)
                    </button>
                </form>
                <a href="imports/import_pinjaman_excel.php" class="btn btn-outline">
                    <i class="fas fa-file-import"></i> Import
                </a>
                <button class="btn btn-primary" onclick="openModal('addPinjamanModal')">
                    <i class="fas fa-plus"></i> Ajukan Pinjaman
                </button>
            </div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th style="width: 40px; text-align: center;"><input type="checkbox" onchange="toggleAllCheckboxes(this)"></th>
                    <th style="width: 30px; text-align: center;">No</th>
                    <th>PINJAMAN & ANGGOTA</th>
                    <th style="width: 130px; text-align: right;">JUMLAH / DIBAYAR</th>
                    <th style="width: 100px; text-align: right;">ANGSURAN</th>
                    <th style="width: 130px; text-align: right;">SISA (POKOK/JASA)</th>
                    <th style="width: 80px; text-align: center;">STATUS</th>
                    <th style="width: 110px; text-align: right;">REKAP SISA</th>
                    <th style="width: 130px; text-align: center;">AKSI</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($pinjamanList)): ?>
                    <tr><td colspan="9" class="text-center text-muted" style="padding: 40px;">
                        <i class="fas fa-hand-holding-usd" style="font-size: 2rem; display: block; margin-bottom: 10px; color: var(--gray-300);"></i>
                        Tidak ada data pinjaman
                    </td></tr>
                <?php else: ?>
                    <?php $nomor = 1; foreach ($pinjamanList as $p): ?>
                        <tr>
                            <td style="text-align: center;">
                                <input type="checkbox" class="rowCheckbox" value="<?=$p['id']?>" onchange="updateBulkDeleteBtn()">
                            </td>
                            <td style="text-align: center; font-weight: bold;"><?=$nomor++?></td>
                            <td>
                                <div style="font-weight: 800; color: var(--primary-600); font-size: 0.8rem; margin-bottom: 2px;">#<?= htmlspecialchars($p['no_pinjaman']) ?></div>
                                <div class="fw-bold"><?= htmlspecialchars($p['nama']) ?></div>
                                <div style="color: var(--gray-400); font-size: 0.75rem;"><?= htmlspecialchars($p['no_anggota'] ?? '') ?></div>
                            </td>
                            <td style="text-align: right;">
                                <div style="font-weight: 700; font-size: 0.95rem;"><?= formatRupiah($p['jumlah_pinjaman']) ?></div>
                                <div style="color: var(--success-600); font-size: 0.75rem; font-weight: 600;">Paid: <?= formatRupiah($p['total_bayar'] - $p['sisa_pinjaman']) ?></div>
                            </td>
                            <td style="text-align: right; font-size: 0.85rem;">
                                <strong><?= formatRupiah($p['jumlah_angsuran']) ?></strong><span style="color:var(--gray-400);">/bln</span>
                            </td>
                            <td style="text-align: right;">
                                <div style="color: var(--danger-600); font-size: 0.85rem; font-weight: 700;">P: <?= formatRupiah($p['sisa_pokok'] ?? 0) ?></div>
                                <div style="color: var(--warning-600); font-size: 0.75rem; font-weight: 600;">J: <?= formatRupiah($p['sisa_jasa'] ?? 0) ?></div>
                            </td>
                            <td style="text-align: center;">
                                <?php
                                $badgeClass = match($p['status']) {
                                    'pending' => 'badge-warning',
                                    'disetujui' => 'badge-success',
                                    'ditolak' => 'badge-danger',
                                    'lunas' => 'badge-info',
                                    default => 'badge-primary'
                                };
                                ?>
                                <span class="badge <?= $badgeClass ?>"><?= ucfirst($p['status']) ?></span>
                            </td>
                            <td>
                                <?php
                                $totalSisaStmt = $db->prepare("SELECT SUM(sisa_pinjaman) FROM pinjaman WHERE anggota_id = ? AND status IN ('disetujui', 'pending')");
                                $totalSisaStmt->execute([$p['anggota_id']]);
                                $totalSisaMember = $totalSisaStmt->fetchColumn() ?: 0;
                                ?>
                                <a href="javascript:void(0)" onclick="showRekapPinjaman(<?= $p['anggota_id'] ?>)" 
                                   style="color: var(--danger-600); font-weight: 700; text-decoration: none; cursor: pointer; white-space: nowrap;"
                                   title="Klik untuk lihat rekap semua pinjaman anggota ini">
                                    <?= formatRupiah($totalSisaMember) ?>
                                </a>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <?php
                                    // WhatsApp button
                                    $telepon = $p['telepon'] ?? '';
                                    $waNumber = preg_replace('/[^0-9]/', '', $telepon);
                                    if (strlen($waNumber) > 0 && $waNumber[0] === '0') {
                                        $waNumber = '62' . substr($waNumber, 1);
                                    }
                                    // Build WA message
                                     $waMsg = "Halo *" . $p['nama'] . "*, Informasi Pinjaman Koperasi:\n";
                                     $waMsg .= "No Pinj: *" . $p['no_pinjaman'] . "*\n";
                                     $waMsg .= "Total Pinjam: *" . formatRupiah($p['jumlah_pinjaman']) . "*\n";
                                     $waMsg .= "Sisa Tagihan: *" . formatRupiah($p['sisa_pinjaman']) . "*\n";
                                     $waMsg .= "----------------------------\n";
                                     $waMsg .= "*JADWAL ANGSURAN:*\n\n";
                                     
                                     $sisaP = $p['jumlah_pinjaman'];
                                     $jasaP = $p['jumlah_pinjaman'] * ($p['jasa_persen'] / 100);
                                     $pokokP = ceil($p['jumlah_pinjaman'] / $p['lama_angsuran']);
                                     $tglM = new DateTime($p['tanggal_pinjaman']);
                                     $tglM->modify('+1 month');
                                     $nowDate = new DateTime();
                                     $nowDate->modify('first day of this month');
                                     $bulanIndoWA = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'];
                                     
                                     for ($i = 1; $i <= $p['lama_angsuran']; $i++) {
                                         $bP = ($i == $p['lama_angsuran']) ? $sisaP : min($pokokP, $sisaP);
                                         $bJ = $jasaP;
                                         $tot = $bP + $bJ;
                                         $sisaP = max(0, $sisaP - $bP);
                                         
                                         $stText = 'Belum';
                                         if ($i <= $p['ang_paid']) {
                                             $stText = 'Lunas ✅';
                                         } else {
                                             $checkD = clone $tglM;
                                             $checkD->modify('first day of this month');
                                             if ($checkD < $nowDate) $stText = 'Terlambat ⚠';
                                         }
                                         
                                         $blnName = $bulanIndoWA[(int)$tglM->format('n') - 1];
                                         $waMsg .= "$i. $blnName " . $tglM->format('Y') . ": *" . formatRupiah($tot) . "*\n";
                                         $waMsg .= "- Pokok: " . formatRupiah($bP) . ", Jasa: " . formatRupiah($bJ) . "\n";
                                         $waMsg .= "- Sisa: " . formatRupiah($sisaP) . " ($stText)\n\n";
                                         $tglM->modify('+1 month');
                                     }
                                     $waMsg .= "----------------------------\n";
                                     $waMsg .= "Terimakasih Sudah Bekerja Sama dengan Koperasi Tsuroyya, Semoga Berkah.";
                                    if ($waNumber): ?>
                                    <button type="button" 
                                            onclick='openWhatsappModal("<?= $waNumber ?>", <?= htmlspecialchars(json_encode($waMsg), ENT_QUOTES, 'UTF-8') ?>)'
                                            class="btn btn-icon btn-outline" 
                                            title="Kirim WhatsApp" 
                                            style="background:#25D366;border-color:#25D366;">
                                        <i class="fab fa-whatsapp" style="color:white;"></i>
                                    </button>
                                    <?php endif; ?>
                                    <a href="cetak_surat_pinjaman.php?id=<?= $p['id'] ?>" target="_blank" class="btn btn-icon btn-outline" title="Surat Pernyataan">
                                        <i class="fas fa-file-contract" style="color: var(--primary-500);"></i>
                                    </a>
                                    <a href="pinjaman.php?detail=<?= $p['id'] ?>" class="btn btn-icon btn-outline" title="Lihat">
                                        <i class="fas fa-eye" style="color: var(--info-500);"></i>
                                    </a>
                                    <?php if ($p['status'] === 'pending' || $p['status'] === 'disetujui'): ?>
                                        <a href="pinjaman.php?edit=<?= $p['id'] ?>" class="btn btn-icon btn-outline" title="Edit">
                                            <i class="fas fa-pen" style="color: var(--warning-500);"></i>
                                        </a>
                                    <?php endif; ?>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus pinjaman ini?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                        <button type="submit" class="btn btn-icon btn-outline" title="Hapus">
                                            <i class="fas fa-trash" style="color: var(--danger-500);"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Summary Section -->
    <div class="summary-section" style="background: linear-gradient(135deg, rgba(99, 102, 241, 0.05) 0%, rgba(59, 130, 246, 0.05) 100%); padding: 16px; border-radius: 16px; margin-top: 20px; border: 1px solid rgba(99, 102, 241, 0.15);">
        <div class="summary-title" style="font-size: 0.8rem; font-weight: 700; color: var(--gray-600); text-transform: uppercase; letter-spacing: 1px; margin-bottom: 12px;">
            <i class="fas fa-chart-line" style="margin-right: 8px; color: var(--primary-500);"></i>Ringkasan Data Pinjaman
        </div>
        <div class="summary-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 14px;">
            <div class="summary-item" style="background: white; padding: 12px; border-radius: 12px; border-left: 4px solid var(--primary-600);">
                <div class="summary-label" style="font-size: 0.75rem; font-weight: 600; color: var(--gray-600); margin-bottom: 6px;">Total Dipinjam</div>
                <div class="summary-value" style="font-size: 1.2rem; font-weight: 900; color: var(--primary-600);"><?= formatRupiah($summary['total_pinjam'] ?? 0) ?></div>
                <div class="summary-sublabel" style="font-size: 0.7rem; color: var(--gray-400); margin-top: 3px;"><?= $totalRows ?> pinjaman</div>
            </div>
            
            <div class="summary-item" style="background: white; padding: 12px; border-radius: 12px; border-left: 4px solid var(--success-600);">
                <div class="summary-label" style="font-size: 0.75rem; font-weight: 600; color: var(--gray-600); margin-bottom: 6px;">Sudah Terbayar</div>
                <div class="summary-value" style="font-size: 1.2rem; font-weight: 900; color: var(--success-600);"><?= formatRupiah($summary['total_bayar'] ?? 0) ?></div>
                <div class="summary-sublabel" style="font-size: 0.7rem; color: var(--gray-400); margin-top: 3px;"><strong><?= $summary['total_pinjam'] > 0 ? round(($summary['total_bayar'] / $summary['total_pinjam']) * 100, 2) : 0 ?>%</strong></div>
            </div>
            
            <div class="summary-item" style="background: white; padding: 12px; border-radius: 12px; border-left: 4px solid var(--danger-600);">
                <div class="summary-label" style="font-size: 0.75rem; font-weight: 600; color: var(--gray-600); margin-bottom: 6px;">Sisa Utang</div>
                <div class="summary-value" style="font-size: 1.2rem; font-weight: 900; color: var(--danger-600);"><?= formatRupiah($summary['total_sisa'] ?? 0) ?></div>
                <div class="summary-sublabel" style="font-size: 0.7rem; color: var(--gray-400); margin-top: 3px;">Pokok: <strong><?= formatRupiah($summary['total_sisa_pokok'] ?? 0) ?></strong></div>
            </div>
        </div>
    </div>

    <?php if ($totalPages > 1): ?>
        <div class="card-footer">
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="pinjaman.php?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($statusFilter) ?>&bulan=<?= urlencode($bulanFilter) ?>"><i class="fas fa-chevron-left"></i></a>
                <?php endif; ?>
                <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                    <a href="pinjaman.php?page=<?= $p ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($statusFilter) ?>&bulan=<?= urlencode($bulanFilter) ?>" 
                       class="<?= $p === $page ? 'active' : '' ?>"><?= $p ?></a>
                <?php endfor; ?>
                <?php if ($page < $totalPages): ?>
                    <a href="pinjaman.php?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($statusFilter) ?>&bulan=<?= urlencode($bulanFilter) ?>"><i class="fas fa-chevron-right"></i></a>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Add Pinjaman Modal -->
<div class="modal modal-lg" id="addPinjamanModal">
    <div class="modal-header">
        <h3><i class="fas fa-hand-holding-usd" style="color: var(--warning-500); margin-right: 8px;"></i>Ajukan Pinjaman Baru</h3>
        <button class="modal-close" onclick="closeModal('addPinjamanModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST" onsubmit="return validateSearchableDropdown(this)">
        <input type="hidden" name="action" value="add">
        <div class="modal-body">
            <div class="form-group">
                <label>Anggota <span class="required">*</span></label>
                <div class="searchable-dropdown" id="memberSearchContainer">
                    <input type="text" class="form-control" name="anggota_search" id="member_search_input" 
                           placeholder="Cari Nama atau No. Anggota..." autocomplete="off"
                           oninput="filterMemberDropdown(this)" onfocus="filterMemberDropdown(this)">
                    <input type="hidden" name="anggota_id" id="member_id_hidden">
                    <div class="dropdown-results" id="member_results_list">
                        <?php foreach ($anggotaList as $a): ?>
                            <div class="dropdown-item" 
                                 data-id="<?= $a['id'] ?>" 
                                 data-text="<?= htmlspecialchars($a['no_anggota'] . ' - ' . $a['nama']) ?>">
                                <i class="fas fa-user-circle"></i>
                                <span><?= htmlspecialchars($a['no_anggota'] . ' - ' . $a['nama']) ?></span>
                            </div>
                        <?php endforeach; ?>
                        <div class="dropdown-item no-results" style="display: none !important;">
                            <i class="fas fa-exclamation-circle"></i>
                            Nama tidak terdaftar
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-row-3">
                <div class="form-group">
                    <label>Jumlah Pinjaman (Rp) <span class="required">*</span></label>
                    <input type="text" name="jumlah_pinjaman" id="jumlah_pinjaman" class="form-control" required 
                           placeholder="0" oninput="formatCurrencyInput(this); hitungAngsuran();">
                </div>
                <div class="form-group">
                    <label>jasa (% / bulan) <span class="required">*</span></label>
                    <input type="number" name="jasa_persen" id="jasa_persen" class="form-control" required 
                           value="<?= $jasaDefault ?>" step="0.1" min="0" onchange="hitungAngsuran()">
                </div>
                <div class="form-group">
                    <label>Lama (bulan) <span class="required">*</span></label>
                    <input type="number" name="lama_angsuran" id="lama_angsuran" class="form-control" required 
                           min="1" max="60" placeholder="12" onchange="hitungAngsuran()">
                </div>
            </div>

            <!-- Calculator display -->
            <div class="detail-grid mt-2 mb-2">
                <div class="detail-item">
                    <div class="detail-label">Pokok / Bulan</div>
                    <div class="detail-value" id="pokok_per_bulan_display">Rp 0</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Jasa / Bulan</div>
                    <div class="detail-value" id="jasa_per_bulan_display">Rp 0</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Total Angsuran</div>
                    <div class="detail-value" id="jumlah_angsuran_display">Rp 0</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Total Bayar</div>
                    <div class="detail-value" id="total_bayar_display">Rp 0</div>
                </div>
            </div>

            <!-- Jadwal Angsuran Preview -->
            <div id="jadwal_preview_container" style="display:none;margin-top:10px;">
                <div style="font-size:0.75rem;font-weight:700;color:var(--gray-600);text-transform:uppercase;letter-spacing:1px;margin-bottom:8px;">
                    <i class="fas fa-calendar-alt" style="color:var(--primary-500);margin-right:6px;"></i>Jadwal Angsuran
                    <span id="jadwal_mulai_label" style="color:var(--primary-500);"></span>
                </div>
                <div style="max-height:200px;overflow-y:auto;border-radius:10px;border:1px solid var(--gray-100);">
                    <table style="width:100%;border-collapse:collapse;font-size:0.78rem;">
                        <thead>
                            <tr style="background:var(--gray-50);">
                                <th style="padding:6px 10px;text-align:center;font-weight:700;color:var(--gray-600);">Ke</th>
                                <th style="padding:6px 10px;font-weight:700;color:var(--gray-600);">Bulan</th>
                                <th style="padding:6px 10px;text-align:right;font-weight:700;color:var(--gray-600);">Pokok</th>
                                <th style="padding:6px 10px;text-align:right;font-weight:700;color:var(--warning-600);">Jasa</th>
                                <th style="padding:6px 10px;text-align:right;font-weight:700;color:var(--success-600);">Total</th>
                                <th style="padding:6px 10px;text-align:right;font-weight:700;color:var(--danger-600);">Sisa</th>
                            </tr>
                        </thead>
                        <tbody id="jadwal_preview_body"></tbody>
                    </table>
                </div>
            </div>

            <div class="form-group">
                <label>Tanggal Pinjaman <span class="required">*</span></label>
                <input type="date" name="tanggal_pinjaman" class="form-control" required value="<?= date('Y-m-d') ?>" onchange="hitungAngsuran()">
            </div>
            <div class="form-group">
                <label>Catatan</label>
                <textarea name="catatan" class="form-control" rows="2" placeholder="Catatan atau tujuan pinjaman (opsional)"></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('addPinjamanModal')">Batal</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-paper-plane"></i> Ajukan</button>
        </div>
    </form>
</div>
<?php endif; ?>

<!-- Edit Pinjaman Modal -->
<?php if ($editData): ?>
<script>document.addEventListener('DOMContentLoaded', () => openModal('editPinjamanModal'));</script>
<div class="modal modal-lg" id="editPinjamanModal">
    <div class="modal-header">
        <h3><i class="fas fa-pen" style="color: var(--warning-500); margin-right: 8px;"></i>Edit Pinjaman <?= htmlspecialchars($editData['no_pinjaman']) ?></h3>
        <button class="modal-close" onclick="window.location='pinjaman.php'"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="edit">
        <input type="hidden" name="id" value="<?= $editData['id'] ?>">
        <div class="modal-body">
            <div class="form-group">
                <label>Anggota <span class="required">*</span></label>
                <select name="anggota_id" class="form-control" required disabled>
                    <?php foreach ($anggotaList as $a): ?>
                        <option value="<?= $a['id'] ?>" <?= $editData['anggota_id'] == $a['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($a['no_anggota'] . ' - ' . $a['nama']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <input type="hidden" name="anggota_id" value="<?= $editData['anggota_id'] ?>">
            </div>
            <div class="form-row-3">
                <div class="form-group">
                    <label>Jumlah Pinjaman (Rp) <span class="required">*</span></label>
                    <input type="text" name="jumlah_pinjaman" id="edit_jumlah_pinjaman" class="form-control" required 
                           value="<?= number_format($editData['jumlah_pinjaman'], 0, '', '.') ?>"
                           oninput="formatCurrencyInput(this); hitungAngsuranEdit();">
                </div>
                <div class="form-group">
                    <label>jasa (% / bulan) <span class="required">*</span></label>
                    <input type="number" name="jasa_persen" id="edit_jasa_persen" class="form-control" required 
                           value="<?= $editData['jasa_persen'] ?>" step="0.1" min="0" onchange="hitungAngsuranEdit()">
                </div>
                <div class="form-group">
                    <label>Lama (bulan) <span class="required">*</span></label>
                    <input type="number" name="lama_angsuran" id="edit_lama_angsuran" class="form-control" required 
                           value="<?= $editData['lama_angsuran'] ?>" min="1" max="60" onchange="hitungAngsuranEdit()">
                </div>
            </div>

            <div class="detail-grid mt-2 mb-2">
                <div class="detail-item">
                    <div class="detail-label">Pokok / Bulan</div>
                    <div class="detail-value" id="edit_pokok_per_bulan_display">Rp 0</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Jasa / Bulan</div>
                    <div class="detail-value" id="edit_jasa_per_bulan_display">Rp 0</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Total Angsuran</div>
                    <div class="detail-value" id="edit_jumlah_angsuran_display"><?= formatRupiah($editData['jumlah_angsuran']) ?></div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">Total Bayar</div>
                    <div class="detail-value" id="edit_total_bayar_display"><?= formatRupiah($editData['total_bayar']) ?></div>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Kekurangan Pokok Saat Ini (Rp)</label>
                    <input type="text" name="sisa_pokok" class="form-control" 
                           value="<?= number_format($editData['sisa_pokok'] ?? 0, 0, '', '.') ?>"
                           oninput="formatCurrencyInput(this)">
                </div>
                <div class="form-group">
                    <label>Kekurangan Jasa Saat Ini (Rp)</label>
                    <input type="text" name="sisa_jasa" class="form-control" 
                           value="<?= number_format($editData['sisa_jasa'] ?? 0, 0, '', '.') ?>"
                           oninput="formatCurrencyInput(this)">
                </div>
            </div>

            <div class="form-group">
                <label>Tanggal Pinjaman <span class="required">*</span></label>
                <input type="date" name="tanggal_pinjaman" class="form-control" required value="<?= $editData['tanggal_pinjaman'] ?>">
            </div>
            <div class="form-group">
                <label>Catatan</label>
                <textarea name="catatan" class="form-control" rows="2"><?= htmlspecialchars($editData['catatan']) ?></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="window.location='pinjaman.php'">Batal</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Perbarui</button>
        </div>
    </form>
</div>

<?php endif; ?>

<style>
/* Searchable Dropdown Premium Styles */
.searchable-dropdown {
    position: relative;
    width: 100%;
}
.searchable-dropdown .dropdown-results {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    z-index: 9999; /* Extremely high to stay on top */
    background: #ffffff !important;
    border: 1px solid var(--gray-200);
    border-radius: var(--radius-md);
    box-shadow: 0 12px 30px rgba(0,0,0,0.15);
    max-height: 280px;
    overflow-y: auto;
    display: none !important; /* Force hide */
    margin-top: 5px;
}
.searchable-dropdown .dropdown-results.active {
    display: block !important; /* Force show when active */
}
.searchable-dropdown .dropdown-item {
    padding: 12px 16px;
    cursor: pointer;
    font-size: 0.9rem;
    transition: all 0.2s;
    display: none !important; /* Force hide items */
    align-items: center;
    gap: 10px;
    color: var(--gray-700);
}
.searchable-dropdown .dropdown-item i {
    color: var(--gray-400);
    font-size: 1.1rem;
}
.searchable-dropdown .dropdown-item:hover {
    background: var(--primary-50);
    color: var(--primary-700);
}
.searchable-dropdown .dropdown-item:hover i {
    color: var(--primary-500);
}
.searchable-dropdown .dropdown-item.no-results {
    flex-direction: column;
    padding: 24px;
    color: var(--danger-500);
    pointer-events: none;
}
.searchable-dropdown .dropdown-item.no-results i {
    font-size: 1.8rem;
    margin-bottom: 8px;
    color: var(--danger-500);
}
</style>

<script>
// Core function to filter the member dropdown
function filterMemberDropdown(input) {
    const filter = input.value.toLowerCase().trim();
    const container = input.closest('.searchable-dropdown');
    const dropdown = container.querySelector('.dropdown-results');
    const items = dropdown.querySelectorAll('.dropdown-item:not(.no-results)');
    const noResults = dropdown.querySelector('.no-results');
    const hidden = container.querySelector('input[type="hidden"]');
    
    // Reset hidden ID if text changes (must select again)
    hidden.value = '';
    input.style.borderColor = '';
    input.style.backgroundColor = '';

    if (filter.length > 0) {
        dropdown.classList.add('active');
        let hasResults = false;
        
        items.forEach(item => {
            const text = item.getAttribute('data-text').toLowerCase();
            if (text.includes(filter)) {
                item.style.setProperty('display', 'flex', 'important');
                hasResults = true;
            } else {
                item.style.setProperty('display', 'none', 'important');
            }
        });
        
        if (noResults) {
            noResults.style.setProperty('display', hasResults ? 'none' : 'flex', 'important');
        }
    } else {
        dropdown.classList.remove('active');
    }
}

// Global mousedown listener for selection (works before input loses focus)
document.addEventListener('mousedown', function(e) {
    const item = e.target.closest('.dropdown-item:not(.no-results)');
    
    if (item) {
        const container = item.closest('.searchable-dropdown');
        const input = container.querySelector('input[type="text"]');
        const hidden = container.querySelector('input[type="hidden"]');
        
        // Populate values
        input.value = item.getAttribute('data-text').trim();
        hidden.value = item.getAttribute('data-id');
        
        // Visual Success Feedback
        input.style.setProperty('border-color', 'var(--success-500)', 'important');
        input.style.setProperty('background-color', 'var(--success-50)', 'important');
        
        // Hide Dropdown
        container.querySelector('.dropdown-results').classList.remove('active');
        
        // Cleanup errors
        const error = input.parentNode.querySelector('.field-error');
        if (error) error.remove();
        
        e.preventDefault(); // Prevent focus loss from input
        return;
    }

    // Close dropdowns if clicking elsewhere
    if (!e.target.closest('.searchable-dropdown')) {
        document.querySelectorAll('.dropdown-results.active').forEach(d => d.classList.remove('active'));
    }
});

// Helper for strict matching on submit
function finalValidateMember(input) {
    const container = input.closest('.searchable-dropdown');
    const hidden = container.querySelector('input[type="hidden"]');
    if (hidden.value) return true;

    const filter = input.value.toLowerCase().trim();
    if (!filter) return false;

    const items = container.querySelectorAll('.dropdown-item:not(.no-results)');
    for (const item of items) {
        const fullText = item.getAttribute('data-text').toLowerCase().trim();
        const parts = fullText.split(' - ');
        const nameOnly = parts.length > 1 ? parts[1].trim() : parts[0].trim();

        if (fullText === filter || nameOnly === filter) {
            hidden.value = item.getAttribute('data-id');
            input.value = item.getAttribute('data-text');
            return true;
        }
    }
    return false;
}

// Form submit helper
function validateSearchableDropdown(form) {
    const searchInput = form.querySelector('#member_search_input');
    if (searchInput) {
        finalValidateMember(searchInput);
    }
    
    const hiddenId = form.querySelector('#member_id_hidden');
    if (!hiddenId || !hiddenId.value) {
        alert('Mohon pilih Nama Anggota dari daftar yang tersedia.');
        if (searchInput) searchInput.focus();
        return false;
    }
    return true;
}

function hitungAngsuranEdit() {
    const modal = document.getElementById('editPinjamanModal');
    if (!modal) return;

    const jumlahInput = document.getElementById('edit_jumlah_pinjaman').value.replace(/\./g, '');
    const jasaInput = document.getElementById('edit_jasa_persen').value;
    const lamaInput = document.getElementById('edit_lama_angsuran').value;
    
    if (jumlahInput && jasaInput && lamaInput) {
        const jumlah = parseFloat(jumlahInput);
        const jasa = parseFloat(jasaInput);
        const lama = parseInt(lamaInput);
        
        const jasaPerBulan = jumlah * (jasa / 100);
        const pokokPerBulan = Math.ceil(jumlah / lama);
        const totaljasa = jasaPerBulan * lama;
        const totalBayar = jumlah + totaljasa;
        const angsuran = Math.ceil(totalBayar / lama);
        
        const formatter = new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 });
        
        document.getElementById('edit_pokok_per_bulan_display').innerText = formatter.format(pokokPerBulan);
        document.getElementById('edit_jasa_per_bulan_display').innerText = formatter.format(jasaPerBulan);
        document.getElementById('edit_jumlah_angsuran_display').innerText = formatter.format(angsuran);
        document.getElementById('edit_total_bayar_display').innerText = formatter.format(totalBayar);
    }
}

// Generate jadwal angsuran preview in Add modal
function hitungAngsuran() {
    const jumlahInput = document.getElementById('jumlah_pinjaman');
    const jasaInput  = document.getElementById('jasa_persen');
    const lamaInput  = document.getElementById('lama_angsuran');
    const tglInput   = document.querySelector('#addPinjamanModal input[name="tanggal_pinjaman"]');
    if (!jumlahInput || !jasaInput || !lamaInput) return;

    const jumlahRaw = jumlahInput.value.replace(/\./g, '');
    const jasaVal  = jasaInput.value;
    const lamaVal  = lamaInput.value;
    if (!jumlahRaw || !jasaVal || !lamaVal) return;

    const jumlah = parseFloat(jumlahRaw);
    const jasa   = parseFloat(jasaVal);
    const lama   = parseInt(lamaVal);
    if (!jumlah || !lama) return;

    const jasaPerBulan   = jumlah * (jasa / 100);
    const pokokPerBulan  = Math.ceil(jumlah / lama);
    const totaljasa      = jasaPerBulan * lama;
    const totalBayar     = jumlah + totaljasa;
    const angsuran       = Math.ceil(totalBayar / lama);

    const fmt = new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 });

    document.getElementById('pokok_per_bulan_display').innerText = fmt.format(pokokPerBulan);
    document.getElementById('jasa_per_bulan_display').innerText  = fmt.format(jasaPerBulan);
    document.getElementById('jumlah_angsuran_display').innerText = fmt.format(angsuran);
    document.getElementById('total_bayar_display').innerText     = fmt.format(totalBayar);

    // Build jadwal preview
    const container = document.getElementById('jadwal_preview_container');
    const tbody     = document.getElementById('jadwal_preview_body');
    const mulaiLabel = document.getElementById('jadwal_mulai_label');
    if (!container || !tbody) return;

    // Determine start month: next month after tanggal_pinjaman
    let startDate = new Date();
    if (tglInput && tglInput.value) {
        startDate = new Date(tglInput.value);
    }
    startDate.setDate(1);
    startDate.setMonth(startDate.getMonth() + 1);

    const bulanNames = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'];
    mulaiLabel.textContent = ' (mulai ' + bulanNames[startDate.getMonth()] + ' ' + startDate.getFullYear() + ')';

    let sisaPinjaman = jumlah;
    let html = '';
    for (let i = 1; i <= lama; i++) {
        const bayarPokok = (i === lama) ? sisaPinjaman : Math.min(pokokPerBulan, sisaPinjaman);
        const bayarJasa  = jasaPerBulan;
        const total      = bayarPokok + bayarJasa;
        sisaPinjaman     = Math.max(0, sisaPinjaman - bayarPokok);
        const bulanLabel = bulanNames[startDate.getMonth()] + ' ' + startDate.getFullYear();

        html += `<tr style="border-bottom:1px solid #F1F5F9;">
            <td style="padding:5px 10px;text-align:center;"><span style="background:var(--primary-100);color:var(--primary-700);padding:2px 7px;border-radius:6px;font-weight:700;font-size:0.75rem;">${i}</span></td>
            <td style="padding:5px 10px;font-weight:600;color:var(--gray-700);">${bulanLabel}</td>
            <td style="padding:5px 10px;text-align:right;">${fmt.format(bayarPokok)}</td>
            <td style="padding:5px 10px;text-align:right;color:var(--warning-600);">${fmt.format(bayarJasa)}</td>
            <td style="padding:5px 10px;text-align:right;font-weight:700;color:var(--success-700);">${fmt.format(total)}</td>
            <td style="padding:5px 10px;text-align:right;color:var(--danger-600);font-weight:700;">${fmt.format(sisaPinjaman)}</td>
        </tr>`;
        startDate.setMonth(startDate.getMonth() + 1);
    }
    tbody.innerHTML = html;
    container.style.display = 'block';
}

function toggleAllCheckboxes(source) {
    const checkboxes = document.querySelectorAll('.rowCheckbox');
    checkboxes.forEach(checkbox => checkbox.checked = source.checked);
    updateBulkDeleteBtn();
}

function updateBulkDeleteBtn() {
    const form = document.getElementById('bulkDeleteForm');
    const checkboxes = Array.from(document.querySelectorAll('.rowCheckbox')).filter(cb => cb.checked);
    const selectedCount = checkboxes.length;
    
    document.getElementById('selectedCount').innerText = selectedCount;
    
    if (selectedCount > 0) {
        form.style.display = 'block';
        const ids = checkboxes.map(cb => cb.value).join(',');
        document.getElementById('bulkIds').value = ids;
    } else {
        form.style.display = 'none';
    }
}

function submitBulkDelete(e) {
    e.preventDefault();
    
    const count = document.querySelectorAll('.rowCheckbox:checked').length;
    if (!confirm(`Yakin ingin menghapus ${count} pinjaman? Tindakan ini tidak dapat dibatalkan.`)) {
        return false;
    }
    
    const form = document.getElementById('bulkDeleteForm');
    form.submit();
}

// Run once on load for edit
document.addEventListener('DOMContentLoaded', () => {
    if (document.getElementById('editPinjamanModal')) hitungAngsuranEdit();
});
</script>

<!-- Modal Rekap Pinjaman Per Anggota -->
<div class="modal modal-lg" id="rekapPinjamanModal">
    <div class="modal-header">
        <h3><i class="fas fa-list-alt" style="color:var(--warning-500);margin-right:8px;"></i>Rekap Pinjaman Anggota</h3>
        <button class="modal-close" onclick="closeModal('rekapPinjamanModal')"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body">
        <div id="rekapInfo" style="background:var(--gray-50);border-radius:var(--radius-md);padding:12px 16px;margin-bottom:14px;display:flex;align-items:center;gap:12px;">
            <div style="width:38px;height:38px;border-radius:50%;background:var(--warning-500)20;display:flex;align-items:center;justify-content:center;">
                <i class="fas fa-user-tag" style="color:var(--warning-500);font-size:1rem;"></i>
            </div>
            <div>
                <div id="rekapNama" style="font-weight:700;color:var(--gray-800);">-</div>
                <div id="rekapNoAnggota" style="font-size:0.78rem;color:var(--gray-500);">-</div>
            </div>
            <div style="margin-left:auto;text-align:right;">
                <div style="font-size:0.7rem;color:var(--gray-400);text-transform:uppercase;">Total Sisa Pinjaman</div>
                <div id="rekapTotalSisa" style="font-weight:800;color:var(--danger-600);font-size:1.1rem;">-</div>
            </div>
        </div>

        <div id="rekapLoading" style="text-align:center;padding:30px;display:none;">
            <i class="fas fa-spinner fa-spin" style="font-size:1.5rem;color:var(--gray-400);"></i>
            <p style="color:var(--gray-500);margin-top:8px;">Memuat data...</p>
        </div>
        
        <div id="rekapContent" style="max-height:400px;overflow-y:auto;border-radius:var(--radius-md);border:1px solid var(--gray-200);">
            <table class="data-table" style="margin:0;">
                <thead style="position:sticky;top:0;z-index:1;">
                    <tr>
                        <th style="width:40px;">No</th>
                        <th>No Pinjaman</th>
                        <th>Tanggal</th>
                        <th class="text-right">Jumlah</th>
                        <th class="text-right">Sisa</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody id="rekapBody"></tbody>
            </table>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="closeModal('rekapPinjamanModal')">Tutup</button>
    </div>
</div>

<!-- WhatsApp Preview Modal -->
<div class="modal" id="whatsappModal">
    <div class="modal-header">
        <h3><i class="fab fa-whatsapp" style="color: #25D366; margin-right: 8px;"></i>Preview Pesan WhatsApp</h3>
        <button class="modal-close" onclick="closeModal('whatsappModal')"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body">
        <div class="form-group">
            <label>Nomor WhatsApp</label>
            <input type="text" id="wa_phone_display" class="form-control" readonly>
        </div>
        <div class="form-group">
            <label>Pesan</label>
            <textarea id="wa_message_edit" class="form-control" rows="10" style="font-family: monospace;"></textarea>
            <small class="text-muted">* Anda dapat mengedit pesan di atas sebelum mengirim.</small>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('whatsappModal')">Batal</button>
        <button type="button" class="btn btn-success" onclick="sendWhatsappNow()">
            <i class="fab fa-whatsapp"></i> Kirim Sekarang
        </button>
    </div>
</div>

<script>
let currentWaPhone = '';

function openWhatsappModal(phone, message) {
    currentWaPhone = phone;
    document.getElementById('wa_phone_display').value = '+' + phone;
    document.getElementById('wa_message_edit').value = message;
    openModal('whatsappModal');
}

function sendWhatsappNow() {
    const message = document.getElementById('wa_message_edit').value;
    const url = `https://wa.me/${currentWaPhone}?text=${encodeURIComponent(message)}`;
    window.open(url, '_blank');
    closeModal('whatsappModal');
}

function formatRupiahJS(num) {
    if (typeof num === 'string') num = parseFloat(num);
    return 'Rp ' + new Intl.NumberFormat('id-ID').format(num);
}

function showRekapPinjaman(anggotaId) {
    const loading = document.getElementById('rekapLoading');
    const content = document.getElementById('rekapContent');
    const body = document.getElementById('rekapBody');
    
    loading.style.display = 'block';
    content.style.display = 'none';
    
    openModal('rekapPinjamanModal');
    
    fetch('pinjaman.php?ajax_rekap_anggota=' + anggotaId)
        .then(r => r.json())
        .then(data => {
            loading.style.display = 'none';
            content.style.display = 'block';
            
            document.getElementById('rekapNama').textContent = data.nama;
            document.getElementById('rekapNoAnggota').textContent = data.no_anggota;
            document.getElementById('rekapTotalSisa').textContent = formatRupiahJS(data.total_sisa);
            
            if (data.loans.length === 0) {
                body.innerHTML = '<tr><td colspan="6" class="text-center text-muted" style="padding:20px;">Tidak ada riwayat pinjaman</td></tr>';
            } else {
                let html = '';
                data.loans.forEach((l, i) => {
                    const tgl = new Date(l.tanggal_pinjaman).toLocaleDateString('id-ID', {day:'2-digit', month:'short', year:'numeric'});
                    let badgeClass = 'badge-primary';
                    if (l.status === 'lunas') badgeClass = 'badge-info';
                    else if (l.status === 'disetujui') badgeClass = 'badge-success';
                    else if (l.status === 'pending') badgeClass = 'badge-warning';
                    else if (l.status === 'ditolak') badgeClass = 'badge-danger';
                    
                    html += `<tr>
                        <td>${i+1}</td>
                        <td class="fw-bold">${l.no_pinjaman}</td>
                        <td>${tgl}</td>
                        <td class="text-right">${formatRupiahJS(l.jumlah_pinjaman)}</td>
                        <td class="text-right fw-bold text-danger">${formatRupiahJS(l.sisa_pinjaman)}</td>
                        <td><span class="badge ${badgeClass}">${l.status}</span></td>
                    </tr>`;
                });
                body.innerHTML = html;
            }
        })
        .catch(err => {
            loading.style.display = 'none';
            content.style.display = 'block';
            body.innerHTML = '<tr><td colspan="6" class="text-center text-danger" style="padding:20px;">Gagal memuat data</td></tr>';
        });
}
</script>

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