<?php
/* APBDES ADMIN - FIX REDIRECT LAYAR KOSONG - 13 JULI 2026 */
if (ob_get_level() === 0) {
    ob_start();
}

require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';

function redirectApbdes($tahun)
{
    $url = 'apbdes.php?tahun=' . (int) $tahun;

    if (!headers_sent()) {
        header('Location: ' . $url, true, 303);
        exit;
    }

    echo '<script>window.location.replace(' . json_encode($url) . ');</script>';
    echo '<noscript><meta http-equiv="refresh" content="0;url=' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"></noscript>';
    exit;
}

function rupiahApbdes($number)
{
    return 'Rp ' . number_format((int)$number, 0, ',', '.');
}

$act = $_GET['a'] ?? 'list';

/* ================= SAVE SUMMARY ================= */

if($act=='save_summary' && $_SERVER['REQUEST_METHOD']=='POST'){

$tahun=intval($_POST['tahun']);

$cek=$mysqli->prepare("SELECT id FROM apbdes WHERE tahun=?");
$cek->bind_param("i",$tahun);
$cek->execute();
$cek->store_result();

if($cek->num_rows>0){

$stmt=$mysqli->prepare("
UPDATE apbdes
SET total_pendapatan=?, total_belanja=?
WHERE tahun=?
");

$stmt->bind_param("iii",
$_POST['total_pendapatan'],
$_POST['total_belanja'],
$tahun
);

}else{

$stmt=$mysqli->prepare("
INSERT INTO apbdes(tahun,total_pendapatan,total_belanja)
VALUES (?,?,?)
");

$stmt->bind_param("iii",
$tahun,
$_POST['total_pendapatan'],
$_POST['total_belanja']
);

}

$stmt->execute();

redirectApbdes($tahun);

}


/* ================= SAVE DETAIL ================= */

if($act=='save_detail' && $_SERVER['REQUEST_METHOD']=='POST'){

$apbdesId=intval($_POST['apbdes_id'] ?? 0);
$tahun=intval($_POST['tahun'] ?? date('Y'));
$jenis=$_POST['jenis'] ?? '';
$nama=trim($_POST['nama'] ?? '');
$jumlah=intval($_POST['jumlah'] ?? 0);
$bidang=$jenis==='belanja' ? trim($_POST['bidang'] ?? '') : null;

if(!in_array($jenis,array('pendapatan','belanja'),true) || $apbdesId<=0 || $nama==='' || $jumlah<0){
redirectApbdes($tahun);
}

if($jenis==='belanja' && $bidang===''){
$bidang='Belanja Belum Dikelompokkan';
}

$stmt=$mysqli->prepare("
INSERT INTO apbdes_detail(apbdes_id,jenis,bidang,nama,jumlah)
VALUES (?,?,?,?,?)
");

$stmt->bind_param("isssi",
$apbdesId,
$jenis,
$bidang,
$nama,
$jumlah
);

$stmt->execute();

redirectApbdes($tahun);

}


/* ================= DELETE DETAIL ================= */

if($act=='del_detail'){

$id=intval($_GET['id']);
$tahun=intval($_GET['tahun']);

$mysqli->query("DELETE FROM apbdes_detail WHERE id=$id");

redirectApbdes($tahun);

}

$tahun=$_GET['tahun'] ?? date('Y');

$stmt=$mysqli->prepare("SELECT * FROM apbdes WHERE tahun=?");
$stmt->bind_param("i",$tahun);
$stmt->execute();

$result=$stmt->get_result();
$summary=$result->fetch_assoc();

$pendapatanRows = [];
$belanjaRows = [];
$totalDetailPendapatan = 0;
$totalDetailBelanja = 0;

if ($summary) {
    $stmt=$mysqli->prepare("SELECT * FROM apbdes_detail WHERE apbdes_id=? AND jenis='pendapatan' ORDER BY nama ASC");
    $stmt->bind_param("i",$summary['id']);
    $stmt->execute();
    $res=$stmt->get_result();
    while($p=$res->fetch_assoc()){
        $pendapatanRows[] = $p;
        $totalDetailPendapatan += (int)$p['jumlah'];
    }

    $stmt=$mysqli->prepare("SELECT * FROM apbdes_detail WHERE apbdes_id=? AND jenis='belanja' ORDER BY bidang ASC, nama ASC");
    $stmt->bind_param("i",$summary['id']);
    $stmt->execute();
    $res=$stmt->get_result();
    while($b=$res->fetch_assoc()){
        $belanjaRows[] = $b;
        $totalDetailBelanja += (int)$b['jumlah'];
    }
}

$summaryPendapatan = (int)($summary['total_pendapatan'] ?? 0);
$summaryBelanja = (int)($summary['total_belanja'] ?? 0);
$surplus = $summaryPendapatan - $summaryBelanja;

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

<div class="page-hero">
    <div class="page-title">
        <span class="page-title-icon"><i class="ri-money-dollar-circle-fill"></i></span>
        <div>
            <h1>Manajemen APBDes</h1>
            <p>Kelola ringkasan pendapatan, belanja, dan detail anggaran desa per tahun.</p>
        </div>
    </div>
    <form class="page-actions" method="get">
        <label class="sr-only" for="tahunApbdes">Pilih Tahun</label>
        <input class="input" id="tahunApbdes" type="number" name="tahun" value="<?= esc($tahun) ?>" onchange="this.form.submit()" style="width:130px">
        <button class="action-btn secondary" type="submit"><i class="ri-filter-3-line"></i> Tampilkan</button>
    </form>
</div>

<div class="stats-grid">
    <div class="stat-card tone-blue">
        <div class="stat-icon"><i class="ri-arrow-down-circle-fill"></i></div>
        <div class="stat-info">
            <div class="stat-label">Pendapatan</div>
            <div class="stat-value"><?= rupiahApbdes($summaryPendapatan) ?></div>
            <div class="stat-sub">Summary tahun <?= esc($tahun) ?></div>
        </div>
    </div>
    <div class="stat-card tone-orange">
        <div class="stat-icon"><i class="ri-arrow-up-circle-fill"></i></div>
        <div class="stat-info">
            <div class="stat-label">Belanja</div>
            <div class="stat-value"><?= rupiahApbdes($summaryBelanja) ?></div>
            <div class="stat-sub">Summary tahun <?= esc($tahun) ?></div>
        </div>
    </div>
    <div class="stat-card <?= $surplus >= 0 ? 'tone-green' : 'tone-red' ?>">
        <div class="stat-icon"><i class="ri-scales-3-fill"></i></div>
        <div class="stat-info">
            <div class="stat-label"><?= $surplus >= 0 ? 'Surplus' : 'Defisit' ?></div>
            <div class="stat-value"><?= rupiahApbdes(abs($surplus)) ?></div>
            <div class="stat-sub">Pendapatan dikurangi belanja</div>
        </div>
    </div>
    <div class="stat-card tone-purple">
        <div class="stat-icon"><i class="ri-list-check-3"></i></div>
        <div class="stat-info">
            <div class="stat-label">Rincian Item</div>
            <div class="stat-value"><?= count($pendapatanRows) + count($belanjaRows) ?></div>
            <div class="stat-sub">Pendapatan & belanja</div>
        </div>
    </div>
</div>

<div class="data-card" style="margin-bottom:14px">
    <div class="data-card-head">
        <div>
            <h2><i class="ri-dashboard-3-line"></i> Summary Tahun <?= esc($tahun) ?></h2>
            <p>Masukkan total pendapatan dan belanja utama untuk publikasi APBDes.</p>
        </div>
    </div>
    <div class="data-card-body">
        <form method="post" action="apbdes.php?a=save_summary" class="form-grid">
            <input type="hidden" name="tahun" value="<?= esc($tahun) ?>">

            <div class="form-field">
                <label>Total Pendapatan</label>
                <input class="input" type="number" name="total_pendapatan" required value="<?= esc($summaryPendapatan) ?>">
            </div>

            <div class="form-field">
                <label>Total Belanja</label>
                <input class="input" type="number" name="total_belanja" required value="<?= esc($summaryBelanja) ?>">
            </div>

            <div class="form-actions" style="grid-column:1/-1">
                <button class="action-btn primary"><i class="ri-save-3-fill"></i> Simpan Summary</button>
            </div>
        </form>
    </div>
</div>

<?php if($summary): ?>

<div class="filter-card" style="margin-bottom:14px">
    <div class="filter-card-head">
        <div>
            <h3><i class="ri-add-box-fill"></i> Tambah Detail APBDes</h3>
            <p>Tambahkan item pendapatan atau belanja berdasarkan bidang.</p>
        </div>
    </div>
    <div class="filter-card-body">
        <form method="post" action="apbdes.php?a=save_detail" class="form-grid">
            <input type="hidden" name="apbdes_id" value="<?= (int)$summary['id'] ?>">
            <input type="hidden" name="tahun" value="<?= esc($tahun) ?>">

            <div class="form-field">
                <label>Jenis</label>
                <select class="input" name="jenis" id="jenisDetail">
                    <option value="pendapatan">Pendapatan</option>
                    <option value="belanja">Belanja</option>
                </select>
            </div>

            <div class="form-field" id="bidangBelanjaWrap" hidden>
                <label>Bidang Belanja</label>
                <input class="input" type="text" name="bidang" id="bidangBelanja" list="daftarBidangBelanja" placeholder="Pilih atau ketik nama bidang">
                <small class="note">Setiap item belanja akan ditampilkan di bawah bidang ini.</small>
                <datalist id="daftarBidangBelanja">
                    <option value="Bidang Penyelenggaraan Pemerintahan Desa">
                    <option value="Bidang Pelaksanaan Pembangunan Desa">
                    <option value="Bidang Pembinaan Kemasyarakatan Desa">
                    <option value="Bidang Pemberdayaan Masyarakat Desa">
                    <option value="Bidang Penanggulangan Bencana, Keadaan Darurat, dan Mendesak Desa">
                </datalist>
            </div>

            <div class="form-field">
                <label>Nama Item</label>
                <input class="input" type="text" name="nama" required placeholder="Contoh: Belanja alat tulis kantor">
            </div>

            <div class="form-field">
                <label>Jumlah</label>
                <input class="input" type="number" name="jumlah" required>
            </div>

            <div class="form-actions" style="grid-column:1/-1">
                <button class="action-btn primary"><i class="ri-add-circle-fill"></i> Tambah Detail</button>
            </div>
        </form>
    </div>
</div>

<div class="dashboard-grid two">
    <div class="data-card">
        <div class="data-card-head">
            <div>
                <h2><i class="ri-arrow-down-circle-fill"></i> Detail Pendapatan</h2>
                <p>Total rincian: <?= rupiahApbdes($totalDetailPendapatan) ?></p>
            </div>
        </div>
        <div class="table-wrap">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>Nama</th>
                        <th>Jumlah</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if($pendapatanRows): foreach($pendapatanRows as $p): ?>
                    <tr>
                        <td class="td-nama"><?= esc($p['nama']) ?></td>
                        <td class="mono"><strong><?= rupiahApbdes($p['jumlah']) ?></strong></td>
                        <td>
                            <a class="action-btn danger small" href="apbdes.php?a=del_detail&id=<?= (int)$p['id'] ?>&tahun=<?= esc($tahun) ?>" onclick="return confirmDelete('Hapus detail pendapatan ini?')"><i class="ri-delete-bin-line"></i> Hapus</a>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                    <tr><td colspan="3">Belum ada detail pendapatan.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="data-card">
        <div class="data-card-head">
            <div>
                <h2><i class="ri-arrow-up-circle-fill"></i> Detail Belanja</h2>
                <p>Total rincian: <?= rupiahApbdes($totalDetailBelanja) ?></p>
            </div>
        </div>
        <div class="table-wrap">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>Bidang</th>
                        <th>Item Belanja</th>
                        <th>Jumlah</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if($belanjaRows): foreach($belanjaRows as $b): ?>
                    <tr>
                        <td><span class="status-pill blue"><?= esc($b['bidang'] ?: 'Belanja Belum Dikelompokkan') ?></span></td>
                        <td class="td-nama"><?= esc($b['nama']) ?></td>
                        <td class="mono"><strong><?= rupiahApbdes($b['jumlah']) ?></strong></td>
                        <td>
                            <a class="action-btn danger small" href="apbdes.php?a=del_detail&id=<?= (int)$b['id'] ?>&tahun=<?= esc($tahun) ?>" onclick="return confirmDelete('Hapus detail belanja ini?')"><i class="ri-delete-bin-line"></i> Hapus</a>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                    <tr><td colspan="4">Belum ada detail belanja.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php else: ?>

<div class="alert">
    <i class="ri-information-fill"></i>
    <div>Silakan simpan summary tahun <?= esc($tahun) ?> terlebih dahulu sebelum menambahkan detail pendapatan dan belanja.</div>
</div>

<?php endif; ?>

<script>
(function(){
var jenis=document.getElementById('jenisDetail');
var wrap=document.getElementById('bidangBelanjaWrap');
var bidang=document.getElementById('bidangBelanja');

function toggleBidang(){
if(!jenis || !wrap || !bidang) return;
var isBelanja=jenis.value==='belanja';
wrap.hidden=!isBelanja;
bidang.required=isBelanja;
bidang.disabled=!isBelanja;
}

if(jenis){
jenis.addEventListener('change',toggleBidang);
toggleBidang();
}
})();
</script>

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