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

$pageTitle = 'SHU Konsumsi';
$pageSubtitle = 'Perhitungan Sisa Hasil Usaha dari Koperasi Konsumsi';

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

// Ensure SHU Konsumsi table exists
$db->exec("
    CREATE TABLE IF NOT EXISTS konsumsi_shu (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tahun INT NOT NULL UNIQUE,
        total_keuntungan 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 30,
        persen_jasa_anggota DECIMAL(5,2) NOT NULL DEFAULT 50,
        persen_jasa_pengurus DECIMAL(5,2) NOT NULL DEFAULT 20,
        dana_cadangan DECIMAL(15,2) NOT NULL DEFAULT 0,
        dana_jasa_anggota DECIMAL(15,2) NOT NULL DEFAULT 0,
        dana_jasa_pengurus DECIMAL(15,2) NOT NULL DEFAULT 0,
        status ENUM('draft','final') DEFAULT 'draft',
        created_by INT DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB
");

$db->exec("
    CREATE TABLE IF NOT EXISTS konsumsi_shu_anggota (
        id INT AUTO_INCREMENT PRIMARY KEY,
        konsumsi_shu_id INT NOT NULL,
        anggota_id INT NOT NULL,
        total_belanja DECIMAL(15,2) NOT NULL DEFAULT 0,
        rasio_belanja DECIMAL(10,6) NOT NULL DEFAULT 0,
        shu_jasa_anggota DECIMAL(15,2) NOT NULL DEFAULT 0,
        FOREIGN KEY (konsumsi_shu_id) REFERENCES konsumsi_shu(id) ON DELETE CASCADE,
        FOREIGN KEY (anggota_id) REFERENCES anggota(id) ON DELETE CASCADE,
        UNIQUE KEY unique_konsumsi_shu_anggota (konsumsi_shu_id, anggota_id)
    ) ENGINE=InnoDB
");

$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 Profit (Keuntungan) for the selected year
        // We use SUM(harga_jual - harga_beli) as raw gross margin / advantage from members.
        // Also ensure no 'pengeluaran umum' negatively skewing it, although if they exist, 
        // we probably handle them separately. The prompt asks to calculate SHU from "Dana Cadangan, Jasa Anggota, Jasa Pengurus".
        $revStmt = $db->prepare("
            SELECT COALESCE(SUM(harga_jual - harga_beli), 0) as total_margin
            FROM konsumsi_transaksi 
            WHERE YEAR(tanggal) = ? AND anggota_id IS NOT NULL AND harga_jual > 0
        ");
        $revStmt->execute([$tahunHitung]);
        $totalMargin = (float)$revStmt->fetchColumn();
        
        $totalKeuntungan = $totalMargin;
        $shuBersih = $totalKeuntungan - $bebanOperasional;
        
        $pCadangan = (float)($_POST['persen_cadangan'] ?? 30);
        $pJasaAnggota = (float)($_POST['persen_jasa_anggota'] ?? 50);
        $pJasaPengurus = (float)($_POST['persen_jasa_pengurus'] ?? 20);
        
        // Equal 100 checking is front-end usually, ensure normalized:
        $totalP = $pCadangan + $pJasaAnggota + $pJasaPengurus;
        if($totalP > 0) {
            $pCadangan = ($pCadangan / $totalP) * 100;
            $pJasaAnggota = ($pJasaAnggota / $totalP) * 100;
            $pJasaPengurus = ($pJasaPengurus / $totalP) * 100;
        }

        if ($shuBersih > 0) {
            $danaCadangan = $shuBersih * $pCadangan / 100;
            $danaJasaAnggota = $shuBersih * $pJasaAnggota / 100;
            $danaJasaPengurus = $shuBersih * $pJasaPengurus / 100;
        } else {
            $danaCadangan = 0;
            $danaJasaAnggota = 0;
            $danaJasaPengurus = 0;
        }
        
        // Upsert DB
        $checkStmt = $db->prepare("SELECT id FROM konsumsi_shu WHERE tahun = ?");
        $checkStmt->execute([$tahunHitung]);
        $existingShu = $checkStmt->fetch();
        
        if ($existingShu) {
            $shuId = $existingShu['id'];
            $stmt = $db->prepare("UPDATE konsumsi_shu SET total_keuntungan=?, total_beban=?, shu_bersih=?, 
                persen_cadangan=?, persen_jasa_anggota=?, persen_jasa_pengurus=?, 
                dana_cadangan=?, dana_jasa_anggota=?, dana_jasa_pengurus=?, status='draft', created_by=? WHERE id=?");
            $stmt->execute([
                $totalKeuntungan, $bebanOperasional, $shuBersih,
                $pCadangan, $pJasaAnggota, $pJasaPengurus,
                $danaCadangan, $danaJasaAnggota, $danaJasaPengurus,
                $_SESSION['user_id'], $shuId
            ]);
            $db->prepare("DELETE FROM konsumsi_shu_anggota WHERE konsumsi_shu_id = ?")->execute([$shuId]);
        } else {
            $stmt = $db->prepare("INSERT INTO konsumsi_shu (tahun, total_keuntungan, total_beban, shu_bersih,
                persen_cadangan, persen_jasa_anggota, persen_jasa_pengurus,
                dana_cadangan, dana_jasa_anggota, dana_jasa_pengurus,
                created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
            $stmt->execute([
                $tahunHitung, $totalKeuntungan, $bebanOperasional, $shuBersih,
                $pCadangan, $pJasaAnggota, $pJasaPengurus,
                $danaCadangan, $danaJasaAnggota, $danaJasaPengurus,
                $_SESSION['user_id']
            ]);
            $shuId = $db->lastInsertId();
        }
        
        // 2. Member Distribution
        // Sum total belanja per member
        $members = $db->query("
            SELECT a.id, a.nama, a.no_anggota,
                COALESCE((SELECT SUM(jumlah_belanja) FROM konsumsi_transaksi kt WHERE kt.anggota_id = a.id AND YEAR(kt.tanggal) = $tahunHitung), 0) as total_belanja
            FROM anggota a WHERE a.status = 'aktif' AND a.is_konsumsi = 1
        ")->fetchAll();
        
        $grandTotalBelanja = array_sum(array_column($members, 'total_belanja'));
        
        $insertMember = $db->prepare("INSERT INTO konsumsi_shu_anggota (konsumsi_shu_id, anggota_id, total_belanja, rasio_belanja, shu_jasa_anggota) VALUES (?,?,?,?,?)");
        
        foreach ($members as $m) {
            $totalM = (float)$m['total_belanja'];
            $rasioBelanja = $grandTotalBelanja > 0 ? $totalM / $grandTotalBelanja : 0;
            $shuJasaMember = $danaJasaAnggota * $rasioBelanja;
            
            $insertMember->execute([
                $shuId, $m['id'], $totalM, $rasioBelanja, $shuJasaMember
            ]);
        }
        
        setFlash('success', "SHU Konsumsi tahun $tahunHitung berhasil diperhitungkan.");
        header("Location: konsumsi_shu.php?tahun=$tahunHitung");
        exit;
    }
    
    if ($action === 'finalize') {
        $db->prepare("UPDATE konsumsi_shu SET status = 'final' WHERE id = ?")->execute([$_POST['id']]);
        setFlash('success', 'SHU Konsumsi telah ditetapkan sebagai final.');
        header("Location: konsumsi_shu.php?tahun=$tahun");
        exit;
    }
}

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

if ($shuData) {
    $shuAnggotaStmt = $db->prepare("
        SELECT sa.*, a.nama, a.no_anggota 
        FROM konsumsi_shu_anggota sa 
        JOIN anggota a ON sa.anggota_id = a.id 
        ORDER BY sa.shu_jasa_anggota 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='konsumsi_shu.php?tahun='+this.value">
                    <button type="button" class="btn btn-outline" style="padding: 0 12px;" 
                            onclick="window.location='konsumsi_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 Konsumsi
            </button>
            <?php if ($shuData && $shuData['status'] === 'draft'): ?>
                <form method="POST" style="display:inline;" onsubmit="return confirm('Tetapkan SHU Konsumsi 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; ?>
            <a href="konsumsi.php" class="btn btn-outline"><i class="fas fa-arrow-left"></i> Kembali ke Konsumsi</a>
        </div>
    </div>
</div>

<?php if ($shuData): ?>

<!-- SHU Overview -->
<div class="stats-grid">
    <div class="stat-card success">
        <div class="stat-info">
            <h3>Margin Konsumsi (Kotor)</h3>
            <div class="stat-value"><?= formatRupiah($shuData['total_keuntungan']) ?></div>
            <span class="stat-change up"><i class="fas fa-arrow-up"></i> (Harga Jual - Harga Beli)</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 Konsumsi Tahun <?= $tahun ?></h2>
    </div>
    <div class="card-body">
        <div class="row align-items-center">
            <div class="col-md-7">
                <table class="table table-hover table-borderless" style="font-size: 0.95rem; margin-bottom: 0;">
                    <thead style="border-bottom: 2px solid #f1f5f9;">
                        <tr>
                            <th class="text-secondary" style="font-weight: 600; font-size: 0.8rem; letter-spacing: 0.5px; padding-bottom: 12px; width: 40%;">ALOKASI</th>
                            <th class="text-center text-secondary" style="font-weight: 600; font-size: 0.8rem; letter-spacing: 0.5px; padding-bottom: 12px; width: 20%;">%</th>
                            <th class="text-right text-secondary" style="font-weight: 600; font-size: 0.8rem; letter-spacing: 0.5px; padding-bottom: 12px; width: 40%;">JUMLAH</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td style="padding: 16px 8px;"><span class="badge" style="background-color: #e0e7ff; color: #4f46e5; padding: 6px 12px; font-weight: 600; border-radius: 20px;">Dana Cadangan</span></td>
                            <td class="text-center" style="padding: 16px 8px; color: #64748b; font-weight: 500;"><?= number_format($shuData['persen_cadangan'], 2) ?>%</td>
                            <td class="text-right fw-bold" style="padding: 16px 8px; color: #1e293b;"><?= formatRupiah($shuData['dana_cadangan']) ?></td>
                        </tr>
                        <tr>
                            <td style="padding: 16px 8px;"><span class="badge" style="background-color: #dcfce7; color: #16a34a; padding: 6px 12px; font-weight: 600; border-radius: 20px;">Jasa Anggota</span></td>
                            <td class="text-center" style="padding: 16px 8px; color: #64748b; font-weight: 500;"><?= number_format($shuData['persen_jasa_anggota'], 2) ?>%</td>
                            <td class="text-right fw-bold" style="padding: 16px 8px; color: #1e293b;"><?= formatRupiah($shuData['dana_jasa_anggota']) ?></td>
                        </tr>
                        <tr>
                            <td style="padding: 16px 8px;"><span class="badge" style="background-color: #fef3c7; color: #d97706; padding: 6px 12px; font-weight: 600; border-radius: 20px;">Jasa Pengurus</span></td>
                            <td class="text-center" style="padding: 16px 8px; color: #64748b; font-weight: 500;"><?= number_format($shuData['persen_jasa_pengurus'], 2) ?>%</td>
                            <td class="text-right fw-bold" style="padding: 16px 8px; color: #1e293b;"><?= formatRupiah($shuData['dana_jasa_pengurus']) ?></td>
                        </tr>
                        <tr style="background: #f8fafc; border-top: 2px solid #f1f5f9;">
                            <td style="padding: 16px 8px; font-weight: 700; color: #334155; border-bottom-left-radius: 8px; border-top-left-radius: 8px;">Total</td>
                            <td class="text-center" style="padding: 16px 8px; font-weight: 700; color: #334155;">100%</td>
                            <td class="text-right" style="padding: 16px 8px; font-weight: 700; color: #334155; border-bottom-right-radius: 8px; border-top-right-radius: 8px;"><?= formatRupiah($shuData['shu_bersih']) ?></td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="col-md-5">
                <?php if ($shuData['shu_bersih'] > 0): ?>
                    <div class="chart-container" style="height: 300px; padding: 20px;">
                        <canvas id="shuChart"></canvas>
                    </div>
                <?php else: ?>
                    <div class="text-center" style="padding: 40px 20px; background-color: #f8fafc; border: 2px dashed #e2e8f0; border-radius: 16px; margin-left: 20px;">
                        <i class="fas fa-chart-pie" style="font-size: 3.5rem; color: #cbd5e1; margin-bottom: 12px;"></i>
                        <h5 style="color: #64748b; font-weight: 700; font-size: 1rem; margin-bottom: 6px;">Grafik Belum Tersedia</h5>
                        <p style="color: #94a3b8; font-size: 0.85rem; margin-bottom: 0;">Nilai SHU masih Rp 0, pastikan ada transaksi dengan margin masuk.</p>
                    </div>
                <?php endif; ?>
            </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 Jasa Anggota Per Member</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 Belanja (Tahun Ini)</th>
                    <th class="text-right">Jasa SHU Diterima</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($shuAnggotaList)): ?>
                    <tr><td colspan="4" 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_belanja']) ?></td>
                            <td class="text-right text-success fw-bold" style="font-size: 0.95rem;"><?= formatRupiah($sa['shu_jasa_anggota']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <tr style="background: var(--gray-50); font-weight: 700;">
                        <td colspan="2" class="text-right">Total Distribusi Anggota</td>
                        <td class="text-right"><?= formatRupiah(array_sum(array_column($shuAnggotaList, 'total_belanja'))) ?></td>
                        <td class="text-right text-success"><?= formatRupiah($shuData['dana_jasa_anggota']) ?></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" style="font-size: 4rem; color: var(--gray-300); margin-bottom: 20px;"></i>
            <h3>Belum Ada Perhitungan SHU Konsumsi Tahun <?= $tahun ?></h3>
            <p>Klik tombol "Hitung SHU Konsumsi" untuk mengkalkulasi bagi hasil margin dari seluruh transaksi belanja Koperasi Konsumsi.</p>
            <button class="btn btn-primary mt-3" onclick="openModal('hitungModal')">
                <i class="fas fa-calculator"></i> Hitung SHU Konsumsi
            </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 Konsumsi 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" style="max-height: 70vh; overflow-y: auto;">
            <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">Tentukan tahun evaluasi margin.</span>
            </div>
            
            <div class="alert alert-info">
                <i class="fas fa-info-circle"></i>
                Total Keuntungan akan terakumulasi otomatis dari total margin (Selisih Harga Jual dengan Harga Beli per Barang) Anggota di tahun <?= $tahun ?>.
            </div>
            
            <div class="form-group">
                <label>Beban Operasional Tambahan (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="Misal biaya transport belanja...">
            </div>

            <hr style="border: none; border-top: 1px dashed var(--gray-300); margin: 24px 0;">
            <h4 style="font-size: 0.95rem; font-weight: 800; color: var(--gray-800); margin-bottom: 16px;">Persentase Alokasi</h4>
            
            <div class="row g-3">
                <div class="col-md-4">
                    <div class="form-group">
                        <label>Dana Cadangan (%)</label>
                        <input type="number" name="persen_cadangan" class="form-control" value="<?= $shuData['persen_cadangan'] ?? 30 ?>" step="0.5" min="0" max="100">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label>Jasa Anggota (%)</label>
                        <input type="number" name="persen_jasa_anggota" class="form-control" value="<?= $shuData['persen_jasa_anggota'] ?? 50 ?>" step="0.5" min="0" max="100">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label>Jasa Pengurus (%)</label>
                        <input type="number" name="persen_jasa_pengurus" class="form-control" value="<?= $shuData['persen_jasa_pengurus'] ?? 20 ?>" step="0.5" min="0" max="100">
                    </div>
                </div>
            </div>
            <div class="alert alert-warning mb-0" style="padding: 10px 15px; font-size: 0.8rem;">
                <i class="fas fa-exclamation-triangle"></i> Pastikan total penjumlahan mencapai persis 100%.
            </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 me-2"></i> Eksekusi Perhitungan</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 Anggota', 'Jasa Pengurus'],
                    datasets: [{
                        data: [
                            {$shuData['dana_cadangan']},
                            {$shuData['dana_jasa_anggota']},
                            {$shuData['dana_jasa_pengurus']}
                        ],
                        backgroundColor: [
                            'rgba(99, 102, 241, 0.85)',
                            'rgba(16, 185, 129, 0.85)',
                            'rgba(245, 158, 11, 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';
?>
