<?php
require_once __DIR__ . '/includes/admin_bootstrap.php';

$msg    = '';
$action = $_GET['action'] ?? 'list';
$editId = (int)($_GET['id'] ?? 0);

if ($action === 'delete' && $editId) {
    $pdo->prepare("DELETE FROM categories WHERE id=?")->execute([$editId]);
    redirect(BASE_URL . '/admin/categories.php?deleted=1');
}
if ($action === 'toggle' && $editId) {
    $pdo->prepare("UPDATE categories SET status = 1 - status WHERE id=?")->execute([$editId]);
    redirect(BASE_URL . '/admin/categories.php');
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_cat'])) {
    $name   = trim($_POST['name']   ?? '');
    $status = isset($_POST['status']) ? 1 : 0;
    $cid    = (int)($_POST['cat_id'] ?? 0);
    $slug   = makeSlug($name);
    if (!$name) {
        $msg = '<div class="alert alert-error">ক্যাটেগরির নাম আবশ্যক।</div>';
    } else {
        $slugBase = $slug; $i = 1;
        while (true) {
            $chk = $pdo->prepare("SELECT id FROM categories WHERE slug=? AND id!=?");
            $chk->execute([$slug, $cid]);
            if (!$chk->fetch()) break;
            $slug = $slugBase . '-' . $i++;
        }
        if ($cid) {
            $pdo->prepare("UPDATE categories SET name=?,slug=?,status=? WHERE id=?")->execute([$name,$slug,$status,$cid]);
        } else {
            $pdo->prepare("INSERT INTO categories (name,slug,status) VALUES (?,?,?)")->execute([$name,$slug,$status]);
        }
        redirect(BASE_URL . '/admin/categories.php?saved=1');
    }
}

$categories = $pdo->query("SELECT c.*, (SELECT COUNT(*) FROM products WHERE category_id=c.id) as product_count FROM categories c ORDER BY c.name")->fetchAll();
$editing = null;
if ($editId && $action === 'edit') {
    $stmt = $pdo->prepare("SELECT * FROM categories WHERE id=?");
    $stmt->execute([$editId]); $editing = $stmt->fetch();
}


// ── HTML output starts ──
include __DIR__ . '/includes/admin_header.php';

?>
<h2>ক্যাটেগরি ব্যবস্থাপনা</h2>
<?= $msg ?>
<?php if(isset($_GET['deleted'])): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> মুছে ফেলা হয়েছে।</div><?php endif; ?>
<?php if(isset($_GET['saved'])): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> সংরক্ষণ সফল।</div><?php endif; ?>

<div style="display:grid;grid-template-columns:1fr 360px;gap:24px;align-items:start;">
    <div class="card">
        <div class="card-header"><h3>সকল ক্যাটেগরি</h3></div>
        <div class="table-wrap">
            <table>
                <thead><tr><th>নাম</th><th>স্লাগ</th><th>পণ্য</th><th>অবস্থা</th><th>অ্যাকশন</th></tr></thead>
                <tbody>
                <?php foreach ($categories as $cat): ?>
                <tr>
                    <td><strong><?= e($cat['name']) ?></strong></td>
                    <td style="color:var(--g600);font-size:.82rem;"><?= e($cat['slug']) ?></td>
                    <td><?= $cat['product_count'] ?></td>
                    <td><span class="badge badge-<?= $cat['status']?'active':'inactive' ?>"><?= $cat['status']?'সক্রিয়':'নিষ্ক্রিয়' ?></span></td>
                    <td>
                        <div class="actions">
                            <a href="?action=edit&id=<?=$cat['id']?>" class="topbar-btn btn-navy"><i class="fas fa-edit"></i></a>
                            <a href="?action=toggle&id=<?=$cat['id']?>" class="topbar-btn btn-gray"><i class="fas fa-toggle-on"></i></a>
                            <a href="?action=delete&id=<?=$cat['id']?>" class="topbar-btn btn-red" data-confirm="মুছে ফেলবেন?"><i class="fas fa-trash"></i></a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <div class="card">
        <div class="card-header">
            <h3><?= $editing ? 'সম্পাদনা' : 'নতুন ক্যাটেগরি' ?></h3>
            <?php if($editing): ?><a href="?" class="topbar-btn btn-gray">বাতিল</a><?php endif; ?>
        </div>
        <div class="card-body">
            <form method="POST">
                <input type="hidden" name="cat_id" value="<?= $editing['id'] ?? 0 ?>">
                <div class="form-group"><label class="form-label">নাম *</label>
                    <input type="text" class="form-control" name="name" value="<?= e($editing['name'] ?? '') ?>" required></div>
                <div class="form-group">
                    <label class="form-check"><input type="checkbox" name="status" value="1" <?= ($editing['status'] ?? 1) ? 'checked' : '' ?>> সক্রিয়</label>
                </div>
                <button type="submit" name="save_cat" class="topbar-btn btn-gold"><i class="fas fa-save"></i> সংরক্ষণ</button>
            </form>
        </div>
    </div>
</div>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
