<?php
/**
 * Transaksi Koperasi Konsumsi
 * Koperasi Management System
 */

// Increase execution time for large calculations
set_time_limit(300); // 5 minutes
ini_set('memory_limit', '256M');

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

$pageTitle = 'Koperasi Konsumsi';
$pageSubtitle = 'Manajemen belanja harian anggota';

// Get current month and year
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('n');
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

// Get monthly limit for selected month
$batasBulanan = getKonsumsiLimitBulanan($selectedMonth, 50000);

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_limit') {
        // Update monthly limit for a specific month
        $bulan = (int)$_POST['bulan'];
        $newLimit = (float)str_replace('.', '', $_POST['new_limit']);
        
        if ($bulan >= 1 && $bulan <= 12 && $newLimit >= 0) {
            if (updateKonsumsiLimitBulanan($bulan, $newLimit)) {
                setFlash('success', 'Batas belanja bulan ini berhasil diperbarui.');
            } else {
                setFlash('danger', 'Gagal memperbarui batas belanja.');
            }
        } else {
            setFlash('danger', 'Bulan atau batas belanja tidak valid.');
        }
        header('Location: konsumsi.php?month=' . $bulan . '&year=' . date('Y'));
        exit;
    }
    
    if ($action === 'update_limit_anggota') {
        // Update per-member consumption limit (optional override)
        $anggotaId = (int)$_POST['anggota_id'];
        $bulan = (int)$_POST['bulan'];
        $newLimit = (float)str_replace('.', '', $_POST['batas_anggota'] ?? 0);
        
        if ($anggotaId > 0 && $bulan >= 1 && $bulan <= 12) {
            if (setKonsumsiLimitAnggota($anggotaId, $bulan, $newLimit)) {
                $msg = $newLimit > 0 ? 'Batas belanja anggota berhasil diperbarui.' : 'Batas belanja anggota yang di-override berhasil dihapus.';
                setFlash('success', $msg);
            } else {
                setFlash('danger', 'Gagal memperbarui batas belanja anggota.');
            }
        } else {
            setFlash('danger', 'Data tidak valid.');
        }
        header('Location: konsumsi.php?month=' . $bulan . '&year=' . date('Y'));
        exit;
    }
    
    if ($action === 'add') {
        $anggotaId = $_POST['anggota_id'];
        $tanggal = $_POST['tanggal'];
        $keteranganGlobal = sanitize($_POST['keterangan'] ?? '');
        
        $namaBarangs = $_POST['nama_barang'] ?? [];
        $hargaBelis = $_POST['harga_beli'] ?? [];
        $globalPpnPersen = (float)($_POST['ppn_persen_global'] ?? 0);
        
        if (!$anggotaId) {
            setFlash('danger', 'Gagal: Anggota harus dipilih dari daftar yang muncul!');
        } else if (empty($namaBarangs)) {
            setFlash('danger', 'Gagal: Masukkan setidaknya satu barang!');
        } else {
            $count = 0;
            $db->beginTransaction();
            try {
                foreach ($namaBarangs as $i => $namaBarang) {
                    $namaBarangText = sanitize($namaBarang);
                    if (empty($namaBarangText)) continue;

                    $hargaBeli = (float)str_replace('.', '', $hargaBelis[$i] ?? 0);
                    
                    // PPN applied globally based on total cost (calculated at database level)
                    $ppnNominal = round($hargaBeli * ($globalPpnPersen / 100));
                    $calculatedHargaJual = $hargaBeli + $ppnNominal;
                    
                    if ($calculatedHargaJual > 0) {
                        $stmt = $db->prepare("INSERT INTO konsumsi_transaksi (anggota_id, tanggal, nama_barang, harga_beli, ppn_persen, harga_jual, jumlah_belanja, keterangan, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        $stmt->execute([$anggotaId, $tanggal, $namaBarangText, $hargaBeli, $globalPpnPersen, $calculatedHargaJual, $calculatedHargaJual, $keteranganGlobal, $_SESSION['user_id']]);
                        $count++;
                    }
                }
                
                if ($count > 0) {
                    $db->commit();
                    setFlash('success', "Berhasil mencatat $count transaksi belanja.");
                } else {
                    $db->rollBack();
                    setFlash('danger', 'Gagal: Tidak ada item belanja yang valid.');
                }
            } catch (Exception $e) {
                $db->rollBack();
                setFlash('danger', 'Gagal: Terjadi kesalahan sistem: ' . $e->getMessage());
            }
        }
        header('Location: konsumsi.php');
        exit;
    }
    
    if ($action === 'delete') {
        $id = $_POST['id'];
        $db->prepare("DELETE FROM konsumsi_transaksi WHERE id = ?")->execute([$id]);
        setFlash('success', 'Transaksi berhasil dihapus.');
        header('Location: konsumsi.php');
        exit;
    }

    if ($action === 'update_konsumsi') {
        $id = $_POST['id'];
        $tanggal = $_POST['tanggal'];
        $namaBarang = sanitize($_POST['nama_barang']);
        $hargaBeli = (float)str_replace('.', '', $_POST['harga_beli']);
        $ppnPersen = (float)$_POST['ppn_persen'];
        $hargaJual = (float)str_replace('.', '', $_POST['harga_jual']);
        $keterangan = sanitize($_POST['keterangan']);

        if ($id && $tanggal && $namaBarang && $hargaJual > 0) {
            $stmt = $db->prepare("UPDATE konsumsi_transaksi SET tanggal = ?, nama_barang = ?, harga_beli = ?, ppn_persen = ?, harga_jual = ?, jumlah_belanja = ?, keterangan = ? WHERE id = ?");
            $stmt->execute([$tanggal, $namaBarang, $hargaBeli, $ppnPersen, $hargaJual, $hargaJual, $keterangan, $id]);
            setFlash('success', 'Transaksi belanja berhasil diperbarui.');
        } else {
            setFlash('danger', 'Data transaksi tidak valid.');
        }
        header('Location: konsumsi.php');
        exit;
    }

    if ($action === 'update_limit_table') {
        // Table inline edit for per-member limit
        $anggotaId = (int)$_POST['anggota_id'];
        $bulan = (int)($_POST['bulan'] ?? $selectedMonth);
        $newLimitStr = $_POST['new_limit'] ?? '0';
        $newLimit = (float)str_replace(['.', ','], '', $newLimitStr);

        if ($anggotaId > 0 && $bulan >= 1 && $bulan <= 12 && $newLimit >= 0) {
            if (setKonsumsiLimitAnggota($anggotaId, $bulan, $newLimit)) {
                $msg = $newLimit > 0 ? 'Batas belanja anggota berhasil diperbarui menjadi ' . formatRupiah($newLimit) . '.' : 'Override batas belanja dihapus, kembali ke batas bulanan.';
                setFlash('success', $msg);
            } else {
                setFlash('danger', 'Gagal memperbarui batas belanja anggota.');
            }
        } else {
            setFlash('danger', 'Data tidak valid (ID: ' . $anggotaId . ', Bulan: ' . $bulan . ', Limit: ' . $newLimit . ').');
        }
        $search = $_GET['search'] ?? '';
        header('Location: konsumsi.php?month=' . $selectedMonth . '&year=' . $selectedYear . ($search ? '&search=' . urlencode($search) : ''));
        exit;
    }
}

// Logic to calculate balance

$months = [
    1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
    5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
    9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
];

$periodDate = new DateTime("$selectedYear-$selectedMonth-01");
$lastDayOfPeriod = $periodDate->format('Y-m-t');

$search = $_GET['search'] ?? '';

// Optimized: Get all members with transaction data in a SINGLE query using JOIN
$queryMembers = "
    SELECT 
        a.id, a.nama, a.no_anggota, a.tanggal_daftar, a.telepon,
        COALESCE(SUM(CASE WHEN MONTH(t.tanggal) = ? AND YEAR(t.tanggal) = ? THEN t.jumlah_belanja ELSE 0 END), 0) as total_belanja_bulan_ini,
        COALESCE(SUM(CASE WHEN MONTH(t.tanggal) = ? AND YEAR(t.tanggal) = ? THEN t.harga_beli ELSE 0 END), 0) as total_harga_asli,
        COALESCE(SUM(CASE WHEN MONTH(t.tanggal) = ? AND YEAR(t.tanggal) = ? THEN (t.harga_beli * (t.ppn_persen/100)) ELSE 0 END), 0) as total_ppn
    FROM anggota a
    LEFT JOIN konsumsi_transaksi t ON a.id = t.anggota_id
    WHERE a.is_konsumsi = 1
";

$params = [
    $selectedMonth, $selectedYear,
    $selectedMonth, $selectedYear,
    $selectedMonth, $selectedYear
];

if ($search) {
    $where = " AND (a.nama LIKE ? OR a.no_anggota LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
} else {
    $where = "";
}

$queryMembers .= $where . " GROUP BY a.id ORDER BY a.nama ASC";

$stmtMembers = $db->prepare($queryMembers);
$stmtMembers->execute($params);
$memberSummaries = $stmtMembers->fetchAll();

