<?php
/**
 * SHU (Sisa Hasil Usaha) - Cooperative Dividend
 * Koperasi Management System
 * 
 * SHU Auto-calculation logic:
 * - Pendapatan (Revenue): Interest from loans (jasa pinjaman)
 * - Beban (Expenses): configurable operational costs
 * - SHU Bersih = Pendapatan - Beban
 * - Distribution:
 *   - Dana Cadangan: 25%
 *   - Jasa Simpanan: 25% (distributed by member savings ratio)
 *   - Jasa Pinjaman: 25% (distributed by member loan activity ratio)
 *   - Dana Pengurus: 10%
 *   - Dana Pendidikan: 5%
 *   - Dana Sosial: 5%
 *   - Dana Pembangunan: 5%
 */

$pageTitle = 'SHU';
$pageSubtitle = 'Sisa Hasil Usaha (Pembagian Keuntungan)';

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

// Ensure SHU table exists
$db->exec("
    CREATE TABLE IF NOT EXISTS shu (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tahun INT NOT NULL UNIQUE,
        total_pendapatan DECIMAL(15,2) NOT NULL DEFAULT 0,
        total_beban DECIMAL(15,2) NOT NULL DEFAULT 0,
        shu_bersih DECIMAL(15,2) NOT NULL DEFAULT 0,
        persen_cadangan DECIMAL(5,2) NOT NULL DEFAULT 25,
        persen_jasa_simpanan DECIMAL(5,2) NOT NULL DEFAULT 25,
        persen_jasa_pinjaman DECIMAL(5,2) NOT NULL DEFAULT 25,
        persen_pengurus DECIMAL(5,2) NOT NULL DEFAULT 10,
        persen_pendidikan DECIMAL(5,2) NOT NULL DEFAULT 5,
        persen_sosial DECIMAL(5,2) NOT NULL DEFAULT 5,
        persen_pembangunan DECIMAL(5,2) NOT NULL DEFAULT 5,
        dana_cadangan DECIMAL(15,2) NOT NULL DEFAULT 0,
        dana_jasa_simpanan DECIMAL(15,2) NOT NULL DEFAULT 0,
        dana_jasa_pinjaman DECIMAL(15,2) NOT NULL DEFAULT 0,
        dana_pengurus DECIMAL(15,2) NOT NULL DEFAULT 0,
        dana_pendidikan DECIMAL(15,2) NOT NULL DEFAULT 0,
        dana_sosial DECIMAL(15,2) NOT NULL DEFAULT 0,
        dana_pembangunan DECIMAL(15,2) NOT NULL DEFAULT 0,
        status ENUM('draft','final') DEFAULT 'draft',
        catatan TEXT DEFAULT NULL,
        created_by INT DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
    ) ENGINE=InnoDB
");

$db->exec("
    CREATE TABLE IF NOT EXISTS shu_anggota (
        id INT AUTO_INCREMENT PRIMARY KEY,
        shu_id INT NOT NULL,
        anggota_id INT NOT NULL,
        total_simpanan DECIMAL(15,2) NOT NULL DEFAULT 0,
        total_pinjaman_aktivitas DECIMAL(15,2) NOT NULL DEFAULT 0,
        rasio_simpanan DECIMAL(10,6) NOT NULL DEFAULT 0,
        rasio_pinjaman DECIMAL(10,6) NOT NULL DEFAULT 0,
        shu_jasa_simpanan DECIMAL(15,2) NOT NULL DEFAULT 0,
        shu_jasa_pinjaman DECIMAL(15,2) NOT NULL DEFAULT 0,
        total_shu DECIMAL(15,2) NOT NULL DEFAULT 0,
        FOREIGN KEY (shu_id) REFERENCES shu(id) ON DELETE CASCADE,
        FOREIGN KEY (anggota_id) REFERENCES anggota(id) ON DELETE CASCADE,
        UNIQUE KEY unique_shu_anggota (shu_id, anggota_id)
    ) ENGINE=InnoDB
");

// Selected year
$tahun = intval($_GET['tahun'] ?? date('Y'));

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'hitung') {
        $tahunHitung = intval($_POST['tahun']);
        $bebanOperasional = (float)str_replace('.', '', $_POST['beban_operasional'] ?? '0');
        
        // 1. Calculate Revenue: total interest earned from loans in that year
        //    Interest = total_bayar - jumlah_pinjaman for all approved/paid-off loans
        $revStmt = $db->prepare("
            SELECT COALESCE(SUM(
                CASE 
                    WHEN status IN ('disetujui','lunas') THEN total_bayar - jumlah_pinjaman
                    ELSE 0 
                END
            ), 0) as pendapatan_jasa
            FROM pinjaman 
            WHERE YEAR(tanggal_pinjaman) = ?
        ");
        $revStmt->execute([$tahunHitung]);
        $pendapatanjasa = (float)$revStmt->fetchColumn();
        
        // Also count installment payments received in that year as activity indicator
        $angsuranStmt = $db->prepare("
            SELECT COALESCE(SUM(jumlah_bayar), 0) as total_angsuran
            FROM angsuran
            WHERE YEAR(tanggal_bayar) = ?
        ");
        $angsuranStmt->execute([$tahunHitung]);
        $totalAngsuranTahun = (float)$angsuranStmt->fetchColumn();
        
        $totalPendapatan = $pendapatanjasa;
        $shuBersih = $totalPendapatan - $bebanOperasional;
        if ($shuBersih < 0) $shuBersih = 0;
        
        // Percentages from form or defaults
        $pCadangan = (float)($_POST['persen_cadangan'] ?? 25);
        $pJasaSimpanan = (float)($_POST['persen_jasa_simpanan'] ?? 25);
        $pJasaPinjaman = (float)($_POST['persen_jasa_pinjaman'] ?? 25);
        $pPengurus = (float)($_POST['persen_pengurus'] ?? 10);
        $pPendidikan = (float)($_POST['persen_pendidikan'] ?? 5);
        $pSosial = (float)($_POST['persen_sosial'] ?? 5);
        $pPembangunan = (float)($_POST['persen_pembangunan'] ?? 5);
        
        // Calculate allocations
        $danaCadangan = $shuBersih * $pCadangan / 100;
        $danaJasaSimpanan = $shuBersih * $pJasaSimpanan / 100;
        $danaJasaPinjaman = $shuBersih * $pJasaPinjaman / 100;
        $danaPengurus = $shuBersih * $pPengurus / 100;
        $danaPendidikan = $shuBersih * $pPendidikan / 100;
        $danaSosial = $shuBersih * $pSosial / 100;
        $danaPembangunan = $shuBersih * $pPembangunan / 100;
        
        // Upsert SHU record
        $checkStmt = $db->prepare("SELECT id FROM shu WHERE tahun = ?");
        $checkStmt->execute([$tahunHitung]);
        $existingShu = $checkStmt->fetch();
        
        if ($existingShu) {
            $shuId = $existingShu['id'];
            $stmt = $db->prepare("UPDATE shu SET total_pendapatan=?, total_beban=?, shu_bersih=?, 
                persen_cadangan=?, persen_jasa_simpanan=?, persen_jasa_pinjaman=?, persen_pengurus=?, persen_pendidikan=?, persen_sosial=?, persen_pembangunan=?,
                dana_cadangan=?, dana_jasa_simpanan=?, dana_jasa_pinjaman=?, dana_pengurus=?, dana_pendidikan=?, dana_sosial=?, dana_pembangunan=?,
                status='draft', created_by=? WHERE id=?");
            $stmt->execute([
                $totalPendapatan, $bebanOperasional, $shuBersih,
                $pCadangan, $pJasaSimpanan, $pJasaPinjaman, $pPengurus, $pPendidikan, $pSosial, $pPembangunan,
                $danaCadangan, $danaJasaSimpanan, $danaJasaPinjaman, $danaPengurus, $danaPendidikan, $danaSosial, $danaPembangunan,
                $_SESSION['user_id'], $shuId
            ]);
            // Clear old member distribution
            $db->prepare("DELETE FROM shu_anggota WHERE shu_id = ?")->execute([$shuId]);
        } else {
            $stmt = $db->prepare("INSERT INTO shu (tahun, total_pendapatan, total_beban, shu_bersih,
                persen_cadangan, persen_jasa_simpanan, persen_jasa_pinjaman, persen_pengurus, persen_pendidikan, persen_sosial, persen_pembangunan,
                dana_cadangan, dana_jasa_simpanan, dana_jasa_pinjaman, dana_pengurus, dana_pendidikan, dana_sosial, dana_pembangunan,
                created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            $stmt->execute([
                $tahunHitung, $totalPendapatan, $bebanOperasional, $shuBersih,
                $pCadangan, $pJasaSimpanan, $pJasaPinjaman, $pPengurus, $pPendidikan, $pSosial, $pPembangunan,
                $danaCadangan, $danaJasaSimpanan, $danaJasaPinjaman, $danaPengurus, $danaPendidikan, $danaSosial, $danaPembangunan,
                $_SESSION['user_id']
            ]);
            $shuId = $db->lastInsertId();
        }
        
        // 2. Calculate per-member distribution
        // Get all active members with their savings and loan activity
        $members = $db->query("
            SELECT a.id, a.nama, a.no_anggota,
                COALESCE((SELECT SUM(CASE WHEN tipe='setoran' THEN jumlah ELSE -jumlah END) FROM simpanan WHERE anggota_id = a.id), 0) as total_simpanan,
                COALESCE((SELECT SUM(jumlah_bayar) FROM angsuran ag JOIN pinjaman p ON ag.pinjaman_id = p.id WHERE p.anggota_id = a.id AND YEAR(ag.tanggal_bayar) = $tahunHitung), 0) as aktivitas_pinjaman
            FROM anggota a WHERE a.status = 'aktif'
        ")->fetchAll();
        
        $grandTotalSimpanan = array_sum(array_map(fn($m) => max(0, $m['total_simpanan']), $members));
        $grandTotalAktivitas = array_sum(array_column($members, 'aktivitas_pinjaman'));
        
        $insertMember = $db->prepare("INSERT INTO shu_anggota (shu_id, anggota_id, total_simpanan, total_pinjaman_aktivitas, rasio_simpanan, rasio_pinjaman, shu_jasa_simpanan, shu_jasa_pinjaman, total_shu) VALUES (?,?,?,?,?,?,?,?,?)");
        
        foreach ($members as $m) {
            $simpananPositif = max(0, $m['total_simpanan']);
            $rasioSimpanan = $grandTotalSimpanan > 0 ? $simpananPositif / $grandTotalSimpanan : 0;
            $rasioPinjaman = $grandTotalAktivitas > 0 ? $m['aktivitas_pinjaman'] / $grandTotalAktivitas : 0;
            
            $shuJasaSimpanan = $danaJasaSimpanan * $rasioSimpanan;
            $shuJasaPinjaman = $danaJasaPinjaman * $rasioPinjaman;
            $totalShuAnggota = $shuJasaSimpanan + $shuJasaPinjaman;
            
            $insertMember->execute([
                $shuId, $m['id'], $simpananPositif, $m['aktivitas_pinjaman'],
                $rasioSimpanan, $rasioPinjaman, $shuJasaSimpanan, $shuJasaPinjaman, $totalShuAnggota
            ]);
        }
        
        setFlash('success', "SHU tahun $tahunHitung berhasil dihitung secara otomatis.");
        header("Location: shu.php?tahun=$tahunHitung");
        exit;
    }
    
    if ($action === 'finalize') {
        $db->prepare("UPDATE shu SET status = 'final' WHERE id = ?")->execute([$_POST['id']]);
        setFlash('success', 'SHU telah ditetapkan sebagai final.');
        header("Location: shu.php?tahun=$tahun");
        exit;
    }
}

// Load SHU data for selected year
$shuData = null;
$shuAnggotaList = [];
$shuStmt = $db->prepare("SELECT * FROM shu WHERE tahun = ?");
$shuStmt->execute([$tahun]);
$shuData = $shuStmt->fetch();

if ($shuData) {
    $shuAnggotaStmt = $db->prepare("
        SELECT sa.*, a.nama, a.no_anggota 
        FROM shu_anggota sa 
        JOIN anggota a ON sa.anggota_id = a.id 
        ORDER BY sa.total_shu DESC
    ");
    $shuAnggotaStmt->execute();
    $shuAnggotaList = $shuAnggotaStmt->fetchAll();
}


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

<!-- Year Selector & Action -->
<div class="card mb-3">
    <div class="card-body">
        <div class="toolbar" style="align-items: flex-end;">
            <div class="form-group" style="margin-bottom: 0;">
                <label style="font-size: 0.78rem; margin-bottom: 4px;">Tahun</label>
                <div style="display: flex; gap: 5px;">
                    <input type="number" class="form-control" id="tahunInputManual" value="<?= $tahun ?>" 
                           style="width: 100px;" min="2000" max="2100"
                           onkeydown="if(event.key==='Enter') window.location='shu.php?tahun='+this.value">
                    <button type="button" class="btn btn-outline" style="padding: 0 12px;" 
                            onclick="window.location='shu.php?tahun='+document.getElementById('tahunInputManual').value">
                        <i class="fas fa-chevron-right"></i>
                    </button>
                </div>
            </div>
            <button class="btn btn-primary" onclick="openModal('hitungModal')">
                <i class="fas fa-calculator"></i> Hitung SHU Otomatis
            </button>
            <a href="export_shu.php?tahun=<?= $tahun ?>" class="btn btn-success">
                <i class="fas fa-file-export"></i> Export
            </a>
            <?php if ($shuData && $shuData['status'] === 'draft'): ?>
                <form method="POST" style="display:inline;" onsubmit="return confirm('Tetapkan SHU tahun <?= $tahun ?> sebagai FINAL? Data tidak bisa diubah lagi.');">
                    <input type="hidden" name="action" value="finalize">
                    <input type="hidden" name="id" value="<?= $shuData['id'] ?>">
                    <button type="submit" class="btn btn-success"><i class="fas fa-check-double"></i> Tetapkan Final</button>
                </form>
            <?php endif; ?>
            <?php if ($shuData): ?>
                <button class="btn btn-outline" onclick="printPage()"><i class="fas fa-print"></i> Cetak</button>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php if ($shuData): ?>

<!-- SHU Overview -->
<div class="stats-grid">
    <div class="stat-card success">
        <div class="stat-info">
            <h3>Total Pendapatan</h3>
            <div class="stat-value"><?= formatRupiah($shuData['total_pendapatan']) ?></div>
            <span class="stat-change up"><i class="fas fa-arrow-up"></i> jasa pinjaman</span>
        </div>
        <div class="stat-icon success"><i class="fas fa-chart-line"></i></div>
    </div>
    <div class="stat-card danger">
        <div class="stat-info">
            <h3>Beban Operasional</h3>
            <div class="stat-value"><?= formatRupiah($shuData['total_beban']) ?></div>
        </div>
        <div class="stat-icon danger"><i class="fas fa-money-bill-wave"></i></div>
    </div>
    <div class="stat-card primary">
        <div class="stat-info">
            <h3>SHU Bersih <?= $tahun ?></h3>
            <div class="stat-value"><?= formatRupiah($shuData['shu_bersih']) ?></div>
            <span class="badge <?= $shuData['status'] === 'final' ? 'badge-success' : 'badge-warning' ?>" style="margin-top: 6px;">
                <?= $shuData['status'] === 'final' ? '✓ Final' : '● Draft' ?>
            </span>
        </div>
        <div class="stat-icon primary"><i class="fas fa-coins"></i></div>
    </div>
</div>

<!-- Allocation Breakdown -->
<div class="card mb-3">
    <div class="card-header">
        <h2><i class="fas fa-chart-pie" style="color: var(--primary-500); margin-right: 8px;"></i>Alokasi SHU Tahun <?= $tahun ?></h2>
    </div>
    <div class="card-body">
        <div class="grid-2">
            <div>
                <div class="chart-container" style="height: 280px;">
                    <canvas id="shuChart"></canvas>
                </div>
            </div>
            <div>
                <table class="data-table" style="font-size: 0.88rem;">
                    <thead>
                        <tr>
                            <th>Alokasi</th>
                            <th class="text-center">%</th>
                            <th class="text-right">Jumlah</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><span class="badge badge-primary">Dana Cadangan</span></td>
                            <td class="text-center"><?= $shuData['persen_cadangan'] ?>%</td>
                            <td class="text-right fw-bold"><?= formatRupiah($shuData['dana_cadangan']) ?></td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-success">Jasa Simpanan</span></td>
                            <td class="text-center"><?= $shuData['persen_jasa_simpanan'] ?>%</td>
                            <td class="text-right fw-bold text-success"><?= formatRupiah($shuData['dana_jasa_simpanan']) ?></td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-info">Jasa Pinjaman</span></td>
                            <td class="text-center"><?= $shuData['persen_jasa_pinjaman'] ?>%</td>
                            <td class="text-right fw-bold text-info"><?= formatRupiah($shuData['dana_jasa_pinjaman']) ?></td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-warning">Dana Pengurus</span></td>
                            <td class="text-center"><?= $shuData['persen_pengurus'] ?>%</td>
                            <td class="text-right fw-bold"><?= formatRupiah($shuData['dana_pengurus']) ?></td>
                        </tr>
                        <tr>
                            <td><span class="badge badge-danger">Dana Pendidikan</span></td>
                            <td class="text-center"><?= $shuData['persen_pendidikan'] ?>%</td>
                            <td class="text-right fw-bold"><?= formatRupiah($shuData['dana_pendidikan']) ?></td>
                        </tr>
                        <tr>
                            <td><span class="badge" style="background: #faf5ff; color: #7e22ce;">Dana Sosial</span></td>
                            <td class="text-center"><?= $shuData['persen_sosial'] ?>%</td>
                            <td class="text-right fw-bold"><?= formatRupiah($shuData['dana_sosial']) ?></td>
                        </tr>
                        <tr>
                            <td><span class="badge" style="background: #f0fdf4; color: #15803d;">Dana Pembangunan</span></td>
                            <td class="text-center"><?= $shuData['persen_pembangunan'] ?>%</td>
                            <td class="text-right fw-bold"><?= formatRupiah($shuData['dana_pembangunan']) ?></td>
                        </tr>
                        <tr style="background: var(--gray-50); font-weight: 700;">
                            <td>Total</td>
                            <td class="text-center">100%</td>
                            <td class="text-right"><?= formatRupiah($shuData['shu_bersih']) ?></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Per-Member Distribution -->
<div class="card">
    <div class="card-header">
        <h2><i class="fas fa-users" style="color: var(--success-500); margin-right: 8px;"></i>Pembagian SHU Per Anggota</h2>
        <span class="text-muted"><?= count($shuAnggotaList) ?> anggota</span>
    </div>
    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Anggota</th>
                    <th class="text-right">Total Simpanan</th>
                    <th class="text-right">SHU Jasa Simpanan</th>
                    <th class="text-right">Aktivitas Pinjaman</th>
                    <th class="text-right">SHU Jasa Pinjaman</th>
                    <th class="text-right">Total SHU</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($shuAnggotaList)): ?>
                    <tr><td colspan="7" class="text-center text-muted" style="padding: 30px;">Belum ada perhitungan SHU</td></tr>
                <?php else: ?>
                    <?php foreach ($shuAnggotaList as $i => $sa): ?>
                        <tr>
                            <td><?= $i + 1 ?></td>
                            <td>
                                <div class="member-cell">
                                    <div class="member-avatar avatar-<?= ($sa['anggota_id'] % 6) + 1 ?>" style="width:32px;height:32px;min-width:32px;font-size:0.7rem;">
                                        <?= strtoupper(substr($sa['nama'], 0, 2)) ?>
                                    </div>
                                    <div class="member-details">
                                        <div class="member-name"><?= htmlspecialchars($sa['nama']) ?></div>
                                        <div class="member-id"><?= $sa['no_anggota'] ?></div>
                                    </div>
                                </div>
                            </td>
                            <td class="text-right"><?= formatRupiah($sa['total_simpanan']) ?></td>
                            <td class="text-right text-success fw-bold"><?= formatRupiah($sa['shu_jasa_simpanan']) ?></td>
                            <td class="text-right"><?= formatRupiah($sa['total_pinjaman_aktivitas']) ?></td>
                            <td class="text-right text-info fw-bold"><?= formatRupiah($sa['shu_jasa_pinjaman']) ?></td>
                            <td class="text-right fw-bold" style="font-size: 0.95rem;"><?= formatRupiah($sa['total_shu']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <tr style="background: var(--gray-50); font-weight: 700;">
                        <td colspan="3" class="text-right">Total Distribusi Anggota</td>
                        <td class="text-right text-success"><?= formatRupiah($shuData['dana_jasa_simpanan']) ?></td>
                        <td></td>
                        <td class="text-right text-info"><?= formatRupiah($shuData['dana_jasa_pinjaman']) ?></td>
                        <td class="text-right"><?= formatRupiah($shuData['dana_jasa_simpanan'] + $shuData['dana_jasa_pinjaman']) ?></td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php else: ?>
<!-- No SHU data -->
<div class="card">
    <div class="card-body">
        <div class="empty-state">
            <i class="fas fa-calculator"></i>
            <h3>Belum Ada Perhitungan SHU Tahun <?= $tahun ?></h3>
            <p>Klik tombol "Hitung SHU Otomatis" untuk menghitung SHU berdasarkan data transaksi.</p>
            <button class="btn btn-primary" onclick="openModal('hitungModal')">
                <i class="fas fa-calculator"></i> Hitung SHU Otomatis
            </button>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Hitung SHU Modal -->
<div class="modal modal-lg" id="hitungModal">
    <div class="modal-header">
        <h3><i class="fas fa-calculator" style="color: var(--primary-500); margin-right: 8px;"></i>Hitung SHU Otomatis - Tahun <?= $tahun ?></h3>
        <button class="modal-close" onclick="closeModal('hitungModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="hitung">
        <div class="modal-body">
            <div class="form-group">
                <label>Tahun SHU <span class="required">*</span></label>
                <input type="number" name="tahun" class="form-control" required value="<?= $tahun ?>" min="2000" max="2100">
                <span class="form-text">Masukkan tahun yang akan dihitung SHU-nya.</span>
            </div>
            
            <div class="alert alert-info">
                <i class="fas fa-info-circle"></i>
                Pendapatan dihitung otomatis dari jasa pinjaman tahun <?= $tahun ?>. Anda hanya perlu memasukkan beban operasional.
            </div>
            
            <div class="form-group">
                <label>Beban Operasional (Rp) <span class="required">*</span></label>
                <input type="text" name="beban_operasional" class="form-control" required 
                       value="<?= $shuData ? number_format($shuData['total_beban'], 0, '', '.') : '0' ?>"
                       oninput="formatCurrencyInput(this)" placeholder="Masukkan total beban operasional">
                <span class="form-text">Biaya operasional koperasi selama tahun <?= $tahun ?> (ATK, listrik, honor, dll.)</span>
            </div>

            <hr style="border: none; border-top: 1px solid var(--gray-200); margin: 20px 0;">
            <h4 style="font-size: 0.9rem; font-weight: 700; color: var(--gray-700); margin-bottom: 16px;">Persentase Alokasi SHU</h4>
            
            <div class="form-row-3">
                <div class="form-group">
                    <label>Dana Cadangan (%)</label>
                    <input type="number" name="persen_cadangan" class="form-control" value="<?= $shuData['persen_cadangan'] ?? 25 ?>" step="0.5" min="0" max="100">
                </div>
                <div class="form-group">
                    <label>Jasa Simpanan (%)</label>
                    <input type="number" name="persen_jasa_simpanan" class="form-control" value="<?= $shuData['persen_jasa_simpanan'] ?? 25 ?>" step="0.5" min="0" max="100">
                </div>
                <div class="form-group">
                    <label>Jasa Pinjaman (%)</label>
                    <input type="number" name="persen_jasa_pinjaman" class="form-control" value="<?= $shuData['persen_jasa_pinjaman'] ?? 25 ?>" step="0.5" min="0" max="100">
                </div>
            </div>
            <div class="form-row-3">
                <div class="form-group">
                    <label>Dana Pengurus (%)</label>
                    <input type="number" name="persen_pengurus" class="form-control" value="<?= $shuData['persen_pengurus'] ?? 10 ?>" step="0.5" min="0" max="100">
                </div>
                <div class="form-group">
                    <label>Dana Pendidikan (%)</label>
                    <input type="number" name="persen_pendidikan" class="form-control" value="<?= $shuData['persen_pendidikan'] ?? 5 ?>" step="0.5" min="0" max="100">
                </div>
                <div class="form-group">
                    <label>Dana Sosial (%)</label>
                    <input type="number" name="persen_sosial" class="form-control" value="<?= $shuData['persen_sosial'] ?? 5 ?>" step="0.5" min="0" max="100">
                </div>
            </div>
            <div class="form-row-3">
                <div class="form-group">
                    <label>Dana Pembangunan (%)</label>
                    <input type="number" name="persen_pembangunan" class="form-control" value="<?= $shuData['persen_pembangunan'] ?? 5 ?>" step="0.5" min="0" max="100">
                </div>
            </div>
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle"></i>
                Total persentase harus = 100%. Default: Cadangan 25%, Jasa Simpanan 25%, Jasa Pinjaman 25%, Pengurus 10%, Pendidikan 5%, Sosial 5%, Pembangunan 5%.
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('hitungModal')">Batal</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-calculator"></i> Hitung SHU</button>
        </div>
    </form>
</div>

<?php
$extraJS = '';
if ($shuData) {
    $extraJS = "
    <script>
        const shuCtx = document.getElementById('shuChart')?.getContext('2d');
        if (shuCtx) {
            new Chart(shuCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Dana Cadangan', 'Jasa Simpanan', 'Jasa Pinjaman', 'Dana Pengurus', 'Dana Pendidikan', 'Dana Sosial', 'Dana Pembangunan'],
                    datasets: [{
                        data: [
                            {$shuData['dana_cadangan']},
                            {$shuData['dana_jasa_simpanan']},
                            {$shuData['dana_jasa_pinjaman']},
                            {$shuData['dana_pengurus']},
                            {$shuData['dana_pendidikan']},
                            {$shuData['dana_sosial']},
                            {$shuData['dana_pembangunan']}
                        ],
                        backgroundColor: [
                            'rgba(99, 102, 241, 0.85)',
                            'rgba(16, 185, 129, 0.85)',
                            'rgba(59, 130, 246, 0.85)',
                            'rgba(245, 158, 11, 0.85)',
                            'rgba(239, 68, 68, 0.85)',
                            'rgba(139, 92, 246, 0.85)',
                            'rgba(34, 197, 94, 0.85)'
                        ],
                        borderWidth: 2,
                        borderColor: '#fff',
                        hoverOffset: 8
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 14,
                                boxWidth: 12,
                                font: { family: 'Inter', size: 11 }
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return context.label + ': Rp ' + new Intl.NumberFormat('id-ID').format(context.parsed);
                                }
                            }
                        }
                    },
                    cutout: '55%'
                }
            });
        }
    </script>
    ";
}

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