<?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'] ?? '';
    $pemilik = $_POST['pemilik'] ?? '';
    $kontak = $_POST['kontak'] ?? '';
    $deskripsi = $_POST['deskripsi'] ?? '';
    $imgname = null;

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

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

if ($act === 'del') {
    $id = (int)($_GET['id'] ?? 0);
    if ($id > 0) {
        $stmt = $mysqli->prepare("SELECT gambar FROM umkm 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 umkm WHERE id=?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();
    }
    header('Location: umkm.php?msg=deleted');
    exit;
}

$row = null;
if ($act === 'edit') {
    $id = (int)($_GET['id'] ?? 0);
    $stmt = $mysqli->prepare("SELECT * FROM umkm 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-shopping-bag-3-fill"></i></span><div><h1><?= $act === 'list' ? 'UMKM Desa' : (($act === 'edit' && $row) ? 'Edit UMKM' : 'Tambah UMKM') ?></h1><p>Kelola usaha masyarakat, pemilik, kontak, deskripsi, dan dokumentasi produk.</p></div></div>
    <div class="page-actions"><?php if($act === 'list'): ?><a class="action-btn primary" href="umkm.php?a=form"><i class="ri-add-circle-fill"></i> Tambah UMKM</a><?php else: ?><a class="action-btn secondary" href="umkm.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 UMKM berhasil dihapus.' : 'Data UMKM berhasil disimpan.' ?></span></div><?php endif; ?>

<?php if ($act === 'list'): ?>
    <?php
    if ($q !== '') {
        $like = "%$q%";
        $stmt = $mysqli->prepare("SELECT * FROM umkm WHERE nama_usaha LIKE ? OR pemilik LIKE ? ORDER BY id DESC");
        $stmt->bind_param('ss', $like, $like);
        $stmt->execute();
        $res = $stmt->get_result();
    } else {
        $res = $mysqli->query("SELECT * FROM umkm 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 UMKM</label><input class="input" name="q" placeholder="Cari usaha atau pemilik..." 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="umkm.php">Reset</a></div></form></div></article>
    <article class="data-card"><div class="data-card-head"><h2>Daftar UMKM Desa</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>Pemilik</th><th>Kontak</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><?= esc($r['pemilik']) ?></td><td><?= esc($r['kontak'] ?? '-') ?></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="umkm.php?a=edit&id=<?= (int)$r['id'] ?>"><i class="ri-pencil-line"></i> Edit</a> <a class="action-btn danger small" href="umkm.php?a=del&id=<?= (int)$r['id'] ?>" onclick="return confirmDelete('Hapus data UMKM ini?')"><i class="ri-delete-bin-line"></i> Hapus</a></td></tr><?php endwhile; else: ?><tr><td colspan="6">Belum ada data UMKM.</td></tr><?php endif; ?>
    </tbody></table></div></article>
<?php else: ?>
    <article class="data-card"><div class="data-card-head"><h2>Form UMKM</h2><span class="status-pill blue">Ekonomi Warga</span></div><div class="data-card-body"><form class="form-grid" method="post" enctype="multipart/form-data" action="umkm.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>Pemilik</label><input class="input" name="pemilik" value="<?= esc($row['pemilik'] ?? '') ?>"></div><div class="form-field"><label>Kontak</label><input class="input" name="kontak" value="<?= esc($row['kontak'] ?? '') ?>"></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 UMKM"><?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="umkm.php"><i class="ri-close-line"></i> Batal</a></div></form></div></article>
<?php endif; ?>

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