// Pre-load all transactions for efficiency (ONLY for current selected month)
// This reduces memory usage significantly by not loading all historical data
$allTransactionsCache = [];
$stmtAllTrans = $db->prepare("
    SELECT anggota_id, 
           SUM(jumlah_belanja) as total_belanja
    FROM konsumsi_transaksi 
    WHERE MONTH(tanggal) = ? AND YEAR(tanggal) = ?
    GROUP BY anggota_id
");
$stmtAllTrans->execute([$selectedMonth, $selectedYear]);
foreach ($stmtAllTrans->fetchAll() as $row) {
    $allTransactionsCache[$row['anggota_id']] = (float)$row['total_belanja'];
}

// Pre-load all per-member limits into easier structure
$allMemberLimitsCache = [];
$stmtMemberLimits = $db->query("SELECT anggota_id, bulan, batas FROM konsumsi_batas_anggota");
foreach ($stmtMemberLimits->fetchAll() as $row) {
    $key = $row['anggota_id'] . '|' . $row['bulan'];
    $allMemberLimitsCache[$key] = (float)$row['batas'];
}

// Function to calculate rolling balance for a specific member using database
function calculateRollingBalance($db, $memberId, $targetMonth, $targetYear, $joinDate, $defaultLimits, $allMemberLimitsCache) {
    // Set start reference point (January 2026 or join date, whichever is appropriate)
    $joinYear = (int)date('Y', strtotime($joinDate));
    $joinMonth = (int)date('n', strtotime($joinDate));
    
    // Use the join date as starting point (default to Jan 2026 if null/earlier)
    if (!$joinDate || $joinYear < 2026) {
        $startYear = 2026;
        $startMonth = 1;
    } else {
        $startYear = $joinYear;
        $startMonth = $joinMonth;
    }
    
    // Safety check: prevent infinite loop if target is before start
    if ($targetYear < $startYear || ($targetYear == $startYear && $targetMonth < $startMonth)) {
        return 0;
    }
    
    // Safety limit: max 10 years (120 months) to prevent timeout
    $maxMonths = 120;
    $monthCount = 0;
    
    // Load ALL monthly spending data for this member in ONE query (highly optimized)
    $stmt = $db->prepare("
        SELECT MONTH(tanggal) as bulan, YEAR(tanggal) as tahun, 
               COALESCE(SUM(jumlah_belanja), 0) as spending
        FROM konsumsi_transaksi
        WHERE anggota_id = ? 
          AND (
            (YEAR(tanggal) > ?) 
            OR (YEAR(tanggal) = ? AND MONTH(tanggal) >= ?)
            OR (YEAR(tanggal) = ? AND MONTH(tanggal) <= ?)
          )
        GROUP BY YEAR(tanggal), MONTH(tanggal)
    ");
    $stmt->execute([$memberId, $startYear, $startYear, $startMonth, $targetYear, $targetMonth]);
    
    // Build lookup map for fast access: year|month => spending
    $spendingMap = [];
    foreach ($stmt->fetchAll() as $row) {
        $key = $row['tahun'] . '|' . str_pad($row['bulan'], 2, '0', STR_PAD_LEFT);
        $spendingMap[$key] = (float)$row['spending'];
    }
    
    $balance = 0;
    $currentYear = $startYear;
    $currentMonth = $startMonth;
    
    // Iterate through each month using pre-loaded data (no database queries in loop!)
    while (true) {
        // Safety check: prevent infinite loop
        $monthCount++;
        if ($monthCount > $maxMonths) {
            error_log("calculateRollingBalance: Max months limit reached for member $memberId");
            break;
        }
        
        // Get spending for this month from map
        $mapKey = $currentYear . '|' . str_pad($currentMonth, 2, '0', STR_PAD_LEFT);
        $spending = $spendingMap[$mapKey] ?? 0;
        
        // Get member's limit for this month (check override, then default)
        $monthlyLimit = (float)($defaultLimits[$currentMonth] ?? 50000);
        $memberLimitKey = $memberId . '|' . $currentMonth;
        if (isset($allMemberLimitsCache[$memberLimitKey])) {
            $monthlyLimit = $allMemberLimitsCache[$memberLimitKey];
        }
        
        // Add this month's balance
        $balance = $balance + $monthlyLimit - $spending;
        
        // Stop if we've reached the target month
        if ($currentYear == $targetYear && $currentMonth == $targetMonth) {
            break;
        }
        
        // Move to next month
        $currentMonth++;
        if ($currentMonth > 12) {
            $currentMonth = 1;
            $currentYear++;
        }
    }
    
    return $balance;
}

// Pre-load all default limits
$defaultLimits = [];
$stmtLimits = $db->query("SELECT bulan, batas FROM konsumsi_batas_bulanan");
foreach ($stmtLimits->fetchAll() as $row) {
    $defaultLimits[(int)$row['bulan']] = (float)$row['batas'];
}

// Pre-load all minimum transaction dates for all members using single database query
$minTransactionDates = [];
$stmtMinTrans = $db->query("
    SELECT anggota_id, MIN(YEAR(tanggal)) as min_year, MIN(MONTH(tanggal)) as min_month 
    FROM konsumsi_transaksi 
    GROUP BY anggota_id
");
foreach ($stmtMinTrans->fetchAll() as $row) {
    $minTransactionDates[$row['anggota_id']] = [
        'min_year' => (int)$row['min_year'],
        'min_month' => (int)$row['min_month']
    ];
}

// Calculate display data with proper rolling balance logic
$displayData = [];
foreach ($memberSummaries as $m) {
    $spentThisMonth = (float)$m['total_belanja_bulan_ini'];
    
    // Get join date (use earliest transaction or join date)
    $joinDate = $m['tanggal_daftar'] ?: '2026-01-01';
    
    // Get pre-loaded minimum transaction date
    $minTransaction = $minTransactionDates[$m['id']] ?? null;
    
    // Determine actual reference year/month
    $joinYear = (int)date('Y', strtotime($joinDate));
    $joinMonth = (int)date('n', strtotime($joinDate));
    
    if ($minTransaction) {
        // Use earliest transaction date
        $referenceYear = (int)$minTransaction['min_year'];
        $referenceMonth = (int)$minTransaction['min_month'];
    } else {
        // Use join date
        $referenceYear = $joinYear;
        $referenceMonth = $joinMonth;
    }
    
    // Skip if member hasn't joined yet in the selected period
    if ($referenceYear > $selectedYear || 
        ($referenceYear == $selectedYear && $referenceMonth > $selectedMonth)) {
        continue;
    }
    
    // Get member's limit for current month (includes per-member override) 
    // Use the pre-loaded default limits and member limits
    $memberMonthlyLimit = (float)($defaultLimits[$selectedMonth] ?? 50000);
    if (isset($allMemberLimitsCache[$m['id'] . '|' . $selectedMonth])) {
        $memberMonthlyLimit = $allMemberLimitsCache[$m['id'] . '|' . $selectedMonth];
    }
    
    // Calculate balance from start to previous month (if exists)
    $saldoLalu = 0;
    if ($selectedMonth > 1 || $selectedYear > $referenceYear || 
        ($selectedYear == $referenceYear && $selectedMonth > $referenceMonth)) {
        $prevMonth = $selectedMonth - 1;
        $prevYear = $selectedYear;
        if ($prevMonth < 1) {
            $prevMonth = 12;
            $prevYear--;
        }
        $saldoLalu = calculateRollingBalance($db, $m['id'], $prevMonth, $prevYear, $joinDate, $defaultLimits, $allMemberLimitsCache);
    }
    
    // Check if member is active in the selected month
    $monthsCount = (($selectedYear - $referenceYear) * 12) + ($selectedMonth - $referenceMonth) + 1;
    $plafonBulanIni = ($monthsCount > 0) ? $memberMonthlyLimit : 0;
    
    // Saldo Awal = Saldo dari bulan lalu + Batas belanja bulan ini
    $saldoAwal = $saldoLalu + $plafonBulanIni;
    
    $m['total_belanja'] = $spentThisMonth;
    $m['total_harga_asli'] = (float)$m['total_harga_asli'];
    $m['total_ppn'] = (float)$m['total_ppn'];
    $m['saldo_lalu'] = $saldoLalu;
    $m['plafon_ini'] = $plafonBulanIni;
    $m['saldo_awal'] = $saldoAwal;
    
    // Saldo Akhir = Saldo Awal - Belanja bulan ini (rolling ke bulan depan)
    $m['saldo_akhir'] = $saldoAwal - $spentThisMonth;
    
    $displayData[] = $m;
}

// Recent transactions for the list - filtered by selected month
$stmtRecent = $db->prepare("
    SELECT t.*, a.nama, a.no_anggota 
    FROM konsumsi_transaksi t 
    LEFT JOIN anggota a ON t.anggota_id = a.id 
    WHERE MONTH(t.tanggal) = ? AND YEAR(t.tanggal) = ?
    ORDER BY t.tanggal DESC, t.id DESC 
    LIMIT 50
");
$stmtRecent->execute([$selectedMonth, $selectedYear]);
$recentTransactions = $stmtRecent->fetchAll();

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

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

<style>
/* Modern Consumption Page Styles */
.stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 24px;
    margin-bottom: 32px;
}

.new-stats-card {
    background: white;
    padding: 24px;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-sm);
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid var(--gray-100);
    transition: all var(--transition-base);
    position: relative;
    overflow: hidden;
}

.new-stats-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--shadow-md);
    border-color: var(--primary-200);
}

.new-stats-info p {
    color: var(--gray-500);
    font-size: 0.75rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    margin-bottom: 8px;
}

.new-stats-info h3 {
    font-size: 1.75rem;
    font-weight: 800;
    color: var(--gray-900);
    margin: 0;
    letter-spacing: -0.02em;
}

.new-stats-icon {
    width: 56px;
    height: 56px;
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    transition: all var(--transition-base);
}

.bg-konsumsi { background: var(--primary-50); color: var(--primary-600); }
.bg-realisasi { background: var(--success-50); color: var(--success-600); }
.bg-config { background: var(--warning-50); color: var(--warning-600); }

/* Ultra Compact & Modern Refinement */
.pro-card-compact { 
    margin-bottom: 24px; 
    border: 1px solid var(--gray-100);
}
.pro-card-compact .pro-card-header { 
    padding: 12px 20px; 
}
.pro-card-compact .pro-card-body { 
    padding: 16px 20px; 
}

/* Floating Label Logic - Premium Refinement */
.floating-group {
    position: relative;
    margin-bottom: 0px;
    width: 100%;
}

.floating-input {
    height: 48px !important;
    padding: 14px 14px 0 42px !important;
    border: 1.5px solid var(--gray-200) !important;
    border-radius: 12px !important;
    font-size: 0.95rem !important;
    background: white !important;
    transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
    width: 100% !important;
}

.floating-input:focus {
    border-color: var(--primary-500) !important;
    background: white !important;
    box-shadow: 0 0 0 4px var(--primary-50) !important;
}

.floating-label {
    position: absolute;
    top: 50%;
    left: 44px;
    transform: translateY(-50%);
    font-size: 0.95rem;
    color: var(--gray-400);
    pointer-events: none;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    font-weight: 500;
    margin: 0;
    z-index: 10;
}

.floating-input:focus ~ .floating-label,
.floating-input:not(:placeholder-shown) ~ .floating-label {
    top: 10px;
    left: 44px;
    font-size: 0.6rem;
    color: var(--primary-500);
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    background: transparent;
}

.floating-group i {
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--gray-400);
    font-size: 1rem;
    z-index: 5;
    transition: all 0.25s ease;
}

.floating-input:focus ~ i {
    color: var(--primary-500);
}

.footer-action-row {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 20px;
    padding-top: 16px;
    border-top: 1px dashed var(--gray-100);
    margin-top: 16px;
}

.btn-modern {
    height: 44px;
    padding: 0 32px;
    border-radius: 10px;
    font-weight: 700;
    font-size: 0.9rem;
    text-transform: uppercase;
    letter-spacing: 0.02em;
}

.total-summary-inline {
    display: flex;
    align-items: center;
    gap: 12px;
}

.total-summary-inline .label {
    font-size: 0.65rem;
    font-weight: 800;
    color: var(--gray-400);
    text-transform: uppercase;
    letter-spacing: 0.1em;
}

.total-summary-inline .value {
    font-size: 1.25rem;
    font-weight: 900;
    color: var(--primary-700);
}

.pro-card {
    border-radius: var(--radius-xl);
    border: none;
    box-shadow: var(--shadow-md);
    background: white;
    margin-bottom: 32px;
}

