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

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

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

$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'
];

$batasBulanan = (float)getSetting('batas_konsumsi_bulanan', 50000);

// Function to calculate rolling balance
function calculateRollingBalance($db, $memberId, $targetMonth, $targetYear, $batasBulanan, $joinDate) {
    $joinYear = (int)date('Y', strtotime($joinDate));
    $joinMonth = (int)date('n', strtotime($joinDate));
    if ($joinYear < 2026 || ($joinYear == 2026 && $joinMonth < 3)) { 
        $joinYear = 2026; 
        $joinMonth = 3; 
    }
    
    $balance = 0;
    $currentYear = $joinYear;
    $currentMonth = $joinMonth;
    
    while (true) {
        $stmt = $db->prepare("
            SELECT COALESCE(SUM(jumlah_belanja), 0) as spending 
            FROM konsumsi_transaksi 
            WHERE anggota_id = ? AND MONTH(tanggal) = ? AND YEAR(tanggal) = ?
        ");
        $stmt->execute([$memberId, $currentMonth, $currentYear]);
        $spending = (float)$stmt->fetchColumn();
        
        $balance = $balance + $batasBulanan - $spending;
        
        if ($currentYear == $targetYear && $currentMonth == $targetMonth) {
            break;
        }
        
        $currentMonth++;
        if ($currentMonth > 12) {
            $currentMonth = 1;
            $currentYear++;
        }
    }
    
    return $balance;
}

// Fetch member summaries
$queryMembers = "
    SELECT a.id, a.nama, a.no_anggota, a.telepon, a.tanggal_daftar,
    (SELECT COALESCE(SUM(jumlah_belanja), 0) FROM konsumsi_transaksi 
     WHERE anggota_id = a.id 
     AND MONTH(tanggal) = ? 
     AND YEAR(tanggal) = ?) as total_belanja_bulan_ini,
    (SELECT COALESCE(SUM(harga_beli), 0) FROM konsumsi_transaksi 
     WHERE anggota_id = a.id 
     AND MONTH(tanggal) = ? 
     AND YEAR(tanggal) = ?) as total_harga_asli,
    (SELECT COALESCE(SUM(harga_beli * (ppn_persen/100)), 0) FROM konsumsi_transaksi 
     WHERE anggota_id = a.id 
     AND MONTH(tanggal) = ? 
     AND YEAR(tanggal) = ?) as total_ppn
    FROM anggota a
";

$params = [$selectedMonth, $selectedYear, $selectedMonth, $selectedYear, $selectedMonth, $selectedYear];
$where = " WHERE 1=1";
if ($search) {
    $where = " WHERE (a.nama LIKE ? OR a.no_anggota LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$stmt = $db->prepare($queryMembers . $where . " ORDER BY a.nama ASC");
$stmt->execute($params);
$rawData = $stmt->fetchAll();

// Process data with rolling balance calculation
$data = [];
foreach ($rawData as $m) {
    $joinDate = $m['tanggal_daftar'] ?: '2026-03-01';
    $joinYear = (int)date('Y', strtotime($joinDate));
    $joinMonth = (int)date('n', strtotime($joinDate));
    
    if ($joinYear < 2026 || ($joinYear == 2026 && $joinMonth < 3)) { 
        $referenceYear = 2026;
        $referenceMonth = 3;
    } else {
        $referenceYear = $joinYear;
        $referenceMonth = $joinMonth;
    }
    
    // Skip if member hasn't joined yet
    if ($referenceYear > $selectedYear || ($referenceYear == $selectedYear && $referenceMonth > $selectedMonth)) {
        continue;
    }
    
    // Calculate saldo awal from previous month
    $saldoAwal = 0;
    if ($selectedMonth > 1 || $selectedYear > $referenceYear || 
        ($selectedYear == $referenceYear && $selectedMonth > $referenceMonth)) {
        $prevMonth = $selectedMonth - 1;
        $prevYear = $selectedYear;
        if ($prevMonth < 1) {
            $prevMonth = 12;
            $prevYear--;
        }
        $saldoAwal = calculateRollingBalance($db, $m['id'], $prevMonth, $prevYear, $batasBulanan, $joinDate);
    }
    
    // Add current month's plafon
    $monthsCount = (($selectedYear - $referenceYear) * 12) + ($selectedMonth - $referenceMonth) + 1;
    if ($monthsCount > 0) {
        $saldoAwal += $batasBulanan;
    }
    
    $spent = (float)$m['total_belanja_bulan_ini'];
    $saldoAkhir = $saldoAwal - $spent;
    
    $m['saldo_awal'] = $saldoAwal;
    $m['saldo_akhir'] = $saldoAkhir;
    $m['total_belanja_bulan_ini'] = $spent;
    
    $data[] = $m;
}

// Handle Actions (Manual Input)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $anggotaId = !empty($_POST['anggota_id']) ? $_POST['anggota_id'] : null;
        $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']);
        $tipe = $_POST['tipe_transaksi'] ?? 'debet';
        
        // If credit, make the value negative
        if ($tipe === 'kredit') {
            $hargaJual = -$hargaJual;
            $hargaBeli = -$hargaBeli;
        }
        
        if ($hargaJual != 0) {
            $stmtInsert = $db->prepare("INSERT INTO konsumsi_transaksi (anggota_id, tanggal, nama_barang, harga_beli, ppn_persen, harga_jual, jumlah_belanja, keterangan, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmtInsert->execute([$anggotaId, $tanggal, $namaBarang, $hargaBeli, $ppnPersen, $hargaJual, $hargaJual, $keterangan, $_SESSION['user_id']]);
            setFlash('success', 'Transaksi manual '.($tipe == 'debet' ? '(Debet)' : '(Kredit)').' berhasil dicatat.');
        } else {
            setFlash('danger', 'Data nominal tidak valid.');
        }
        header("Location: konsumsi_laporan.php?month=$selectedMonth&year=$selectedYear&search=" . urlencode($search));
        exit;
    }
}

// Fetch member list for dropdown
$anggotaList = $db->query("SELECT id, no_anggota, nama FROM anggota WHERE status='aktif' ORDER BY nama")->fetchAll();

$pageTitle = 'Laporan Konsumsi';
include __DIR__ . '/../includes/header.php';
?>

<div class="row mb-4 no-print">
    <div class="col-md-12">
        <div class="pro-card shadow-sm" style="border-radius: 16px; border: none; background: white;">
            <div class="pro-card-body d-flex justify-content-between align-items-center" style="padding: 20px 32px;">
                <div class="d-flex align-items-center" style="gap: 16px;">
                    <a href="konsumsi.php?month=<?= $selectedMonth ?>&year=<?= $selectedYear ?>" class="btn btn-outline-secondary" style="border-radius: 12px; height: 45px; width: 45px; display: flex; align-items: center; justify-content: center; border: 1.5px solid var(--gray-200); color: var(--gray-600);">
                        <i class="fas fa-arrow-left"></i>
                    </a>
                    <div>
                        <h4 class="mb-0 fw-bold">Detail Laporan Konsumsi</h4>
                        <p class="text-muted small mb-0">Periode: <?= $months[$selectedMonth] ?> <?= $selectedYear ?></p>
                    </div>
                </div>
                <div class="d-flex gap-2">
                    <button onclick="window.print()" class="btn btn-sm btn-outline-primary shadow-sm" style="padding: 0 20px; height: 45px; font-size: 0.9rem; border-radius: 12px; gap: 8px; border: 1.5px solid #4F46E5; color: #4F46E5; font-weight: 700;">
                        <i class="fas fa-print"></i>
                        <span>CETAK LAPORAN</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4 no-print">
    <!-- Manual Input Tool -->
    <div class="col-md-6 mb-3 mb-md-0">
        <div class="pro-card shadow-sm h-100" style="border-radius: 16px; border: none; background: white; border-left: 5px solid #4F46E5;">
            <div class="pro-card-body d-flex justify-content-between align-items-center" style="padding: 24px;">
                <div class="d-flex align-items-center" style="gap: 16px;">
                    <div style="width: 48px; height: 48px; background: #EEF2FF; border-radius: 12px; display: flex; align-items: center; justify-content: center; color: #4F46E5;">
                        <i class="fas fa-plus-circle fa-lg"></i>
                    </div>
                    <div>
                        <h5 class="mb-0 fw-bold">Manual Input</h5>
                        <p class="text-muted small mb-0">Input belanja manual bulan ini</p>
                    </div>
                </div>
                <button type="button" onclick="openModal('addModal')" class="btn btn-primary" style="background: #4F46E5; border: none; border-radius: 10px; padding: 10px 20px; font-weight: 700;">
                    BUAT BARU
                </button>
            </div>
        </div>
    </div>
    
    <!-- Export Tool -->
    <div class="col-md-6">
        <div class="pro-card shadow-sm h-100" style="border-radius: 16px; border: none; background: white; border-left: 5px solid #10B981;">
            <div class="pro-card-body d-flex justify-content-between align-items-center" style="padding: 24px;">
                <div class="d-flex align-items-center" style="gap: 16px;">
                    <div style="width: 48px; height: 48px; background: #ECFDF5; border-radius: 12px; display: flex; align-items: center; justify-content: center; color: #10B981;">
                        <i class="fas fa-file-excel fa-lg"></i>
                    </div>
                    <div>
                        <h5 class="mb-0 fw-bold">Eksport Data</h5>
                        <p class="text-muted small mb-0">Unduh data periode ini (Excel)</p>
                    </div>
                </div>
                <a href="../exports/konsumsi_export_excel.php?month=<?= $selectedMonth ?>&year=<?= $selectedYear ?>&search=<?= urlencode($search) ?>" class="btn" style="background: #10B981; color: white; border: none; border-radius: 10px; padding: 10px 20px; font-weight: 700;">
                    DOWNLOAD
                </a>
            </div>
        </div>
    </div>
</div>
    <div class="col-md-12">
        <div class="pro-card" style="border-radius: 20px; overflow: hidden; border: none; box-shadow: var(--shadow-lg);">
            <div class="report-header text-center" style="padding: 40px; background: white; border-bottom: 2px solid var(--gray-50);">
                <img src="assets/img/logo.png" alt="Logo" style="height: 60px; margin-bottom: 20px;" onerror="this.style.display='none'">
                <h2 class="fw-bold mb-1" style="color: var(--gray-900); letter-spacing: -0.02em;"><?= getSetting('nama_koperasi') ?></h2>
                <p class="text-muted mb-4" style="font-size: 1.1rem;"><?= getSetting('alamat_koperasi') ?></p>
                <div style="display: inline-block; padding: 8px 24px; background: var(--primary-50); color: var(--primary-700); border-radius: 99px; font-weight: 800; font-size: 0.9rem; letter-spacing: 0.05em; text-transform: uppercase;">
                    LAPORAN REKAPITULASI KONSUMSI - <?= strtoupper($months[$selectedMonth]) ?> <?= $selectedYear ?>
                </div>
            </div>
            
            <div class="pro-card-body" style="padding: 40px;">
                <table class="table-clean-pro" style="width: 100%; border-collapse: separate; border-spacing: 0;">
                    <thead>
                        <tr style="background: var(--gray-50);">
                            <th style="padding: 20px; border-bottom: 2px solid var(--gray-100); border-radius: 12px 0 0 0;">NO</th>
                            <th style="padding: 20px; border-bottom: 2px solid var(--gray-100);">NAMA ANGGOTA</th>
                            <th class="text-right" style="padding: 20px; border-bottom: 2px solid var(--gray-100);">SALDO AWAL</th>
                            <th class="text-right" style="padding: 20px; border-bottom: 2px solid var(--gray-100);">HARGA ASLI</th>
                            <th class="text-right" style="padding: 20px; border-bottom: 2px solid var(--gray-100);">PPN</th>
                            <th class="text-right" style="padding: 20px; border-bottom: 2px solid var(--gray-100);">TOTAL BELANJA</th>
                            <th class="text-right" style="padding: 20px; border-bottom: 2px solid var(--gray-100);">SISA/KURANG</th>
                            <th class="text-right" style="padding: 20px; border-bottom: 2px solid var(--gray-100); border-radius: 0 12px 0 0;">SALDO DEPAN</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $no = 1;
                        $t_awal = 0; $t_asli = 0; $t_ppn = 0; $t_total = 0; $t_akhir = 0;
                        foreach ($data as $m): 
                            $spent = (float)$m['total_belanja_bulan_ini'];
                            $saldoAwal = (float)$m['saldo_awal'];
                            $saldoAkhir = (float)$m['saldo_akhir'];
                            $diff = $saldoAkhir - $saldoAwal; // Sisa/Kurang
                            
                            $t_awal += $saldoAwal;
                            $t_asli += (float)$m['total_harga_asli'];
                            $t_ppn += (float)$m['total_ppn'];
                            $t_total += $spent;
                            $t_akhir += $saldoAkhir;
                        ?>
                        <tr>
                            <td class="text-center" style="padding: 16px; border-bottom: 1px solid var(--gray-50); color: var(--gray-500);"><?= $no++ ?></td>
                            <td style="padding: 16px; border-bottom: 1px solid var(--gray-50);">
                                <div class="fw-bold" style="color: var(--gray-800);"><?= htmlspecialchars($m['nama']) ?></div>
                                <div class="small text-muted"><?= $m['no_anggota'] ?></div>
                            </td>
                            <td class="text-right" style="padding: 16px; border-bottom: 1px solid var(--gray-50);"><?= formatRupiah($saldoAwal) ?></td>
                            <td class="text-right" style="padding: 16px; border-bottom: 1px solid var(--gray-50);"><?= formatRupiah($m['total_harga_asli']) ?></td>
                            <td class="text-right" style="padding: 16px; border-bottom: 1px solid var(--gray-50);"><?= formatRupiah($m['total_ppn']) ?></td>
                            <td class="text-right fw-bold" style="padding: 16px; border-bottom: 1px solid var(--gray-50); color: var(--primary-700);"><?= formatRupiah($spent) ?></td>
                            <td class="text-right" style="padding: 16px; border-bottom: 1px solid var(--gray-50);">
                                <span class="<?= $diff >= 0 ? 'text-success' : 'text-danger' ?> fw-bold">
                                    <?= formatRupiah($diff) ?>
                                </span>
                            </td>
                            <td class="text-right fw-bold" style="padding: 16px; border-bottom: 1px solid var(--gray-50); background: var(--primary-50); color: var(--primary-800); position: relative;">
                                <?= formatRupiah($saldoAkhir) ?>
                                <button type="button" class="btn-input-mini no-print" onclick='openModalWithMember(<?= json_encode(["id" => $m["id"], "nama" => $m["nama"], "no_anggota" => $m["no_anggota"]]) ?>)' title="Input Transaksi">
                                    <i class="fas fa-plus"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr style="background: var(--gray-900); color: white;">
                            <td colspan="2" class="text-center fw-bold" style="padding: 20px; border-radius: 0 0 0 12px;">TOTAL KESELURUHAN</td>
                            <td class="text-right fw-bold" style="padding: 20px;"><?= formatRupiah($t_awal) ?></td>
                            <td class="text-right fw-bold" style="padding: 20px;"><?= formatRupiah($t_asli) ?></td>
                            <td class="text-right fw-bold" style="padding: 20px; color: var(--warning-400);"><?= formatRupiah($t_ppn) ?></td>
                            <td class="text-right fw-bold" style="padding: 20px;"><?= formatRupiah($t_total) ?></td>
                            <td class="text-right fw-bold" style="padding: 20px; color: <?= ($t_awal - $t_total) >= 0 ? '#6EE7B7' : '#FCA5A5' ?>;"><?= formatRupiah($t_awal - $t_total) ?></td>
                            <td class="text-right fw-bold" style="padding: 20px; border-radius: 0 0 12px 0; background: var(--primary-600);"><?= formatRupiah($t_akhir) ?></td>
                        </tr>
                    </tfoot>
                </table>
                
                <div class="report-footer mt-5 pt-5" style="display: grid; grid-template-columns: 1fr 1fr; gap: 40px; text-align: center;">
                    <div class="spacer"></div>
                    <div class="signature">
                        <p class="mb-5"><?= getSetting('alamat_koperasi') ?>, <?= date('d') ?> <?= $months[(int)date('n')] ?> <?= date('Y') ?></p>
                        <p class="mb-0 fw-bold" style="text-decoration: underline;">( ........................................... )</p>
                        <p class="text-muted">Pengelola Koperasi</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Addition Styles for Modal and Input */
.btn-input-mini {
    position: absolute;
    right: 5px;
    top: 50%;
    transform: translateY(-50%);
    width: 24px;
    height: 24px;
    border-radius: 6px;
    background: var(--primary-600);
    color: white;
    border: none;
    font-size: 0.7rem;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    opacity: 0;
    transition: all 0.2s;
}
tr:hover .btn-input-mini { opacity: 1; right: 10px; }

@media print {
    body { background: white !important; padding: 0 !important; }
    .app-sidebar, .top-header, .no-print, .btn-input-mini { display: none !important; }
    .main-content { margin: 0 !important; padding: 0 !important; width: 100% !important; }
    .pro-card { box-shadow: none !important; border: 1px solid #eee !important; color: black !important; }
    .pro-card-body { padding: 20px !important; }
    tfoot tr td { background: #333 !important; color: white !important; -webkit-print-color-adjust: exact; }
    .bg-primary-50 { background: #f0f7ff !important; -webkit-print-color-adjust: exact; }
}

/* Modal and UI Refinement (Premium Version) */
.modal-overlay-pro { 
    display: none; 
    position: fixed; 
    top: 0; 
    left: 0; 
    width: 100vw; 
    height: 100vh; 
    background: rgba(15, 23, 42, 0.75); 
    z-index: 9999; 
    align-items: center; 
    justify-content: center; 
    backdrop-filter: blur(12px);
    padding: 20px;
}
.modal-overlay-pro.active { display: flex !important; animation: modalFadeIn 0.4s cubic-bezier(0.16, 1, 0.3, 1); }

.modal-content-pro { 
    background: white; 
    border-radius: 32px; 
    width: 100%; 
    max-width: 680px; 
    max-height: 90vh; 
    overflow: hidden; 
    box-shadow: 0 40px 80px -15px rgba(0, 0, 0, 0.5); 
    display: flex; 
    flex-direction: column;
    border: 1px solid rgba(255,255,255,0.1);
}

.modal-header-pro { 
    padding: 30px 40px; 
    border-bottom: 1px solid #f1f5f9; 
    background: #fff; 
    flex-shrink: 0;
}
.modal-body-pro { 
    padding: 0 40px 30px; 
    overflow-y: auto; 
    flex-grow: 1; 
}
.modal-footer-pro { 
    padding: 20px 40px; 
    background: #f8fafc; 
    border-top: 1px solid #f1f5f9; 
    display: flex; 
    justify-content: flex-end; 
    gap: 15px;
    flex-shrink: 0;
}

/* UI Elements Styling */
.section-label {
    font-size: 0.7rem;
    font-weight: 800;
    color: #94a3b8;
    text-transform: uppercase;
    letter-spacing: 1.5px;
    margin-bottom: 12px;
    display: block;
}

.tipe-selector { display: flex; gap: 12px; margin-bottom: 25px; }
.tipe-btn {
    flex: 1;
    padding: 12px;
    border-radius: 16px;
    border: 2px solid #f1f5f9;
    font-weight: 800;
    font-size: 0.82rem;
    transition: all 0.3s;
    background: #f8fafc;
    color: #94a3b8;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}
.tipe-btn.active[data-tipe="debet"] { border-color: #ef4444; color: #ef4444; background: #fff5f5; box-shadow: 0 10px 15px -3px rgba(239, 68, 68, 0.1); }
.tipe-btn.active[data-tipe="kredit"] { border-color: #10b981; color: #10b981; background: #f0fdf4; box-shadow: 0 10px 15px -3px rgba(16, 185, 129, 0.1); }

.target-toggle {
    display: flex;
    background: #f1f5f9;
    padding: 5px;
    border-radius: 14px;
    margin-bottom: 25px;
    border: 1px solid #e2e8f0;
}
.target-btn {
    flex: 1;
    padding: 8px;
    text-align: center;
    border-radius: 10px;
    cursor: pointer;
    font-weight: 700;
    font-size: 0.8rem;
    transition: all 0.3s;
    color: #64748b;
    border: none;
    background: transparent;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}
.target-btn.active {
    background: white;
    color: #4F46E5;
    box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
}

.pro-input-group { margin-bottom: 20px; }
.label-pro { font-size: 0.85rem; font-weight: 700; color: #475569; margin-bottom: 8px; display: block; }
.pro-input { 
    width: 100%; 
    padding: 12px 18px; 
    border: 2px solid #f1f5f9; 
    border-radius: 14px; 
    outline: none; 
    transition: all 0.3s; 
    font-size: 0.95rem;
    color: #1e293b;
    background: #f8fafc;
}
.pro-input:focus { border-color: #6366f1; background: white; box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1); }

/* Summary Card Style */
.summary-card {
    padding: 24px;
    border-radius: 20px;
    margin-top: 25px;
    transition: all 0.3s;
    border: 1.5px solid transparent;
}
.summary-card.debet { background: #fee2e2; border-color: #fca5a5; }
.summary-card.kredit { background: #dcfce7; border-color: #86efac; }

.summary-label { font-size: 0.7rem; font-weight: 800; color: #64748b; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 5px; }
.summary-value-wrapper { display: flex; align-items: center; gap: 10px; }
.summary-currency { font-size: 1.4rem; font-weight: 800; }
.summary-currency.debet { color: #b91c1c; }
.summary-currency.kredit { color: #166534; }
.summary-input { 
    border: none; 
    background: transparent; 
    font-size: 2.2rem; 
    font-weight: 900; 
    width: 100%; 
    outline: none; 
}
.summary-input.debet { color: #b91c1c; }
.summary-input.kredit { color: #166534; }

/* Searchable Dropdown Fixes */
.searchable-dropdown { position: relative; width: 100%; }
.searchable-dropdown .dropdown-results { 
    position: absolute; 
    top: 100%; 
    left: 0; 
    right: 0; 
    background: white; 
    border: 1px solid #e2e8f0; 
    border-radius: 16px; 
    margin-top: 8px; 
    max-height: 250px; 
    overflow-y: auto; 
    z-index: 10000; 
    display: none; 
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); 
}
.searchable-dropdown .dropdown-results.active { display: block !important; animation: dropdownFadeIn 0.2s ease-out; }

.searchable-dropdown .dropdown-item { padding: 14px 20px; cursor: pointer; display: flex; align-items: center; gap: 15px; font-size: 0.9rem; transition: all 0.2s; border-bottom: 1px solid #f8fafc; }
.searchable-dropdown .dropdown-item:last-child { border-bottom: none; }
.searchable-dropdown .dropdown-item:hover { background: #f1f5f9; padding-left: 25px; color: #4F46E5; }

@keyframes modalFadeIn { 
    from { opacity: 0; transform: scale(0.95) translateY(20px); } 
    to { opacity: 1; transform: scale(1) translateY(0); } 
}
</style>

<!-- Add Modal (Premium UI) -->
<div class="modal-overlay-pro" id="addModal">
    <div class="modal-content-pro">
        <div class="modal-header-pro d-flex justify-content-between align-items-center">
            <div>
                <h3 class="mb-1 fw-bold"><i class="fas fa-file-invoice-dollar text-primary me-2"></i> Input Transaksi Manual</h3>
                <p class="text-muted small mb-0">Kelola pencatatan belanja atau pemasukan secara manual</p>
            </div>
            <button class="modal-close-pro" onclick="closeModal('addModal')" style="width: 40px; height: 40px; border-radius: 12px; background: #f1f5f9; display: flex; align-items: center; justify-content: center; color: #64748b; border: none; transition: all 0.2s;"><i class="fas fa-times"></i></button>
        </div>
        
        <form method="POST" style="display: contents;">
            <input type="hidden" name="action" value="add">
            <input type="hidden" name="tipe_transaksi" id="tipe_transaksi_hidden" value="debet">
            
            <div class="modal-body-pro">
                <div class="row">
                    <div class="col-md-6">
                        <label class="section-label">Tipe Transaksi</label>
                        <div class="tipe-selector">
                            <button type="button" class="tipe-btn active" data-tipe="debet" onclick="setTipe('debet')">
                                <i class="fas fa-arrow-up"></i> DEBET
                            </button>
                            <button type="button" class="tipe-btn" data-tipe="kredit" onclick="setTipe('kredit')">
                                <i class="fas fa-arrow-down"></i> KREDIT
                            </button>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="section-label">Target Transaksi</label>
                        <div class="target-toggle">
                            <button type="button" class="target-btn active" id="btn_target_anggota" onclick="setTarget('anggota')">
                                <i class="fas fa-user-tag text-xs"></i> ANGGOTA
                            </button>
                            <button type="button" class="target-btn" id="btn_target_umum" onclick="setTarget('umum')">
                                <i class="fas fa-globe text-xs"></i> UMUM
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Anggota Selection -->
                <div id="container_anggota" class="pro-input-group">
                    <label class="label-pro">Pilih Anggota <span class="text-danger">*</span></label>
                    <div class="searchable-dropdown">
                        <div class="position-relative">
                            <i class="fas fa-search position-absolute" style="left: 18px; top: 18px; color: #94a3b8;"></i>
                            <input type="text" class="pro-input" id="member_search_input" style="padding-left: 48px;" placeholder="Ketik nama atau No. Anggota..." autocomplete="off" oninput="filterMemberDropdown(this)">
                        </div>
                        <input type="hidden" name="anggota_id" id="member_id_hidden">
                        <div class="dropdown-results" id="member_results_list">
                            <?php foreach ($anggotaList as $a): ?>
                                <div class="dropdown-item" data-id="<?= $a['id'] ?>" data-text="<?= htmlspecialchars($a['no_anggota'] . ' - ' . $a['nama']) ?>">
                                    <div class="avatar-sm bg-light rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;">
                                        <i class="fas fa-user text-muted" style="font-size: 14px;"></i>
                                    </div>
                                    <span class="fw-semibold"><?= htmlspecialchars($a['no_anggota'] . ' - ' . $a['nama']) ?></span>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="row g-4">
                    <div class="col-md-6 pro-input-group">
                        <label class="label-pro">Tanggal</label>
                        <input type="date" name="tanggal" class="pro-input" required value="<?= date('Y-m-d') ?>">
                    </div>
                    <div class="col-md-6 pro-input-group">
                        <label class="label-pro" id="label_nama_barang">Keterangan / Item</label>
                        <input type="text" name="nama_barang" class="pro-input" required placeholder="Contoh: Belanja Bulanan">
                    </div>
                </div>

                <div class="row g-4">
                    <div class="col-md-7 pro-input-group">
                        <label class="label-pro">Nominal Utama (Rp)</label>
                        <div class="position-relative">
                            <span class="position-absolute" style="left: 18px; top: 14px; font-weight: 800; color: #94a3b8;">Rp</span>
                            <input type="text" name="harga_beli" id="modal_harga_beli" class="pro-input" style="padding-left: 50px;" required oninput="formatCurrencyInput(this); hitungHargaJual();" placeholder="0">
                        </div>
                    </div>
                    <div class="col-md-5 pro-input-group" id="ppn_container">
                        <label class="label-pro">PPN (%)</label>
                        <div class="position-relative">
                            <input type="number" name="ppn_persen" id="modal_ppn_persen" class="pro-input" value="0" oninput="hitungHargaJual()">
                            <span class="position-absolute" style="right: 18px; top: 14px; font-weight: 800; color: #94a3b8;">%</span>
                        </div>
                    </div>
                </div>

                <!-- Prominent Summary Box -->
                <div class="summary-card debet" id="total_impact_container">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <label class="summary-label">TOTAL AKHIR TRANSAKSI</label>
                        <span class="badge rounded-pill bg-danger text-white shadow-sm px-3" id="badge_tipe" style="font-size: 10px; font-weight: 800; border: 1px solid rgba(255,255,255,0.2);">DEBET</span>
                    </div>
                    <div class="summary-value-wrapper">
                        <span class="summary-currency debet" id="total_currency">Rp</span>
                        <input type="text" name="harga_jual" id="modal_harga_jual" class="summary-input debet" readonly value="0">
                    </div>
                    <p class="text-muted small mb-0 mt-3" id="tipe_info" style="font-size: 11px; line-height: 1.4;">
                        <i class="fas fa-info-circle me-1"></i> Transaksi ini akan tercatat sebagai pengeluaran/belanja yang meningkatkan penggunaan saldo plafon.
                    </p>
                </div>
            </div>

            <div class="modal-footer-pro">
                <button type="button" class="btn btn-light" onclick="closeModal('addModal')" style="border-radius: 14px; padding: 12px 25px; font-weight: 700; color: #64748b; background: white; border: 1.5px solid #f1f5f9;">BATAL</button>
                <button type="submit" class="btn btn-primary" style="background: #4F46E5; border: none; border-radius: 14px; padding: 12px 35px; font-weight: 800; box-shadow: 0 10px 20px -10px rgba(79, 70, 229, 0.5); letter-spacing: 0.5px;">SIMPAN TRANSAKSI</button>
            </div>
        </form>
    </div>
</div>

<script>
function setTarget(target) {
    const container = document.getElementById('container_anggota');
    const labelNama = document.getElementById('label_nama_barang');
    const btnAnggota = document.getElementById('btn_target_anggota');
    const btnUmum = document.getElementById('btn_target_umum');
    const hiddenId = document.getElementById('member_id_hidden');
    const searchInput = document.getElementById('member_search_input');

    if (target === 'umum') {
        container.style.display = 'none';
        labelNama.innerText = 'Keterangan Pengeluaran';
        btnUmum.classList.add('active');
        btnAnggota.classList.remove('active');
        hiddenId.value = '';
        searchInput.required = false;
    } else {
        container.style.display = 'block';
        labelNama.innerText = 'Nama Barang / Referensi';
        btnAnggota.classList.add('active');
        btnUmum.classList.remove('active');
        searchInput.required = true;
    }
}
function setTipe(tipe) {
    document.getElementById('tipe_transaksi_hidden').value = tipe;
    document.querySelectorAll('.tipe-btn').forEach(btn => btn.classList.remove('active'));
    document.querySelector(`.tipe-btn[data-tipe="${tipe}"]`).classList.add('active');
    
    const container = document.getElementById('total_impact_container');
    const currency = document.getElementById('total_currency');
    const input = document.getElementById('modal_harga_jual');
    const info = document.getElementById('tipe_info');
    const badge = document.getElementById('badge_tipe');
    const ppnContainer = document.getElementById('ppn_container');

    if (tipe === 'debet') {
        container.className = 'summary-card debet';
        currency.className = 'summary-currency debet';
        input.className = 'summary-input debet';
        badge.innerText = 'DEBET';
        badge.className = 'badge rounded-pill bg-danger text-white shadow-sm px-3';
        info.innerHTML = '<i class="fas fa-info-circle me-1"></i> Transaksi ini akan tercatat sebagai pengeluaran/belanja yang meningkatkan penggunaan saldo plafon.';
        ppnContainer.style.opacity = '1';
        ppnContainer.style.pointerEvents = 'auto';
    } else {
        container.className = 'summary-card kredit';
        currency.className = 'summary-currency kredit';
        input.className = 'summary-input kredit';
        badge.innerText = 'KREDIT';
        badge.className = 'badge rounded-pill bg-success text-white shadow-sm px-3';
        info.innerHTML = '<i class="fas fa-info-circle me-1"></i> Transaksi ini akan tercatat sebagai pemasukan/retur yang mengurangi penggunaan saldo plafon.';
        ppnContainer.style.opacity = '0.5';
        ppnContainer.style.pointerEvents = 'none';
        document.getElementById('modal_ppn_persen').value = 0;
        hitungHargaJual();
    }
}

function openModal(id) {
    document.getElementById(id).classList.add('active');
}
function closeModal(id) {
    document.getElementById(id).classList.remove('active');
}
function openModalWithMember(member) {
    document.getElementById('member_search_input').value = member.no_anggota + ' - ' + member.nama;
    document.getElementById('member_id_hidden').value = member.id;
    openModal('addModal');
}

function filterMemberDropdown(input) {
    const filter = input.value.toLowerCase();
    const results = document.getElementById('member_results_list');
    const items = results.querySelectorAll('.dropdown-item');
    if (filter.length > 0) {
        results.classList.add('active');
    } else {
        results.classList.remove('active');
    }
    items.forEach(item => {
        if (item.getAttribute('data-text').toLowerCase().includes(filter)) {
            item.style.display = 'flex';
        } else {
            item.style.display = 'none';
        }
    });
}

document.addEventListener('click', function(e) {
    if (e.target.closest('.dropdown-item')) {
        const item = e.target.closest('.dropdown-item');
        const input = item.closest('.searchable-dropdown').querySelector('input[type="text"]');
        const hidden = item.closest('.searchable-dropdown').querySelector('input[type="hidden"]');
        input.value = item.getAttribute('data-text');
        hidden.value = item.getAttribute('data-id');
        item.closest('.dropdown-results').classList.remove('active');
    } else if (!e.target.closest('.searchable-dropdown')) {
        document.querySelectorAll('.dropdown-results').forEach(res => res.classList.remove('active'));
    }
});

function formatCurrencyInput(input) {
    let value = input.value.replace(/[^0-9]/g, '');
    input.value = value ? new Intl.NumberFormat('id-ID').format(value) : '';
}

function hitungHargaJual() {
    const valString = document.getElementById('modal_harga_beli').value.replace(/\./g, '');
    const beli = parseFloat(valString) || 0;
    const ppn = parseFloat(document.getElementById('modal_ppn_persen').value) || 0;
    const total = beli + (beli * (ppn / 100));
    document.getElementById('modal_harga_jual').value = new Intl.NumberFormat('id-ID').format(Math.round(total));
}
</script>

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