<?php
require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';
require_once __DIR__.'/../includes/kependudukan_helpers.php';

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

if ($act === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $nama = $_POST['nama_usaha'] ?? '';
    $deskripsi = $_POST['deskripsi'] ?? '';
    $imgname = null;

    if (isset($_FILES['gambar']) && $_FILES['gambar']['error'] === 0) {
        $ext = pathinfo($_FILES['gambar']['name'], PATHINFO_EXTENSION);
        $imgname = 'bumdes_'.time().'_'.rand(1000,9999).'.'.$ext;
        move_uploaded_file($_FILES['gambar']['tmp_name'], __DIR__.'/../uploads/'.$imgname);
    }

    if ($id > 0) {
        if ($imgname) {
            $stmt = $mysqli->prepare("UPDATE bumdes SET nama_usaha=?, deskripsi=?, gambar=? WHERE id=?");
            $stmt->bind_param('sssi', $nama, $deskripsi, $imgname, $id);
        } else {
            $stmt = $mysqli->prepare("UPDATE bumdes SET nama_usaha=?, deskripsi=? WHERE id=?");
            $stmt->bind_param('ssi', $nama, $deskripsi, $id);
        }
    } else {
        $stmt = $mysqli->prepare("INSERT INTO bumdes(nama_usaha,deskripsi,gambar) VALUES (?,?,?)");
        $stmt->bind_param('sss', $nama, $deskripsi, $imgname);
    }
    $stmt->execute();
    $stmt->close();
    header('Location: bumdes.php?msg=saved');
    exit;
}

if ($act === 'del') {
    $id = (int)($_GET['id'] ?? 0);
    if ($id > 0) {
        $stmt = $mysqli->prepare("SELECT gambar FROM bumdes WHERE id=?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $o = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if ($o && !empty($o['gambar'])) @unlink(__DIR__.'/../uploads/'.$o['gambar']);
        $stmt = $mysqli->prepare("DELETE FROM bumdes WHERE id=?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();
    }
    header('Location: bumdes.php?msg=deleted');
    exit;
}

$row = null;
if ($act === 'edit') {
    $id = (int)($_GET['id'] ?? 0);
    $stmt = $mysqli->prepare("SELECT * FROM bumdes WHERE id=?");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}

include __DIR__.'/../includes/header.php';
$q = trim($_GET['q'] ?? '');
$msg = $_GET['msg'] ?? '';
?>

<section class="page-hero">
    <div class="page-title"><span class="page-title-icon"><i class="ri-store-2-fill"></i></span><div><h1><?= $act === 'list' ? 'BUMDes' : (($act === 'edit' && $row) ? 'Edit Usaha BUMDes' : 'Tambah Usaha BUMDes') ?></h1><p>Kelola unit usaha Badan Usaha Milik Desa beserta deskripsi dan dokumentasi.</p></div></div>
    <div class="page-actions"><?php if($act === 'list'): ?><a class="action-btn primary" href="bumdes.php?a=form"><i class="ri-add-circle-fill"></i> Tambah Usaha</a><?php else: ?><a class="action-btn secondary" href="bumdes.php"><i class="ri-arrow-left-line"></i> Kembali</a><?php endif; ?></div>
</section>

<?php if ($msg): ?><div class="alert"><i class="ri-information-fill"></i><span><?= $msg === 'deleted' ? 'Data BUMDes berhasil dihapus.' : 'Data BUMDes berhasil disimpan.' ?></span></div><?php endif; ?>

<?php if ($act === 'list'): ?>
    <?php
    if ($q !== '') {
        $like = "%$q%";
        $stmt = $mysqli->prepare("SELECT * FROM bumdes WHERE nama_usaha LIKE ? ORDER BY id DESC");
        $stmt->bind_param('s', $like);
        $stmt->execute();
        $res = $stmt->get_result();
    } else {
        $res = $mysqli->query("SELECT * FROM bumdes ORDER BY id DESC");
    }
    ?>
    <article class="filter-card" style="margin-bottom:14px"><div class="filter-card-body"><form class="filter-grid" method="get"><div class="filter-field"><label>Cari Usaha</label><input class="input" name="q" placeholder="Cari nama usaha BUMDes..." value="<?= esc($q) ?>"></div><div class="filter-field"><button class="action-btn primary" type="submit"><i class="ri-search-line"></i> Cari</button> <a class="action-btn secondary" href="bumdes.php">Reset</a></div></form></div></article>
    <article class="data-card"><div class="data-card-head"><h2>Daftar Usaha BUMDes</h2><span class="status-pill blue"><?= $res ? mambu_fmt($res->num_rows) : '0' ?> data</span></div><div class="table-wrap"><table class="admin-table"><thead><tr><th>ID</th><th>Nama Usaha</th><th>Gambar</th><th>Aksi</th></tr></thead><tbody>
    <?php if($res && $res->num_rows): while($r = $res->fetch_assoc()): ?><tr><td><span class="id-badge"><?= (int)$r['id'] ?></span></td><td class="td-nama"><?= esc($r['nama_usaha']) ?></td><td><?php if(!empty($r['gambar'])): ?><img src="../uploads/<?= esc($r['gambar']) ?>" class="cover-img" alt="<?= esc($r['nama_usaha']) ?>"><?php else: ?><span class="status-pill gray">Tanpa gambar</span><?php endif; ?></td><td style="white-space:nowrap"><a class="action-btn success small" href="bumdes.php?a=edit&id=<?= (int)$r['id'] ?>"><i class="ri-pencil-line"></i> Edit</a> <a class="action-btn danger small" href="bumdes.php?a=del&id=<?= (int)$r['id'] ?>" onclick="return confirmDelete('Hapus data BUMDes ini?')"><i class="ri-delete-bin-line"></i> Hapus</a></td></tr><?php endwhile; else: ?><tr><td colspan="4">Belum ada data BUMDes.</td></tr><?php endif; ?>
    </tbody></table></div></article>
<?php else: ?>
    <article class="data-card"><div class="data-card-head"><h2>Form Usaha BUMDes</h2><span class="status-pill blue">Ekonomi Desa</span></div><div class="data-card-body"><form class="form-grid" method="post" enctype="multipart/form-data" action="bumdes.php?a=save"><input type="hidden" name="id" value="<?= (int)($row['id'] ?? 0) ?>"><div class="form-field"><label>Nama Usaha</label><input class="input" name="nama_usaha" value="<?= esc($row['nama_usaha'] ?? '') ?>" required></div><div class="form-field"><label>Gambar</label><input type="file" class="input" name="gambar"><?php if(!empty($row['gambar'])): ?><img class="preview" src="../uploads/<?= esc($row['gambar']) ?>" alt="Preview BUMDes"><?php endif; ?></div><div class="form-field" style="grid-column:1/-1"><label>Deskripsi</label><textarea class="input" name="deskripsi" rows="5"><?= esc($row['deskripsi'] ?? '') ?></textarea></div><div class="form-actions" style="grid-column:1/-1"><button class="action-btn primary" type="submit"><i class="ri-save-3-fill"></i> Simpan</button><a class="action-btn secondary" href="bumdes.php"><i class="ri-close-line"></i> Batal</a></div></form></div></article>
<?php endif; ?>

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