.pro-card-header {
    padding: 24px 32px;
    background: white;
    border-bottom: 1px solid var(--gray-100);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.pro-card-header h3 {
    font-weight: 800;
    font-size: 1.25rem;
    color: var(--gray-900);
    margin: 0;
    display: flex;
    align-items: center;
    gap: 12px;
}

.pro-card-body {
    padding: 32px;
}

.action-panel {
    background: var(--gray-50);
    border-radius: var(--radius-lg);
    padding: 24px;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    border: 1px dashed var(--gray-200);
}

.price-container {
    text-align: center;
    margin-bottom: 24px;
}

.display-total-large {
    background: white;
    padding: 16px;
    border-radius: var(--radius-md);
    box-shadow: var(--shadow-sm);
    display: flex;
    align-items: baseline;
    justify-content: center;
    gap: 8px;
    border: 2px solid var(--primary-100);
}

.display-total-large .currency {
    font-size: 1.25rem;
    font-weight: 700;
    color: var(--primary-500);
}

.search-box-pro {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 0 12px;
    height: 38px;
    transition: all 0.3s ease;
}

.search-box-pro input {
    border: none;
    background: transparent;
    outline: none;
    color: var(--gray-700);
    font-weight: 500;
}

.search-box-pro:focus-within {
    background: white !important;
    box-shadow: 0 0 0 3px var(--primary-50);
    border-radius: 10px;
}

.btn-primary-pro {
    background: var(--primary-600);
    color: white;
    border: none;
    padding: 16px 24px;
    border-radius: var(--radius-md);
    font-weight: 700;
    font-size: 1rem;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
    width: 100%;
    transition: all var(--transition-base);
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.2);
}

.btn-primary-pro:hover {
    background: var(--primary-700);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(37, 99, 235, 0.4);
}

/* Table Enhancements Re-refined */
.table-clean-pro {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
}

.table-clean-pro th {
    background: linear-gradient(135deg, #6366f1 0%, #4338ca 100%);
    color: white;
    font-size: 0.7rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    padding: 18px 20px;
    border: none;
    white-space: nowrap;
}

.table-clean-pro thead tr th:first-child { border-top-left-radius: 12px; }
.table-clean-pro thead tr th:last-child { border-top-right-radius: 12px; }

.table-clean-pro td {
    padding: 18px 20px;
    border-bottom: 1px solid #F1F5F9;
    color: var(--gray-700);
    vertical-align: middle;
    font-size: 0.9rem;
}

.member-info {
    display: flex;
    flex-direction: column;
}

.member-name {
    font-weight: 700;
    color: var(--gray-900);
    font-size: 0.95rem;
}

.member-id {
    font-size: 0.75rem;
    color: var(--gray-400);
    font-family: 'Inter', sans-serif;
}

/* Row Hover & Highlights */
.table-clean-pro tbody tr {
    transition: all 0.2s ease;
}

.table-clean-pro tbody tr:nth-child(even) {
    background-color: #FDFEFE;
}

.table-clean-pro tbody tr:hover {
    background-color: #EEF2FF !important;
    transform: scale(1.002);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
}

.saldo-highlight {
    background: linear-gradient(135deg, #EEF2FF 0%, #E0E7FF 100%);
    color: #4338ca;
    font-weight: 800;
    padding: 8px 14px;
    border-radius: 10px;
    font-size: 0.85rem;
    display: inline-block;
    border: 1px solid #C7D2FE;
    box-shadow: 0 2px 4px rgba(79, 70, 229, 0.05);
}

.badge-soft {
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 0.75rem;
    font-weight: 700;
    display: inline-flex;
    align-items: center;
    gap: 5px;
}

.badge-soft-success { 
    background: #DCFCE7; 
    color: #15803d; 
    border: 1px solid #BBF7D0;
}
.badge-soft-danger { 
    background: #FEE2E2; 
    color: #B91C1C; 
    border: 1px solid #FECACA;
}
.badge-soft-warning { 
    background: #FEF3C7; 
    color: #B45309; 
    border: 1px solid #FDE68A;
}

/* Searchable Dropdown Modernization */
.searchable-dropdown { position: relative; width: 100%; }
.dropdown-results {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid var(--gray-200);
    border-radius: 14px;
    margin-top: 8px;
    max-height: 250px;
    overflow-y: auto;
    z-index: 1000;
    box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
    display: none;
}

.dropdown-results.active { display: block; animation: slideDown 0.2s ease-out; }

@keyframes slideDown {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

.dropdown-item {
    padding: 12px 16px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 12px;
    border-radius: var(--radius-sm);
    transition: all var(--transition-fast);
}

.dropdown-item:hover { background: var(--primary-50); color: var(--primary-700); }
.dropdown-item i { color: var(--gray-400); font-size: 1rem; }

.minimal-select {
    padding: 8px 12px;
    border: none;
    background: transparent;
    font-weight: 600;
    color: var(--gray-700);
    cursor: pointer;
    outline: none;
}

.search-box-pro {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px 16px;
    background: white;
    border: 1px solid var(--gray-200);
    border-radius: var(--radius-md);
    width: 280px;
}

.search-box-pro input {
    border: none;
    background: transparent;
    outline: none;
    width: 100%;
    font-size: 0.9rem;
}

.dropdown-item.best-suggestion {
    background: var(--primary-50);
    border-left: 4px solid var(--primary-500);
    position: relative;
}

.dropdown-item.best-suggestion::after {
    content: 'Saran';
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 0.65rem;
    font-weight: 800;
    text-transform: uppercase;
    color: var(--primary-600);
    background: white;
    padding: 2px 8px;
    border-radius: 4px;
    border: 1px solid var(--primary-100);
}

@media print {
    .no-print { display: none !important; }
}
</style>

<div class="row mb-5">
    <div class="col-md-12">
        <div class="stats-container">
            <div class="new-stats-card">
                <div class="new-stats-info">
                    <p>Batas Belanja Bulanan</p>
                    <h3><?= formatRupiah($batasBulanan) ?></h3>
                </div>
                <div class="new-stats-icon bg-konsumsi">
                    <i class="fas fa-shopping-bag"></i>
                </div>
            </div>
            
            <div class="new-stats-card">
                <div class="new-stats-info">
                    <p>Realisasi Periode</p>
                    <?php 
                        $stmtThisMonth = $db->prepare("SELECT SUM(jumlah_belanja) FROM konsumsi_transaksi WHERE MONTH(tanggal) = ? AND YEAR(tanggal) = ?");
                        $stmtThisMonth->execute([$selectedMonth, $selectedYear]);
                        $thisMonthSum = $stmtThisMonth->fetchColumn();
                    ?>
                    <h3 style="color: var(--success-600);"><?= formatRupiah($thisMonthSum ?: 0) ?></h3>
                </div>
                <div class="new-stats-icon bg-realisasi">
                    <i class="fas fa-chart-line"></i>
                </div>
            </div>
            
            <div class="new-stats-card" style="cursor: pointer;" onclick="openModal('settingLimitModal')">
                <div class="new-stats-info">
                    <p>Atur Batas Sistem</p>
                    <h3 style="color: var(--warning-600); font-size: 1.25rem;"><i class="fas fa-cog"></i> Konfigurasi</h3>
                </div>
                <div class="new-stats-icon bg-config">
                    <i class="fas fa-tools"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 1. Input Section -->
    <div class="col-md-12 mb-4">
        <div class="pro-card pro-card-compact">
            <div class="pro-card-header">
                <h3>
                    <i class="fas fa-shopping-cart text-primary"></i>
                    Input Belanja Baru
                </h3>
                <div class="d-flex align-items-center" style="background: var(--primary-50); padding: 6px 16px; border-radius: 99px; gap: 8px;">
                    <i class="fas fa-calendar-alt text-primary" style="font-size: 0.8rem;"></i>
                    <span style="font-size: 0.8rem; font-weight: 700; color: var(--primary-400);">Periode:</span>
                    <select id="input_header_month" class="minimal-select-header" onchange="updatePeriodFromHeader()">
                        <?php foreach ($months as $num => $name): ?>
                            <option value="<?= $num ?>" <?= $selectedMonth == $num ? 'selected' : '' ?>><?= $name ?></option>
                        <?php endforeach; ?>
                    </select>
                    <div style="width: 1px; height: 12px; background: var(--primary-200);"></div>
                    <select id="input_header_year" class="minimal-select-header" onchange="updatePeriodFromHeader()">
                        <?php for ($y = 2024; $y <= (int)date('Y')+1; $y++): ?>
                            <option value="<?= $y ?>" <?= $selectedYear == $y ? 'selected' : '' ?>><?= $y ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
            </div>
            <form method="POST" onsubmit="return validateSearchableDropdown(this)">
                <input type="hidden" name="action" value="add">
                <div class="pro-card-body">
                    <!-- Row 1: Anggota Selection & Date -->
                    <div class="row g-3 mb-4">
                        <div class="col-md-8">
                            <div class="floating-group searchable-dropdown">
                                <i class="fas fa-user-tag"></i>
                                <input type="text" class="form-control floating-input" name="anggota_search" id="member_search_input" 
                                       placeholder=" " autocomplete="off"
                                       oninput="filterMemberDropdown(this)" onfocus="filterMemberDropdown(this)">
                                <label class="floating-label">Cari Nama Anggota atau No. Kartu Aktif *</label>
                                <input type="hidden" name="anggota_id" id="member_id_hidden">
                                <div class="dropdown-results" id="member_results_list">
                                    <div class="dropdown-item no-results" style="display: none; color: var(--gray-400); cursor: default; font-style: italic;">
                                        <i class="fas fa-search-minus"></i>
                                        <span>Anggota tidak ditemukan...</span>
                                    </div>
                                    <?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-id-card"></i>
                                            <span><?= htmlspecialchars($a['no_anggota'] . ' - ' . $a['nama']) ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="floating-group">
                                <i class="fas fa-calendar-check"></i>
                                <input type="date" name="tanggal" class="form-control floating-input" 
                                       placeholder=" " required value="<?= date('Y-m-d') ?>">
                                <label class="floating-label">Tgl Belanja</label>
                            </div>
                        </div>
                    </div>

                    <div style="margin-bottom: 12px; display: flex; justify-content: space-between; align-items: center;">
                        <h4 style="font-size: 0.85rem; font-weight: 800; color: var(--gray-500); text-transform: uppercase; margin: 0; letter-spacing: 0.05em;">Daftar Barang Belanja</h4>
                        <button type="button" class="btn btn-sm btn-outline-primary" style="border-radius: 8px; font-weight: 700; font-size: 0.75rem;" onclick="addItemRow()">
                            <i class="fas fa-plus"></i> Tambah Item
                        </button>
                    </div>

                    <!-- Items Container -->
                    <div id="items-container">
                        <div class="item-row mb-3 p-3" style="background: var(--gray-50); border-radius: 16px; position: relative; border: 1px solid var(--gray-100);">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <div class="floating-group">
                                        <i class="fas fa-shopping-basket"></i>
                                        <input type="text" name="nama_barang[]" class="form-control floating-input" 
                                               placeholder=" " required>
                                        <label class="floating-label">Nama Barang / Deskripsi *</label>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="floating-group">
                                        <i class="fas fa-coins text-warning"></i>
                                        <input type="text" name="harga_beli[]" class="form-control floating-input harga-beli-input" 
                                               placeholder=" " required oninput="formatCurrencyInput(this); calculateTotals();"
                                               style="font-weight: 700; color: var(--gray-700);">
                                        <label class="floating-label">Harga Beli (Rp)</label>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="item-subtotal-display" style="height: 48px; display: flex; flex-direction: column; justify-content: center; text-align: right; padding-right: 10px;">
                                        <span style="font-size: 0.6rem; color: var(--gray-400); font-weight: 700; text-transform: uppercase;">Subtotal</span>
                                        <span class="subtotal-val fw-bold" style="color: var(--primary-600); font-size: 1rem;">Rp 0</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Global Note & PPN & Footer Action -->
                    <div class="row g-3 mt-2">
                        <div class="col-md-5">
                            <div class="floating-group">
                                <i class="fas fa-pen-nib"></i>
                                <input type="text" name="keterangan" class="form-control floating-input" placeholder=" ">
                                <label class="floating-label">Catatan Transaksi (Opsional)</label>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="floating-group">
                                <i class="fas fa-percent text-info"></i>
                                <input type="number" name="ppn_persen_global" class="form-control floating-input" placeholder=" " value="0" step="0.01" oninput="calculateTotals()"
                                       style="font-weight: 700; color: var(--gray-700);">
                                <label class="floating-label">PPN Global (%)</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="footer-action-row mt-0 pt-0" style="border: none; height: 100%;">
                                <div class="total-summary-inline" style="background: var(--primary-50); padding: 8px 16px; border-radius: 12px; border: 1px solid var(--primary-100); flex: 1;">
                                    <span class="label">Grand Total:</span>
                                    <div class="d-flex align-items-baseline" style="gap: 4px;">
                                        <span style="font-size: 0.85rem; font-weight: 800; color: var(--primary-400);">Rp</span>
                                        <span id="grand_total_display" class="value" style="font-weight: 900;">0</span>
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-primary btn-modern shadow-lg" style="border-radius: 14px; background: linear-gradient(135deg, var(--primary-600) 0%, var(--primary-700) 100%);">
                                    <i class="fas fa-save me-2"></i> SIMPAN
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 2. Table Section (Main Data) -->
    <div class="col-md-12 mb-5">
        <div class="pro-card">
            <div class="pro-card-header d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div class="d-flex align-items-center flex-wrap" style="gap: 15px;">
                    <h3 class="mb-0 me-2" style="white-space: nowrap;">
                        <i class="fas fa-users-cog text-info me-2"></i>
                        Saldo Konsumsi
                    </h3>
                    
                    <div class="d-flex align-items-center flex-wrap" style="background: white; border: 1.5px solid #F1F5F9; border-radius: 14px; padding: 5px 12px; gap: 12px; box-shadow: 0 2px 4px rgba(0,0,0,0.02);">
                        <div class="period-picker d-flex align-items-center" style="gap: 5px;">
                            <div style="background: var(--primary-50); color: var(--primary-600); padding: 5px 10px; border-radius: 8px; font-size: 0.65rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; display: flex; align-items: center; gap: 5px;">
                                <i class="fas fa-calendar-day"></i>
                                <span>Periode</span>
                            </div>
                            <select id="filter_month" class="minimal-select" onchange="updatePeriod()" style="font-size: 0.85rem; font-weight: 700; border: none; background: transparent; padding: 5px 8px; cursor: pointer; color: var(--gray-800);">
                                <?php foreach ($months as $num => $name): ?>
                                    <option value="<?= $num ?>" <?= $selectedMonth == $num ? 'selected' : '' ?>><?= $name ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div style="width: 1px; height: 16px; background: #E2E8F0;"></div>
                            <select id="filter_year" class="minimal-select" onchange="updatePeriod()" style="font-size: 0.85rem; font-weight: 700; border: none; background: transparent; padding: 5px 8px; cursor: pointer; color: var(--gray-800);">
                                <?php for ($y = 2024; $y <= (int)date('Y')+1; $y++): ?>
                                    <option value="<?= $y ?>" <?= $selectedYear == $y ? 'selected' : '' ?>><?= $y ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="d-none d-sm-block" style="width: 1.5px; height: 24px; background: #F1F5F9;"></div>
                        <div class="search-box-pro d-flex align-items-center" style="gap: 10px;">
                            <i class="fas fa-search" style="color: var(--gray-400); font-size: 0.8rem;"></i>
                            <input type="text" placeholder="Cari nama anggota..." value="<?= htmlspecialchars($search) ?>"
                                   style="border: none; background: transparent; font-size: 0.85rem; width: 140px; outline: none; transition: all 0.3s; font-weight: 500; color: var(--gray-700);"
                                   onfocus="this.style.width='200px'" onblur="if(!this.value) this.style.width='140px'"
                                   onkeydown="if(event.key==='Enter') { updatePeriod(this.value); }">
                        </div>
                    </div>
                </div>

                <div class="d-flex align-items-center flex-nowrap" style="gap: 8px;">
                    <a href="konsumsi_shu.php?tahun=<?= $selectedYear ?>" 
                       class="btn shadow-sm" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; border-radius: 10px; padding: 0 20px; height: 42px; display: flex; align-items: center; gap: 8px; font-weight: 800; font-size: 0.85rem; letter-spacing: 0.5px; border: none; box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3) !important;"
                       title="Hitung Sisa Hasil Usaha Konsumsi">
                        <i class="fas fa-coins" style="font-size: 1.1rem;"></i>
                        <span class="d-none d-sm-inline">HITUNG SHU</span>
                    </a>
                    <a href="reports/konsumsi_laporan.php<?= $search ? '?search='.urlencode($search).'&month='.$selectedMonth.'&year='.$selectedYear : '?month='.$selectedMonth.'&year='.$selectedYear ?>" 
                       class="btn btn-sm shadow-sm" style="background: var(--primary-600); color: white; border-radius: 8px; padding: 0 14px; height: 42px; display: flex; align-items: center; gap: 6px; font-weight: 700; font-size: 0.75rem;"
                       title="Lihat Laporan Lengkap">
                        <i class="fas fa-file-alt"></i>
                        <span class="d-none d-sm-inline">LAPORAN</span>
                    </a>
                </div>
            </div>
            
            <div class="table-responsive" style="padding: 0;">
                <table class="table-clean-pro">
                    <thead>
                        <tr>
                            <th width="40" class="text-center">NO</th>
                            <th>NAMA & ID ANGGOTA</th>
                            <th class="text-right d-none d-md-table-cell">SALDO LALU</th>
                            <th class="text-right d-none d-md-table-cell">BATAS BELANJA</th>
                            <th class="text-right">SALDO AWAL</th>
                            <th width="140" class="text-center">EDIT LIMIT</th>
                            <th class="text-right">BELANJA</th>
                            <th class="text-right">PPN</th>
                            <th class="text-right">BELANJA+PPN</th>
                            <th class="text-right">SALDO AKHIR</th>
                            <th width="70" class="text-center">AKSI</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $no = 1;
                        $totalSaldoLalu = 0;
                        $totalPlafon = 0;
                        $totalSaldoAwal = 0;
                        $totalBelanja = 0;
                        $totalHargaAsli = 0;
                        $totalPpn = 0;
                        $totalSaldoAkhir = 0;
                        
                        foreach($displayData as $m): 
                        $totalSaldoLalu += $m['saldo_lalu'];
                        $totalPlafon += $m['plafon_ini'];
                        $totalSaldoAwal += $m['saldo_awal'];
                        $totalHargaAsli += (float)$m['total_harga_asli'];
                        $totalPpn += (float)$m['total_ppn'];
                        $totalBelanja += $m['total_belanja'];
                        $totalSaldoAkhir += $m['saldo_akhir'];
                        ?>
                        <tr class="align-middle member-row" data-member-id="<?= $m['id'] ?>">
                            <td class="text-center" style="color: var(--gray-300); font-weight: 700;"><?= $no++ ?></td>
                            <td>
                                <div class="member-info">
                                    <span class="member-name"><?= htmlspecialchars($m['nama']) ?></span>
                                    <span class="member-id"><?= $m['no_anggota'] ?></span>
                                </div>
                            </td>
                            <td class="text-right d-none d-md-table-cell" style="color: <?= $m['saldo_lalu'] >= 0 ? 'var(--success-600)' : 'var(--danger-600)' ?>;">
                                <?= formatRupiah($m['saldo_lalu']) ?>
                            </td>
                            <td class="text-right d-none d-md-table-cell" style="color: var(--warning-600); font-weight: 600;">
                                <?= formatRupiah($m['plafon_ini']) ?>
                            </td>
                            <td class="text-right fw-bold" style="color: var(--primary-600);">
                                <?= formatRupiah($m['saldo_awal']) ?>
                            </td>
                            <!-- EDIT LIMIT COLUMN -->
                            <td class="text-center edit-limit-cell">
                                <div class="limit-display" data-current-limit="<?= $m['plafon_ini'] ?>">
                                    <span class="current-limit fw-bold" style="color: var(--warning-600); cursor: pointer;" onclick="toggleEditLimit(this)">
                                        <?= formatRupiah($m['plafon_ini']) ?>
                                    </span>
                                    <form method="POST" class="edit-limit-form" style="display: none; margin-top: 8px;">
                                        <input type="hidden" name="action" value="update_limit_table">
                                        <input type="hidden" name="anggota_id" value="<?= $m['id'] ?>">
                                        <input type="text" name="new_limit" value="<?= formatRupiah($m['plafon_ini'], false) ?>" 
                                               class="form-control form-control-sm edit-limit-input text-right" 
                                               style="width: 100px; display: inline-block; margin-bottom: 4px;" 
                                               oninput="formatCurrencyInput(this)" required>
                                        <div class="d-flex gap-1 justify-content-center">
                                            <button type="submit" class="btn btn-success btn-sm px-2">
                                                <i class="fas fa-check"></i>
                                            </button>
                                            <button type="button" class="btn btn-secondary btn-sm px-2 cancel-edit" onclick="cancelEditLimit(this)">
                                                <i class="fas fa-times"></i>
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </td>
                            <td class="text-right" style="color: var(--gray-700);">
                                <?= formatRupiah($m['total_harga_asli']) ?>
                            </td>
                            <td class="text-right" style="color: var(--warning-600);">
                                <?= formatRupiah($m['total_ppn']) ?>
                            </td>
                            <td class="text-right" style="color: var(--gray-800); font-weight: 700;">
                                <?= formatRupiah($m['total_belanja']) ?>
                            </td>
                            <td class="text-right">
                                <span class="saldo-highlight px-3 py-2" style="font-size: 0.85rem; background: <?= $m['saldo_akhir'] >= 0 ? 'linear-gradient(135deg, var(--success-50) 0%, var(--success-100) 100%)' : 'linear-gradient(135deg, var(--danger-50) 0%, var(--danger-100) 100%)' ?>; color: <?= $m['saldo_akhir'] >= 0 ? 'var(--success-700)' : 'var(--danger-700)' ?>; border: 1px solid <?= $m['saldo_akhir'] >= 0 ? 'var(--success-200)' : 'var(--danger-200)' ?>; font-weight: 700;">
                                    <?= formatRupiah($m['saldo_akhir']) ?>
                                </span>
                            </td>
                            <td class="text-center">
                                <button type="button" class="btn-wa-minimal me-1" 
                                        onclick='sendWhatsAppNotification(<?= json_encode($m) ?>, <?= $selectedMonth ?>)'
                                        title="Kirim Notifikasi WA">
                                    <i class="fab fa-whatsapp"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (!empty($displayData)): ?>
                        <tr style="background: linear-gradient(135deg, #F8FAFC 0%, #F1F5F9 100%); color: var(--gray-900); font-weight: 800; border-top: 3px solid var(--primary-100); box-shadow: 0 -2px 8px rgba(0,0,0,0.05);">
                            <td colspan="2" class="text-center py-4" style="font-size: 0.75rem; color: var(--gray-600); letter-spacing: 0.1em;">
                                TOTAL REKAPITULASI (<?= $months[$selectedMonth] ?> <?= $selectedYear ?>)
                            </td>
                            <td class="text-right d-none d-md-table-cell" style="color: #64748b; font-size: 0.8rem;"><?= formatRupiah($totalSaldoLalu) ?></td>
                            <td class="text-right d-none d-md-table-cell" style="color: #64748b; font-size: 0.8rem;"><?= formatRupiah($totalPlafon) ?></td>
                            <td class="text-right fw-bold" style="color: var(--primary-600); font-size: 0.9rem;"><?= formatRupiah($totalSaldoAwal) ?></td>
                            <td class="text-center"> - </td>
                            <td class="text-right fw-bold" style="color: var(--gray-700); font-size: 0.9rem;"><?= formatRupiah($totalHargaAsli) ?></td>
                            <td class="text-right fw-bold" style="color: var(--warning-600); font-size: 0.9rem;"><?= formatRupiah($totalPpn) ?></td>
                            <td class="text-right fw-bold" style="color: var(--gray-800); font-size: 1rem;"><?= formatRupiah($totalBelanja) ?></td>
                            <td class="text-right">
                                <span class="saldo-highlight px-4 py-3" style="background: linear-gradient(135deg, var(--gray-800) 0%, var(--gray-900) 100%); color: white; border: 2px solid var(--gray-300); font-size: 1.1rem; font-weight: 900; min-width: 120px; display: inline-block; text-align: right; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
                                    <?= formatRupiah($totalSaldoAkhir) ?>
                                </span>
                            </td>
                            <td></td>
                        </tr>
                        <?php endif; ?>
                        <?php if (empty($displayData)): ?>
                            <tr><td colspan="10" class="text-center py-5 text-muted" style="font-style: italic;">Tidak ada data ditemukan untuk kriteria ini.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 3. Log Section (Transactions) -->
    <div class="col-md-12">
        <div class="pro-card">
            <div class="pro-card-header">
                <h3>
                    <i class="fas fa-history text-muted"></i>
                    Log Transaksi Terakhir
                </h3>
            </div>
            <div class="table-responsive">
                <table class="table-clean-pro">
                    <thead>
                        <tr>
                            <th width="120" style="background: linear-gradient(135deg, #64748b 0%, #475569 100%);">TANGGAL</th>
                            <th width="200" style="background: linear-gradient(135deg, #64748b 0%, #475569 100%);">ANGGOTA</th>
                            <th style="background: linear-gradient(135deg, #64748b 0%, #475569 100%);">BARANG / KETERANGAN</th>
                            <th class="text-right" width="140" style="background: linear-gradient(135deg, #64748b 0%, #475569 100%);">HARGA ASLI</th>
                            <th class="text-right" width="120" style="background: linear-gradient(135deg, #64748b 0%, #475569 100%);">PPN</th>
                            <th class="text-right" width="160" style="background: linear-gradient(135deg, #64748b 0%, #475569 100%);">HARGA JUAL</th>
                            <th width="100" class="text-center" style="background: linear-gradient(135deg, #64748b 0%, #475569 100%);">AKSI</th>
                        </tr>
                    </thead>
                        <tbody>
                            <?php 
                            $logTotalHargaAsli = 0;
                            $logTotalPPN = 0;
                            $logTotalHargaJual = 0;
                            foreach($recentTransactions as $t): 
                                $hargaAsli = (float)($t['harga_beli'] ?? 0);
                                $ppnPersen = (float)($t['ppn_persen'] ?? 0);
                                $ppnNominal = $hargaAsli * ($ppnPersen / 100);
                                $hargaJual = (float)($t['harga_jual'] ?? $t['jumlah_belanja'] ?? 0);
                                
                                // Skip total calculation if it's already negative to avoid double subtraction in display if needed, 
                                // but usually we sum everything as is.
                                $logTotalHargaAsli += $hargaAsli;
                                $logTotalPPN += $ppnNominal;
                                $logTotalHargaJual += $hargaJual;

                                $isKredit = $hargaJual < 0;
                                $displayHargaJual = abs($hargaJual);
                                $displayHargaAsli = abs($hargaAsli);
                                $displayPPN = abs($ppnNominal);
                            ?>
                            <tr class="align-middle">
                                <td style="font-size: 0.8rem; color: var(--gray-400); font-weight: 600;">
                                    <div class="d-flex flex-column">
                                        <span><?= date('d M Y', strtotime($t['tanggal'])) ?></span>
                                        <span style="font-size: 0.65rem; opacity: 0.7;"><?= date('H:i', strtotime($t['created_at'])) ?></span>
                                    </div>
                                </td>
                                <td>
                                    <?php if ($t['anggota_id']): ?>
                                        <div class="d-flex align-items-center" style="gap: 10px;">
                                            <div style="width: 32px; height: 32px; background: #EEF2FF; color: #4F46E5; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 12px;">
                                                <i class="fas fa-user-tag"></i>
                                            </div>
                                            <div>
                                                <div class="fw-bold" style="color: var(--gray-800); font-size: 0.85rem;"><?= htmlspecialchars($t['nama']) ?></div>
                                                <div style="font-size: 0.7rem; color: var(--gray-400);"><?= $t['no_anggota'] ?></div>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <div class="d-flex align-items-center" style="gap: 10px;">
                                            <div style="width: 32px; height: 32px; background: #FFF7ED; color: #EA580C; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 12px;">
                                                <i class="fas fa-globe"></i>
                                            </div>
                                            <div>
                                                <div class="fw-bold" style="color: #EA580C; font-size: 0.85rem;">PENGELUARAN UMUM</div>
                                                <div style="font-size: 0.7rem; color: var(--gray-400);">Tanpa Nama Anggota</div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center" style="gap: 8px;">
                                        <span class="badge" style="background: <?= $isKredit ? '#DCFCE7' : '#FEE2E2' ?>; color: <?= $isKredit ? '#166534' : '#B91C1C' ?>; font-size: 9px; padding: 4px 8px; font-weight: 800; border-radius: 6px;">
                                            <?= $isKredit ? 'KREDIT' : 'DEBET' ?>
                                        </span>
                                        <span style="font-size: 0.85rem; color: var(--gray-600);"><?= htmlspecialchars($t['nama_barang'] ?: '-') ?></span>
                                    </div>
                                </td>
                                <td class="text-right" style="color: var(--gray-500); font-size: 0.85rem;"><?= formatRupiah($displayHargaAsli) ?></td>
                                <td class="text-right" style="color: var(--gray-400); font-size: 0.85rem;"><?= $displayPPN > 0 ? formatRupiah($displayPPN) : '-' ?></td>
                                <td class="text-right fw-bold" style="color: <?= $isKredit ? '#10B981' : '#4F46E5' ?>; font-size: 0.95rem;">
                                    <?= ($isKredit ? '-' : '') . formatRupiah($displayHargaJual) ?>
                                </td>
                                <td class="text-center">
                                    <form method="POST" onsubmit="return confirm('Hapus transaksi ini?')" style="display:inline;">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $t['id'] ?>">
                                        <button type="submit" class="btn-wa-minimal" style="color: #EF4444; width: 32px; height: 32px; background: #FEF2F2; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center;" title="Hapus">
                                            <i class="fas fa-trash-alt" style="font-size: 0.9rem;"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr style="background: var(--gray-50); color: var(--gray-900); font-weight: 700; border-top: 1px solid var(--gray-200);">
                                <td colspan="3" class="text-center" style="font-size: 0.6rem; color: var(--gray-400); letter-spacing: 0.1em; padding: 12px;">TOTAL LOG TERAKHIR</td>
                                <td class="text-right" style="color: var(--gray-500); padding: 12px;"><?= formatRupiah($logTotalHargaAsli) ?></td>
                                <td class="text-right" style="color: var(--gray-500); padding: 12px;"><?= formatRupiah($logTotalPPN) ?></td>
                                <td class="text-right" style="color: var(--primary-700); padding: 12px;"><?= formatRupiah($logTotalHargaJual) ?></td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Modal -->
<div class="modal" id="addModal">
    <div class="modal-header pro-card-header">
        <h3><i class="fas fa-shopping-cart text-primary"></i> Input Belanja Baru</h3>
        <button class="modal-close" onclick="closeModal('addModal')"><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 pro-card-body">
            <div class="form-group mb-4">
                <label class="label-pro fw-bold mb-2 d-block">Pilih Anggota <span class="required text-danger">*</span></label>
                <div class="searchable-dropdown">
                    <div class="input-with-icon position-relative">
                        <i class="fas fa-user-tag icon-prefix position-absolute" style="left: 14px; top: 18px; color: var(--gray-400);"></i>
                        <input type="text" class="form-control pro-input pro-input-modal" name="anggota_search" id="modal_member_search_input" 
                               style="padding-left: 44px; height: 52px; border-radius: 12px; border: 1.5px solid var(--gray-200); width: 100%;"
                               placeholder="Cari Nama / No. Anggota..." autocomplete="off"
                               oninput="filterMemberDropdown(this)" onfocus="filterMemberDropdown(this)">
                    </div>
                    <input type="hidden" name="anggota_id" id="modal_member_id_hidden">
                    <div class="dropdown-results" id="modal_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-id-card"></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>
                            <span>Tidak ditemukan</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="form-group mb-4">
                <label class="label-pro fw-bold mb-2 d-block">Tanggal <span class="required text-danger">*</span></label>
                <div class="input-with-icon position-relative">
                    <i class="fas fa-calendar-alt icon-prefix position-absolute" style="left: 14px; top: 18px; color: var(--gray-400);"></i>
                    <input type="date" name="tanggal" class="form-control pro-input" style="padding-left: 44px; height: 52px; border-radius: 12px; border: 1.5px solid var(--gray-200); width: 100%;" required value="<?= date('Y-m-d') ?>">
                </div>
            </div>

            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                <label class="label-pro fw-bold" style="text-transform: uppercase; font-size: 0.75rem; color: var(--gray-400); letter-spacing: 0.05em;">Daftar Barang</label>
                <button type="button" class="btn btn-sm btn-outline-primary" style="border-radius: 8px;" onclick="addItemRowModal()">
                    <i class="fas fa-plus"></i> Tambah Baris
                </button>
            </div>

            <div id="modal-items-container">
                <div class="modal-item-row p-3 mb-3" style="background: var(--gray-50); border-radius: 14px; border: 1px solid var(--gray-100); position: relative;">
                    <div class="row g-2 mb-2">
                        <div class="col-12">
                            <input type="text" name="nama_barang[]" class="form-control pro-input" style="height: 44px; border-radius: 10px;" required placeholder="Nama Barang...">
                        </div>
                    </div>
                    <div class="row g-2">
                        <div class="col-9">
                            <input type="text" name="harga_beli[]" class="form-control pro-input modal-harga-beli" style="height: 44px; border-radius: 10px;" required placeholder="Harga Beli" oninput="formatCurrencyInput(this); calculateModalTotals();">
                        </div>
                        <div class="col-3 text-end" style="display: flex; flex-direction: column; justify-content: center;">
                            <span style="font-size: 0.6rem; color: var(--gray-400); text-transform: uppercase; font-weight: 700;">Subtotal</span>
                            <span class="modal-subtotal fw-bold" style="font-size: 0.85rem; color: var(--primary-600);">Rp 0</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="form-group mb-4">
                <label class="label-pro fw-bold mb-2 d-block">Catatan</label>
                <textarea name="keterangan" class="form-control pro-input" style="border-radius: 12px; border: 1.5px solid var(--gray-200); width: 100%;" rows="2" placeholder="Catatan tambahan..."></textarea>
            </div>

            <div class="form-group mb-4">
                <label class="label-pro fw-bold mb-2 d-block">PPN Global (%)</label>
                <input type="number" name="ppn_persen_global" class="form-control pro-input" style="height: 52px; border-radius: 12px; border: 1.5px solid var(--gray-200); width: 100%;" value="0" step="0.01" placeholder="0" oninput="calculateModalTotals()">
            </div>

            <div class="price-container" style="background: var(--primary-50); padding: 20px; border-radius: 16px; border: 1px solid var(--primary-100);">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span class="label-pro fw-bold" style="color: var(--primary-700); text-transform: uppercase; font-size: 0.7rem;">Estimasi Grand Total</span>
                    <div class="display-total-large" style="box-shadow: none; border: none; background: transparent; padding: 0;">
                        <span class="currency" style="font-size: 1rem;">Rp</span>
                        <span id="modal_grand_total" class="fw-bold" style="font-size: 1.5rem; color: var(--primary-700);">0</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer" style="padding: 24px 32px; border-top: 1px solid var(--gray-100);">
            <button type="button" class="btn btn-outline" style="padding: 12px 24px; border-radius: 10px;" onclick="closeModal('addModal')">Batal</button>
            <button type="submit" class="btn btn-primary" style="padding: 12px 32px; border-radius: 10px; font-weight: 700;">Simpan Transaksi</button>
        </div>
        <div class="modal-footer" style="padding: 24px 32px; border-top: 1px solid var(--gray-100);">
            <button type="button" class="btn btn-outline" style="padding: 12px 24px; border-radius: 10px;" onclick="closeModal('addModal')">Batal</button>
            <button type="submit" class="btn btn-primary" style="padding: 12px 32px; border-radius: 10px; font-weight: 700;">Simpan Transaksi</button>
        </div>
    </form>
</div>

<!-- Edit Konsumsi Modal -->
<div class="modal" id="editKonsumsiModal">
    <div class="modal-header pro-card-header">
        <h3><i class="fas fa-edit text-primary"></i> Edit Transaksi</h3>
        <button class="modal-close" onclick="closeModal('editKonsumsiModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="update_konsumsi">
        <input type="hidden" name="id" id="edit_konsumsi_id">
        <div class="modal-body pro-card-body">
            <div class="form-group mb-4">
                <label class="label-pro fw-bold mb-2 d-block">Anggota (Read Only)</label>
                <input type="text" id="edit_konsumsi_anggota_nama" class="form-control pro-input" 
                       style="height: 52px; border-radius: 12px; border: 1.5px solid var(--gray-100); background: var(--gray-50); color: var(--gray-500); width: 100%;" readonly>
            </div>
            
            <div class="row g-3">
                <div class="col-md-6 mb-4">
                    <label class="label-pro fw-bold mb-2 d-block">Tanggal <span class="required text-danger">*</span></label>
                    <input type="date" name="tanggal" id="edit_konsumsi_tanggal" class="form-control pro-input" 
                           style="height: 52px; border-radius: 12px; border: 1.5px solid var(--gray-200); width: 100%;" required>
                </div>
                <div class="col-md-6 mb-4">
                    <label class="label-pro fw-bold mb-2 d-block">Nama Barang <span class="required text-danger">*</span></label>
                    <input type="text" name="nama_barang" id="edit_konsumsi_nama_barang" class="form-control pro-input" 
                           style="height: 52px; border-radius: 12px; border: 1.5px solid var(--gray-200); width: 100%;" required>
                </div>
            </div>

            <div class="row g-3">
                <div class="col-md-8 mb-4">
                    <label class="label-pro fw-bold mb-2 d-block">Harga Beli Dasar (Rp)</label>
                    <div class="input-with-icon position-relative">
                        <span class="icon-prefix fw-bold position-absolute" style="left: 14px; top: 15px; color: var(--gray-500);">Rp</span>
                        <input type="text" name="harga_beli" id="edit_konsumsi_harga_beli" class="form-control pro-input" 
                               style="padding-left: 44px; height: 52px; border-radius: 12px; border: 1.5px solid var(--gray-200); width: 100%;" required 
                               oninput="formatCurrencyInput(this); calculateEditKonsumsiHargaJual();">
                    </div>
                </div>
                <div class="col-md-4 mb-4">
                    <label class="label-pro fw-bold mb-2 d-block">PPN (%)</label>
                    <input type="number" name="ppn_persen" id="edit_konsumsi_ppn_persen" class="form-control pro-input" 
                           style="height: 52px; border-radius: 12px; border: 1.5px solid var(--gray-200); width: 100%;" value="0" step="1"
                           oninput="calculateEditKonsumsiHargaJual();">
                </div>
            </div>

            <div class="price-container" style="background: var(--success-50); padding: 24px; border-radius: 16px; border: 1px solid var(--success-100);">
                <label class="label-pro fw-bold mb-2 d-block" style="color: var(--success-700); text-transform: uppercase; font-size: 0.7rem; letter-spacing: 0.05em;">Total Harga Jual (Baru)</label>
                <div class="display-total-large" style="box-shadow: none; border: none; background: transparent;">
                    <span class="currency" style="color: var(--success-600);">Rp</span>
                    <input type="text" name="harga_jual" id="edit_konsumsi_harga_jual" class="total-input-pro" style="color: var(--success-700);" readonly value="0">
                </div>
            </div>
        </div>
        <div class="modal-footer" style="padding: 24px 32px; border-top: 1px solid var(--gray-100);">
            <button type="button" class="btn btn-outline" style="padding: 12px 24px; border-radius: 10px;" onclick="closeModal('editKonsumsiModal')">Batal</button>
            <button type="submit" class="btn btn-primary" style="padding: 12px 32px; border-radius: 10px; font-weight: 700; background: var(--success-600);">Simpan Perubahan</button>
        </div>
    </form>
</div>

<!-- Setting Limit Modal -->
<div class="modal" id="settingLimitModal">
    <div class="modal-header pro-card-header">
        <h3><i class="fas fa-cog text-primary"></i> Pengaturan Batas Belanja</h3>
        <button class="modal-close" onclick="closeModal('settingLimitModal')"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body pro-card-body" style="padding: 24px 32px;">
        <!-- Tab Navigation -->
        <div class="d-flex gap-2 mb-4 border-bottom" style="border-bottom: 2px solid var(--gray-100);">
            <button type="button" class="tab-btn active" onclick="switchTab('tab-monthly')" 
                    style="padding: 12px 20px; border: none; background: none; cursor: pointer; border-bottom: 3px solid var(--primary-600); color: var(--primary-600); font-weight: 700;">
                <i class="fas fa-calendar-alt me-2"></i> Batas Per Bulan
            </button>
            <button type="button" class="tab-btn" onclick="switchTab('tab-member')"
                    style="padding: 12px 20px; border: none; background: none; cursor: pointer; color: var(--gray-500); font-weight: 600;">
                <i class="fas fa-user me-2"></i> Per Anggota
            </button>
        </div>

        <!-- Tab: Monthly Limits -->
        <div id="tab-monthly" class="tab-content">
            <div class="alert alert-info mb-4" style="border-radius: 12px;">
                <i class="fas fa-info-circle"></i> 
                Atur batas belanja untuk setiap bulan. Batas belanja yang sama berlaku untuk semua anggota di bulan tersebut (kecuali ada override per anggota). Masukkan <strong>0</strong> jika tidak diizinkan ada belanja di bulan tersebut.
            </div>
            
            <form method="POST" id="form-monthly-limits">
                <input type="hidden" name="action" value="update_limit">
                <input type="hidden" name="bulan" id="monthly_bulan">
                
                <div class="row g-3">
                    <?php 
                    $monthsArray = [
                        1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
                        5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
                        9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
                    ];
                    foreach ($monthsArray as $bulan => $namaBulan): 
                        $limitBulan = getKonsumsiLimitBulanan($bulan);
                    ?>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="fw-bold mb-2 d-block" style="font-size: 0.9rem;"><?= $namaBulan ?></label>
                            <div class="input-with-icon position-relative">
                                <span class="icon-prefix fw-bold position-absolute" style="left: 14px; top: 13px; color: var(--gray-500); font-size: 0.9rem;">Rp</span>
                                <input type="text" class="form-control monthly-limit-input" 
                                       data-bulan="<?= $bulan ?>"
                                       style="padding-left: 44px; height: 48px; border-radius: 10px; border: 1.5px solid var(--gray-200); width: 100%;"
                                       placeholder="50000" oninput="formatCurrencyInput(this)"
                                       value="<?= formatRupiah($limitBulan, false) ?>">
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <div style="margin-top: 24px; display: flex; justify-content: flex-end; gap: 12px;">
                    <button type="button" class="btn btn-outline" style="padding: 12px 24px; border-radius: 10px;" onclick="closeModal('settingLimitModal')">Batal</button>
                    <button type="button" class="btn btn-primary" style="padding: 12px 32px; border-radius: 10px; font-weight: 700;" onclick="saveMonthlyLimits()">
                        <i class="fas fa-save me-2"></i> Simpan Semua Bulan
                    </button>
                </div>
            </form>
        </div>

        <!-- Tab: Per-Member Limits -->
        <div id="tab-member" class="tab-content" style="display: none;">
            <div class="alert alert-info mb-4" style="border-radius: 12px;">
                <i class="fas fa-info-circle"></i> 
                Tetapkan batas belanja khusus untuk anggota (opsional). Kosongkan untuk menggunakan batas belanja bulan.
            </div>

            <form method="POST" id="form-member-limit">
                <input type="hidden" name="action" value="update_limit_anggota">
                <input type="hidden" name="bulan" value="<?= $selectedMonth ?>">
                <input type="hidden" name="anggota_id" id="member_limit_anggota_id">

                <div class="form-group mb-4">
                    <label class="fw-bold mb-2 d-block">Pilih Anggota</label>
                    <div style="position: relative;">
                        <input type="text" id="member_limit_search" class="form-control pro-input" 
                               placeholder="Cari nama atau no. anggota..." 
                               style="height: 48px; border-radius: 10px;"
                               oninput="memberLimitFilterDropdown(this)">
                        <div id="member_limit_results" class="dropdown-results" style="top: calc(100% + 5px); position: absolute; width: 100%; max-height: 200px; overflow-y: auto; display: none; z-index: 1000;">
                            <?php foreach ($anggotaList as $a): ?>
                                <div class="dropdown-item" data-id="<?= $a['id'] ?>" data-text="<?= htmlspecialchars($a['no_anggota'] . ' - ' . $a['nama']) ?>" style="padding: 10px 15px; cursor: pointer;">
                                    <span><?= htmlspecialchars($a['no_anggota'] . ' - ' . $a['nama']) ?></span>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="form-group mb-4">
                    <label class="fw-bold mb-2 d-block">Batas Belanja (Rp) - <?= $months[$selectedMonth] ?></label>
                    <div class="input-with-icon position-relative">
                        <span class="icon-prefix fw-bold position-absolute" style="left: 14px; top: 15px; color: var(--gray-500);">Rp</span>
                        <input type="text" name="batas_anggota" id="member_limit_input"
                               style="padding-left: 44px; height: 52px; border-radius: 12px; border: 1.5px solid var(--gray-200); width: 100%;"
                               placeholder="Kosongkan untuk menggunakan limit bulan" oninput="formatCurrencyInput(this)">
                    </div>
                    <small class="text-muted mt-2 d-block">
                        Batas bulan ini: <strong><?= formatRupiah($batasBulanan) ?></strong>
                    </small>
                </div>

                <div style="display: flex; justify-content: flex-end; gap: 12px;">
                    <button type="button" class="btn btn-outline" style="padding: 12px 24px; border-radius: 10px;" onclick="closeModal('settingLimitModal')">Batal</button>
                    <button type="submit" class="btn btn-primary" style="padding: 12px 32px; border-radius: 10px; font-weight: 700;">
                        <i class="fas fa-save me-2"></i> Simpan Batas Anggota
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- WhatsApp Preview Modal -->
<div class="modal" id="waPreviewModal">
    <div class="modal-header pro-card-header">
        <h3><i class="fab fa-whatsapp text-success"></i> Preview Notifikasi</h3>
        <button class="modal-close" onclick="closeModal('waPreviewModal')"><i class="fas fa-times"></i></button>
    </div>
    <div class="modal-body pro-card-body">
        <div class="alert alert-info mb-4" style="border-radius: 12px; font-size: 0.85rem;">
            <i class="fas fa-info-circle"></i> Tinjau atau edit pesan sebelum dikirim ke nomor WhatsApp anggota.
        </div>
        <div class="form-group mb-4">
            <label class="label-pro fw-bold mb-2 d-block">Penerima</label>
            <div class="d-flex align-items-center" style="background: #f8fafc; padding: 10px 15px; border-radius: 10px; border: 1px solid #e2e8f0;">
                <i class="fas fa-user-circle me-3 text-muted" style="font-size: 1.2rem;"></i>
                <div>
                    <div class="fw-bold" id="wa_preview_name" style="font-size: 0.9rem; color: #1e293b;">-</div>
                    <div id="wa_preview_phone" class="text-muted small">-</div>
                </div>
            </div>
        </div>
        <div class="form-group mb-1">
            <label class="label-pro fw-bold mb-2 d-block">Pesan WhatsApp</label>
            <textarea id="wa_preview_message" class="form-control pro-input" 
                      style="height: 200px; border-radius: 12px; border: 1.5px solid var(--gray-200); width: 100%; font-size: 0.9rem; line-height: 1.5; padding: 15px;" 
                      placeholder="Tulis pesan..."></textarea>
            <p class="text-muted small mt-2"><i class="fas fa-keyboard"></i> Anda dapat mengedit teks di atas secara bebas.</p>
        </div>
    </div>
    <input type="hidden" id="wa_target_phone">
    <div class="modal-footer" style="padding: 24px 32px; border-top: 1px solid var(--gray-100);">
        <button type="button" class="btn btn-outline" style="padding: 12px 24px; border-radius: 10px;" onclick="closeModal('waPreviewModal')">Batal</button>
        <button type="button" class="btn btn-primary" onclick="sendFinalWhatsApp()" style="padding: 12px 32px; border-radius: 10px; font-weight: 700; background: #25D366; border: none; box-shadow: 0 4px 12px rgba(37, 211, 102, 0.3);">
            <i class="fab fa-whatsapp me-2"></i> KIRIM SEKARANG
        </button>
    </div>
</div>

<script>
function sendWhatsAppNotification(member, month) {
    const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
    const monthName = months[month - 1];
    
    // Format money for the message
    const remaining = parseFloat(member.saldo_akhir) || 0;
    const remainingStr = new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 }).format(Math.abs(remaining));
    
    let message = `Assalamu'alaikum, Bapak/Ibu *${member.nama}*,\n\nKami menginformasikan bahwa sisa batas belanja konsumsi Anda untuk bulan *${monthName}* adalah sebesar *${remainingStr}*.\n\nSilahkan List belanja dibawah\n1. \n2.\n\nMohon untuk diperhatikan agar total belanja tidak melebihi batas yang ditentukan. Terima kasih.`;
    
    if (remaining < 0) {
        message = `Assalamu'alaikum, Bapak/Ibu *${member.nama}*,\n\nKami menginformasikan bahwa belanja konsumsi Anda untuk bulan *${monthName}* telah *MELEBIHI BATAS* sebesar *${remainingStr}*.\n\nMohon segera melakukan penyesuaian. Terima kasih.`;
    }

    const phone = member.telepon ? member.telepon.replace(/[^0-9]/g, '') : '';
    if (!phone) {
        alert('Nomor telepon anggota tidak tersedia!');
        return;
    }
    
    let processedPhone = phone;
    if (processedPhone.startsWith('0')) {
        processedPhone = '62' + processedPhone.substring(1);
    }
    
    // Fill Preview Modal
    document.getElementById('wa_preview_name').innerText = member.nama;
    document.getElementById('wa_preview_phone').innerText = '+' + processedPhone;
    document.getElementById('wa_target_phone').value = processedPhone;
    document.getElementById('wa_preview_message').value = message;
    
    openModal('waPreviewModal');
}

function sendFinalWhatsApp() {
    const phone = document.getElementById('wa_target_phone').value;
    const message = document.getElementById('wa_preview_message').value;
    
    const url = `https://api.whatsapp.com/send?phone=${phone}&text=${encodeURIComponent(message)}`;
    window.open(url, '_blank');
    closeModal('waPreviewModal');
}

function updatePeriod(searchStr = null) {
    const m = document.getElementById('filter_month').value;
    const y = document.getElementById('filter_year').value;
    const s = searchStr !== null ? searchStr : document.querySelector('.search-box-pro input') ? document.querySelector('.search-box-pro input').value : '';
    window.location = `konsumsi.php?month=${m}&year=${y}&search=${encodeURIComponent(s)}`;
}

function updatePeriodFromHeader() {
    const m = document.getElementById('input_header_month').value;
    const y = document.getElementById('input_header_year').value;
    window.location.href = `konsumsi.php?month=${m}&year=${y}`;
}

function filterMemberDropdown(input) {
    const filter = input.value.toLowerCase();
    const container = input.closest('.searchable-dropdown');
    const results = container.querySelector('.dropdown-results');
    const items = results.querySelectorAll('.dropdown-item:not(.no-results)');
    const noResults = results.querySelector('.no-results');
    
    // Show results contextually
    if (filter.length > 0) {
        results.classList.add('active');
    } else {
        results.classList.remove('active');
        return;
    }

    let matchCount = 0;
    let firstMatch = null;

    items.forEach(item => {
        const text = item.getAttribute('data-text').toLowerCase();
        if (text.includes(filter)) {
            item.style.display = 'flex';
            item.classList.remove('best-suggestion');
            if (matchCount === 0) {
                firstMatch = item;
                item.classList.add('best-suggestion'); // Highlight the single best suggestion
            }
            matchCount++;
        } else {
            item.style.display = 'none';
        }
    });

    if (matchCount === 0) {
        noResults.style.display = 'flex';
    } else {
        noResults.style.display = 'none';
        // If the user hasn't added a "Best Suggestion" header, we could add one here but let's stick to highlighting
    }
}

// Add handling for Enter key to pick the 'best-suggestion'
document.addEventListener('keydown', function(e) {
    if (e.key === 'Enter') {
        const activeDropdown = document.querySelector('.dropdown-results.active');
        if (activeDropdown) {
            const best = activeDropdown.querySelector('.best-suggestion');
            if (best && best.style.display !== 'none') {
                e.preventDefault();
                best.click();
            }
        }
    }
});

document.addEventListener('click', 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"]');
        const list = container.querySelector('.dropdown-results');
        input.value = item.getAttribute('data-text');
        hidden.value = item.getAttribute('data-id');
        list.classList.remove('active');
    }
    if (!e.target.closest('.searchable-dropdown')) {
        document.querySelectorAll('.dropdown-results.active').forEach(list => {
            list.classList.remove('active');
        });
    }
});

function validateSearchableDropdown(form) {
    const hiddenId = form.querySelector('input[type="hidden"][name="anggota_id"]');
    if (!hiddenId || !hiddenId.value) {
        alert('Mohon pilih Anggota dari daftar yang tersedia.');
        const input = form.querySelector('input[name="anggota_search"]');
        if (input) input.focus();
        return false;
    }
    return true;
}

function openModal(id) { document.getElementById(id).classList.add('active'); }
function closeModal(id) { document.getElementById(id).classList.remove('active'); }

function addItemRow() {
    const container = document.getElementById('items-container');
    const firstRow = container.querySelector('.item-row');
    const newRow = firstRow.cloneNode(true);
    
    // Clear inputs in the new row
    newRow.querySelectorAll('input').forEach(input => {
        input.value = '';
    });
    newRow.querySelector('.subtotal-val').innerText = 'Rp 0';
    
    // Add remove button if it's not the only row
    if (!newRow.querySelector('.remove-item-btn')) {
        const removeBtn = document.createElement('button');
        removeBtn.type = 'button';
        removeBtn.className = 'btn btn-icon remove-item-btn';
        removeBtn.style = 'position: absolute; top: 10px; right: 10px; color: var(--danger-500); background: white; border-radius: 50%; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; box-shadow: var(--shadow-sm); border: 1px solid var(--gray-100);';
        removeBtn.innerHTML = '<i class="fas fa-times" style="font-size: 0.7rem;"></i>';
        removeBtn.onclick = function() {
            newRow.remove();
            calculateTotals();
        };
        newRow.appendChild(removeBtn);
    }
    
    container.appendChild(newRow);
}

function addItemRowModal() {
    const container = document.getElementById('modal-items-container');
    const firstRow = container.querySelector('.modal-item-row');
    const newRow = firstRow.cloneNode(true);
    
    newRow.querySelectorAll('input').forEach(input => {
        input.value = '';
    });
    newRow.querySelector('.modal-subtotal').innerText = 'Rp 0';
    
    if (!newRow.querySelector('.remove-item-btn')) {
        const removeBtn = document.createElement('button');
        removeBtn.type = 'button';
        removeBtn.className = 'btn btn-icon remove-item-btn';
        removeBtn.style = 'position: absolute; top: -8px; right: -8px; color: var(--danger-500); background: white; border-radius: 50%; width: 22px; height: 22px; display: flex; align-items: center; justify-content: center; box-shadow: var(--shadow-sm); border: 1px solid var(--gray-100); z-index: 10;';
        removeBtn.innerHTML = '<i class="fas fa-times" style="font-size: 0.6rem;"></i>';
        removeBtn.onclick = function() {
            newRow.remove();
            calculateModalTotals();
        };
        newRow.appendChild(removeBtn);
    }
    
    container.appendChild(newRow);
}

function calculateTotals() {
    let totalHargaBeli = 0;
    document.querySelectorAll('#items-container .item-row').forEach(row => {
        const hargaBeliStr = row.querySelector('.harga-beli-input').value.replace(/\./g, '');
        
        if (hargaBeliStr) {
            const hargaBeli = parseFloat(hargaBeliStr);
            row.querySelector('.subtotal-val').innerText = 'Rp ' + hargaBeli.toLocaleString('id-ID');
            totalHargaBeli += hargaBeli;
        } else {
            row.querySelector('.subtotal-val').innerText = 'Rp 0';
        }
    });
    
    // Calculate global PPN
    const globalPpnPersen = parseFloat(document.querySelector('input[name="ppn_persen_global"]').value) || 0;
    const ppnNominal = Math.round(totalHargaBeli * (globalPpnPersen / 100));
    const grandTotal = totalHargaBeli + ppnNominal;
    
    document.getElementById('grand_total_display').innerText = grandTotal.toLocaleString('id-ID');
}

function calculateModalTotals() {
    let totalHargaBeli = 0;
    document.querySelectorAll('#modal-items-container .modal-item-row').forEach(row => {
        const hargaBeliStr = row.querySelector('.modal-harga-beli').value.replace(/\./g, '');
        
        if (hargaBeliStr) {
            const hargaBeli = parseFloat(hargaBeliStr);
            row.querySelector('.modal-subtotal').innerText = 'Rp ' + hargaBeli.toLocaleString('id-ID');
            totalHargaBeli += hargaBeli;
        } else {
            row.querySelector('.modal-subtotal').innerText = 'Rp 0';
        }
    });
    
    // Calculate global PPN
    const globalPpnPersen = parseFloat(document.querySelector('input[name="ppn_persen_global"]').value) || 0;
    const ppnNominal = Math.round(totalHargaBeli * (globalPpnPersen / 100));
    const grandTotal = totalHargaBeli + ppnNominal;
    
    document.getElementById('modal_grand_total').innerText = grandTotal.toLocaleString('id-ID');
}

function calculateEditKonsumsiHargaJual() {
    const hargaBeliStr = document.getElementById('edit_konsumsi_harga_beli').value.replace(/\./g, '');
    const ppnPersenStr = document.getElementById('edit_konsumsi_ppn_persen').value;
    if (hargaBeliStr) {
        const hargaBeli = parseFloat(hargaBeliStr);
        const ppnPersen = parseFloat(ppnPersenStr) || 0;
        const hargaJual = Math.round(hargaBeli + (hargaBeli * (ppnPersen / 100)));
        document.getElementById('edit_konsumsi_harga_jual').value = hargaJual.toLocaleString('id-ID');
    }
}

function openEditKonsumsiModal(data) {
    document.getElementById('edit_konsumsi_id').value = data.id;
    document.getElementById('edit_konsumsi_anggota_nama').value = data.no_anggota + ' - ' + data.nama;
    document.getElementById('edit_konsumsi_tanggal').value = data.tanggal;
    document.getElementById('edit_konsumsi_nama_barang').value = data.nama_barang;
    document.getElementById('edit_konsumsi_harga_beli').value = data.harga_beli.toLocaleString('id-ID');
    document.getElementById('edit_konsumsi_ppn_persen').value = data.ppn_persen;
    
    calculateEditKonsumsiHargaJual();
    openModal('editKonsumsiModal');
}

/* Tab switching for settings modal */
function switchTab(tabName) {
    // Hide all tabs
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.style.display = 'none';
    });
    
    // Remove active state from all buttons
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
        btn.style.color = 'var(--gray-500)';
        btn.style.borderBottom = 'none';
    });
    
    // Show selected tab
    document.getElementById(tabName).style.display = 'block';
    
    // Mark button as active
    event.target.closest('.tab-btn').classList.add('active');
    event.target.closest('.tab-btn').style.color = 'var(--primary-600)';
    event.target.closest('.tab-btn').style.borderBottom = '3px solid var(--primary-600)';
}

/* Save all monthly limits */
function saveMonthlyLimits() {
    const monthsArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
    let isValid = true;
    
    // Validate all inputs
    document.querySelectorAll('.monthly-limit-input').forEach(input => {
        const value = input.value.replace(/\./g, '').trim();
        if (!value || isNaN(value) || value < 0) {
            input.style.borderColor = 'var(--danger-500)';
            isValid = false;
        } else {
            input.style.borderColor = 'var(--gray-200)';
        }
    });
    
    if (!isValid) {
        alert('Mohon isi semua bulan dengan nilai valid (≥ 0). Nilai 0 berarti tidak ada belanja di bulan tersebut.');
        return;
    }
    
    // Submit each month's limit
    const form = document.getElementById('form-monthly-limits');
    monthsArray.forEach(bulan => {
        const input = document.querySelector(`.monthly-limit-input[data-bulan="${bulan}"]`);
        const value = input.value.replace(/\./g, '');
        
        // Create hidden form and submit
        const hiddenForm = document.createElement('form');
        hiddenForm.method = 'POST';
        hiddenForm.style.display = 'none';
        
        const actionInput = document.createElement('input');
        actionInput.type = 'hidden';
        actionInput.name = 'action';
        actionInput.value = 'update_limit';
        
        const bulanInput = document.createElement('input');
        bulanInput.type = 'hidden';
        bulanInput.name = 'bulan';
        bulanInput.value = bulan;
        
        const limitInput = document.createElement('input');
        limitInput.type = 'hidden';
        limitInput.name = 'new_limit';
        limitInput.value = value;
        
        hiddenForm.appendChild(actionInput);
        hiddenForm.appendChild(bulanInput);
        hiddenForm.appendChild(limitInput);
        document.body.appendChild(hiddenForm);
        
        // Submit with slight delay to avoid race conditions
        setTimeout(() => {
            hiddenForm.submit();
        }, bulan * 100);
    });
}

/* Filter member dropdown for per-member limits */
function memberLimitFilterDropdown(input) {
    const filter = input.value.toLowerCase();
    const results = document.getElementById('member_limit_results');
    const items = results.querySelectorAll('.dropdown-item');
    
    if (filter.length > 0) {
        results.style.display = 'block';
    } else {
        results.style.display = 'none';
        return;
    }
    
    let matchCount = 0;
    items.forEach(item => {
        const text = item.getAttribute('data-text').toLowerCase();
        if (text.includes(filter)) {
            item.style.display = 'flex';
            matchCount++;
        } else {
            item.style.display = 'none';
        }
    });
    
    if (matchCount === 0) {
        results.style.display = 'none';
    }
}

/* INLINE EDIT LIMIT FUNCTIONS */
function toggleEditLimit(displaySpan) {
    const cell = displaySpan.closest('.edit-limit-cell');
    const display = cell.querySelector('.limit-display .current-limit');
    const form = cell.querySelector('.edit-limit-form');
    
    // Hide display, show form
    display.style.display = 'none';
    form.style.display = 'block';
    
    // Focus input
    const input = form.querySelector('.edit-limit-input');
    input.focus();
    input.select();
    
    // Add row highlight
    const row = cell.closest('.member-row');
    row.style.backgroundColor = 'var(--primary-50)';
    row.style.transition = 'background-color 0.3s ease';
}

function cancelEditLimit(cancelBtn) {
    const form = cancelBtn.closest('.edit-limit-form');
    const cell = form.closest('.edit-limit-cell');
    const display = cell.querySelector('.limit-display .current-limit');
    
    // Show display, hide form
    form.style.display = 'none';
    display.style.display = 'inline';
    
    // Reset input value
    const input = form.querySelector('.edit-limit-input');
    input.value = display.dataset.currentLimit.replace(/\./g, '');
    
    // Remove row highlight
    const row = cell.closest('.member-row');
    row.style.backgroundColor = '';
}

// Global currency formatter
function formatCurrencyInput(input) {
    let value = input.value.replace(/[^\d]/g, '');
    if (value === '') {
        input.value = '';
        return;
    }
    input.value = parseInt(value).toLocaleString('id-ID');
}

// Handle form submissions with loading state
document.addEventListener('submit', function(e) {
    if (e.target.matches('.edit-limit-form')) {
        const submitBtn = e.target.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        
        // Add loading state
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        submitBtn.disabled = true;
        
        // Show processing message (will reload page)
        setTimeout(() => {
            // Page will reload after POST, no need for more
        }, 500);
    }
});

// Cancel edit on Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        document.querySelectorAll('.edit-limit-form').forEach(form => {
            form.style.display = 'none';
            const cell = form.closest('.edit-limit-cell');
            const display = cell.querySelector('.current-limit');
            display.style.display = 'inline';
            const row = cell.closest('.member-row');
            row.style.backgroundColor = '';
        });
    }
});

// Prevent Enter from submitting on input (use Tab or buttons)
document.querySelectorAll('.edit-limit-input').forEach(input => {
    input.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            this.closest('form').querySelector('button[type="submit"]').click();
        }
    });
});

// Re-apply after potential dynamic content (though page reloads)
function initEditListeners() {
    document.querySelectorAll('.current-limit').forEach(span => {
        span.onclick = function() { toggleEditLimit(this); };
    });
}

document.addEventListener('DOMContentLoaded', function() {
    initEditListeners();
});

/* Handle member selection for limit override */
document.addEventListener('click', function(e) {
    if (e.target.closest('#member_limit_results .dropdown-item')) {
        const item = e.target.closest('.dropdown-item');
        const memberId = item.getAttribute('data-id');
        const memberText = item.getAttribute('data-text');
        
        document.getElementById('member_limit_search').value = memberText;
        document.getElementById('member_limit_anggota_id').value = memberId;
        document.getElementById('member_limit_results').style.display = 'none';
    }
    
    if (!e.target.closest('#member_limit_search') && !e.target.closest('#member_limit_results')) {
        document.getElementById('member_limit_results').style.display = 'none';
    }
});

document.addEventListener('DOMContentLoaded', function() {
    calculateTotals();
    
    // Inline edit functionality
    document.querySelectorAll('.btn-table-edit').forEach(btn => {
        btn.addEventListener('click', function() {
            const cell = this.closest('td');
            const editForm = cell.querySelector('.edit-form');
            const btnEdit = cell.querySelector('.btn-table-edit');
            
            btnEdit.style.display = 'none';
            editForm.style.display = 'inline-block';
        });
    });
    
    document.addEventListener('click', function(e) {
        if (e.target.closest('.cancel-edit')) {
            const cell = e.target.closest('.td');
            const editForm = cell.querySelector('.edit-form');
            const btnEdit = cell.querySelector('.btn-table-edit');
            
            editForm.style.display = 'none';
            btnEdit.style.display = 'inline-block';
        }
    });
});
</script>

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

