<?php
/**
 * Admin — Categories, Sub-categories & Companies
 * Path: admin/categories.php
 * Category: hover image | Company: catalog (link / Drive / PDF upload)
 */
require_once 'layout-header.php';

$msg_success = '';
$msg_error   = '';
$tab         = isset($_GET['tab']) ? $_GET['tab'] : 'categories';
if (!in_array($tab, ['categories', 'subcategories', 'companies'], true)) $tab = 'categories';

$action  = isset($_GET['action']) ? $_GET['action'] : 'list';
$edit_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$conn) {
    echo "<main class='flex-1 p-6'><div class='p-4 bg-red-950/40 border border-red-800 text-red-200 text-sm rounded-xl'>ডাটাবেজ কানেক্টেড নেই!</div></main>";
    require_once 'layout-footer.php';
    exit;
}

ensure_product_hierarchy();

function admin_upload_file($field, $prefix_name = 'file', $allowed = ['jpg','jpeg','png','webp','gif','pdf']) {
    if (empty($_FILES[$field]) || ($_FILES[$field]['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        return '';
    }
    $ext = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed, true)) return '';
    $dir = '../uploads/';
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $fname = time() . '_' . $prefix_name . '_' . bin2hex(random_bytes(3)) . '.' . $ext;
    if (move_uploaded_file($_FILES[$field]['tmp_name'], $dir . $fname)) {
        return 'uploads/' . $fname;
    }
    return '';
}

// ─── Delete ───────────────────────────────────────────────────────────────
if ($action === 'delete' && $edit_id > 0) {
    if ($tab === 'companies') {
        $ok = delete_company($edit_id);
        $msg_success = $ok ? 'কোম্পানি মুছে ফেলা হয়েছে।' : '';
        $msg_error   = $ok ? '' : 'কোম্পানি মুছতে সমস্যা হয়েছে।';
    } elseif ($tab === 'subcategories') {
        $ok = delete_subcategory($edit_id);
        $msg_success = $ok ? 'সাব-ক্যাটাগরি মুছে ফেলা হয়েছে।' : '';
        $msg_error   = $ok ? '' : 'সাব-ক্যাটাগরি মুছতে সমস্যা হয়েছে।';
    } else {
        $ok = delete_category($edit_id);
        $msg_success = $ok ? 'ক্যাটাগরি মুছে ফেলা হয়েছে।' : '';
        $msg_error   = $ok ? '' : 'ক্যাটাগরি মুছতে সমস্যা হয়েছে।';
    }
    $action = 'list';
}

// ─── Save Category ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form_action']) && $_POST['form_action'] === 'save_category') {
    $tab = 'categories';
    $image_url = trim($_POST['image_url'] ?? '');
    $uploaded  = admin_upload_file('image_file', 'cat', ['jpg','jpeg','png','webp','gif']);
    if ($uploaded) $image_url = $uploaded;

    $data = [
        'name'       => trim($_POST['name'] ?? ''),
        'slug'       => trim($_POST['slug'] ?? ''),
        'icon'       => trim($_POST['icon'] ?? 'fa-folder'),
        'image_url'  => $image_url,
        'sort_order' => intval($_POST['sort_order'] ?? 0),
        'is_active'  => isset($_POST['is_active']) ? 1 : 0,
    ];
    $cat_id = intval($_POST['category_id'] ?? 0);

    if ($data['name'] === '') {
        $msg_error = 'ক্যাটাগরি নাম আবশ্যক।';
        $action = $cat_id > 0 ? 'edit' : 'add';
        $edit_id = $cat_id;
    } else {
        $ok = save_category($data, $cat_id);
        if ($ok) {
            $msg_success = 'ক্যাটাগরি সফলভাবে সেভ হয়েছে!';
            $action = 'list';
        } else {
            $msg_error = 'সেভ করতে সমস্যা হয়েছে (slug ইউনিক হতে পারে)।';
            $action = $cat_id > 0 ? 'edit' : 'add';
            $edit_id = $cat_id;
        }
    }
}

// ─── Save Subcategory ─────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form_action']) && $_POST['form_action'] === 'save_subcategory') {
    $tab = 'subcategories';
    $data = [
        'category_id' => intval($_POST['category_id'] ?? 0),
        'name'        => trim($_POST['name'] ?? ''),
        'slug'        => trim($_POST['slug'] ?? ''),
        'sort_order'  => intval($_POST['sort_order'] ?? 0),
        'is_active'   => isset($_POST['is_active']) ? 1 : 0,
    ];
    $sub_id = intval($_POST['subcategory_id'] ?? 0);

    if ($data['name'] === '' || $data['category_id'] <= 0) {
        $msg_error = 'সাব-ক্যাটাগরি নাম ও ক্যাটাগরি আবশ্যক।';
        $action = $sub_id > 0 ? 'edit' : 'add';
        $edit_id = $sub_id;
    } else {
        $ok = save_subcategory($data, $sub_id);
        if ($ok) {
            $msg_success = 'সাব-ক্যাটাগরি সফলভাবে সেভ হয়েছে!';
            $action = 'list';
        } else {
            $msg_error = 'সেভ করতে সমস্যা হয়েছে (slug ইউনিক হতে পারে)।';
            $action = $sub_id > 0 ? 'edit' : 'add';
            $edit_id = $sub_id;
        }
    }
}

// ─── Save Company ─────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form_action']) && $_POST['form_action'] === 'save_company') {
    $tab = 'companies';
    $catalog_url = trim($_POST['catalog_url'] ?? '');
    $uploaded_pdf = admin_upload_file('catalog_file', 'catalog', ['pdf']);
    if ($uploaded_pdf) $catalog_url = $uploaded_pdf;

    $data = [
        'category_id'    => intval($_POST['category_id'] ?? 0),
        'subcategory_id' => 0,
        'name'           => trim($_POST['name'] ?? ''),
        'slug'           => trim($_POST['slug'] ?? ''),
        'logo_url'       => trim($_POST['logo_url'] ?? ''),
        'catalog_url'    => $catalog_url,
        'is_active'      => isset($_POST['is_active']) ? 1 : 0,
    ];
    $comp_id = intval($_POST['company_id'] ?? 0);

    if ($data['name'] === '' || $data['category_id'] <= 0) {
        $msg_error = 'কোম্পানি নাম ও ক্যাটাগরি আবশ্যক।';
        $action = $comp_id > 0 ? 'edit' : 'add';
        $edit_id = $comp_id;
    } else {
        $ok = save_company($data, $comp_id);
        if ($ok) {
            $msg_success = 'কোম্পানি সফলভাবে সেভ হয়েছে!';
            $action = 'list';
        } else {
            $msg_error = 'সেভ করতে সমস্যা হয়েছে।';
            $action = $comp_id > 0 ? 'edit' : 'add';
            $edit_id = $comp_id;
        }
    }
}

$all_categories    = get_categories(false);
$all_subcategories = get_subcategories(null, false);
$all_companies     = get_all_companies();

$add_labels = [
    'categories'    => 'Add Category',
    'subcategories' => 'Add Sub-category',
    'companies'     => 'Add Company',
];
?>

<main class="flex-1 p-6 md:p-8 space-y-6">

    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-b border-slate-800/80 pb-5">
        <div>
            <h1 class="text-2xl font-black text-white uppercase tracking-wider">Product Hierarchy</h1>
            <p class="text-xs text-slate-400 mt-1">ক্যাটাগরি → সাব-ক্যাটাগরি → কোম্পানি ম্যানেজমেন্ট</p>
        </div>
        <?php if ($action === 'list'): ?>
        <a href="?tab=<?php echo $tab; ?>&action=add" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-black px-5 py-2.5 rounded-xl text-xs uppercase flex items-center">
            <i class="fa-solid fa-plus-circle mr-2"></i>
            <?php echo $add_labels[$tab]; ?>
        </a>
        <?php else: ?>
        <a href="?tab=<?php echo $tab; ?>" class="bg-slate-800 hover:bg-slate-700 text-slate-300 px-5 py-2.5 rounded-xl text-xs uppercase flex items-center">
            <i class="fa-solid fa-arrow-left mr-2"></i> Back
        </a>
        <?php endif; ?>
    </div>

    <?php if ($msg_success): ?>
    <div class="p-4 bg-emerald-950/40 border border-emerald-800 text-emerald-200 text-xs rounded-xl flex items-center">
        <i class="fa-solid fa-circle-check mr-3"></i> <?php echo htmlspecialchars($msg_success); ?>
    </div>
    <?php endif; ?>
    <?php if ($msg_error): ?>
    <div class="p-4 bg-red-950/40 border border-red-800 text-red-200 text-xs rounded-xl flex items-center">
        <i class="fa-solid fa-triangle-exclamation mr-3"></i> <?php echo htmlspecialchars($msg_error); ?>
    </div>
    <?php endif; ?>

    <div class="flex flex-wrap gap-2">
        <a href="?tab=categories" class="px-4 py-2 rounded-xl text-xs font-bold uppercase <?php echo $tab==='categories' ? 'bg-sky-500 text-slate-950' : 'bg-slate-800 text-slate-400 hover:text-white'; ?>">
            <i class="fa-solid fa-layer-group mr-1"></i> Categories (<?php echo count($all_categories); ?>)
        </a>
        <a href="?tab=subcategories" class="px-4 py-2 rounded-xl text-xs font-bold uppercase <?php echo $tab==='subcategories' ? 'bg-sky-500 text-slate-950' : 'bg-slate-800 text-slate-400 hover:text-white'; ?>">
            <i class="fa-solid fa-sitemap mr-1"></i> Sub-categories (<?php echo count($all_subcategories); ?>)
        </a>
        <a href="?tab=companies" class="px-4 py-2 rounded-xl text-xs font-bold uppercase <?php echo $tab==='companies' ? 'bg-sky-500 text-slate-950' : 'bg-slate-800 text-slate-400 hover:text-white'; ?>">
            <i class="fa-solid fa-building mr-1"></i> Companies (<?php echo count($all_companies); ?>)
        </a>
    </div>

    <?php if ($tab === 'categories' && ($action === 'add' || $action === 'edit')):
        $val = ['name'=>'','slug'=>'','icon'=>'fa-folder','image_url'=>'','sort_order'=>0,'is_active'=>1];
        if ($action === 'edit' && $edit_id > 0) {
            $existing = get_category_by_id($edit_id);
            if ($existing) $val = array_merge($val, $existing);
        }
    ?>
    <form method="post" enctype="multipart/form-data" class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 space-y-5 max-w-2xl">
        <input type="hidden" name="form_action" value="save_category">
        <?php if ($action === 'edit'): ?><input type="hidden" name="category_id" value="<?php echo $edit_id; ?>"><?php endif; ?>
        <h2 class="text-sm font-bold uppercase text-sky-400 border-b border-slate-800 pb-3">
            <?php echo $action === 'edit' ? 'Edit Category' : 'Add Category'; ?>
        </h2>
        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Name *</label>
            <input type="text" name="name" value="<?php echo htmlspecialchars($val['name']); ?>" required
                class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
        </div>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
                <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Slug <span class="text-slate-600 normal-case">(খালি রাখলে অটো)</span></label>
                <input type="text" name="slug" value="<?php echo htmlspecialchars($val['slug']); ?>"
                    placeholder="passenger-elevator" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            </div>
            <div>
                <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Icon (FontAwesome)</label>
                <input type="text" name="icon" value="<?php echo htmlspecialchars($val['icon']); ?>"
                    placeholder="fa-elevator" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            </div>
        </div>

        <div class="border border-slate-800 rounded-2xl p-4 space-y-3">
            <p class="text-xs font-bold uppercase text-slate-300">Mega Menu Hover Image</p>
            <p class="text-[10px] text-slate-500">Products মেনুতে category hover করলে পাশে যে ইমেজ দেখাবে</p>
            <?php if (!empty($val['image_url'])):
                $prev = (strpos($val['image_url'], 'http') === 0) ? $val['image_url'] : '../' . ltrim($val['image_url'], '/');
            ?>
            <img src="<?php echo htmlspecialchars($prev); ?>" alt="" class="w-full max-w-xs h-32 object-cover rounded-xl border border-slate-700">
            <?php endif; ?>
            <div>
                <label class="block text-[10px] font-bold uppercase text-slate-500 mb-1.5">Upload image</label>
                <input type="file" name="image_file" accept="image/*"
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2.5 text-xs text-slate-400 file:mr-3 file:py-1 file:px-3 file:rounded-lg file:border-0 file:bg-sky-500 file:text-slate-950 file:text-xs file:font-bold">
            </div>
            <div>
                <label class="block text-[10px] font-bold uppercase text-slate-500 mb-1.5">Or Image URL</label>
                <input type="text" name="image_url" value="<?php echo htmlspecialchars($val['image_url'] ?? ''); ?>"
                    placeholder="https://... or uploads/..." class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            </div>
        </div>

        <div class="grid grid-cols-2 gap-4">
            <div>
                <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Sort Order</label>
                <input type="number" name="sort_order" value="<?php echo (int)$val['sort_order']; ?>" min="0"
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            </div>
            <div class="flex items-end pb-2">
                <label class="flex items-center gap-3 cursor-pointer">
                    <input type="checkbox" name="is_active" value="1" <?php echo $val['is_active'] ? 'checked' : ''; ?> class="accent-sky-500 w-4 h-4">
                    <span class="text-sm font-semibold text-slate-300">Active</span>
                </label>
            </div>
        </div>
        <button type="submit" class="w-full bg-sky-500 hover:bg-sky-600 text-slate-950 font-black py-3.5 rounded-xl text-xs uppercase">
            <i class="fa-solid fa-floppy-disk mr-2"></i> Save Category
        </button>
    </form>

    <?php elseif ($tab === 'subcategories' && ($action === 'add' || $action === 'edit')):
        $val = ['category_id'=>0,'name'=>'','slug'=>'','sort_order'=>0,'is_active'=>1];
        if ($action === 'edit' && $edit_id > 0) {
            $existing = get_subcategory_by_id($edit_id);
            if ($existing) $val = array_merge($val, $existing);
        }
    ?>
    <form method="post" class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 space-y-5 max-w-2xl">
        <input type="hidden" name="form_action" value="save_subcategory">
        <?php if ($action === 'edit'): ?><input type="hidden" name="subcategory_id" value="<?php echo $edit_id; ?>"><?php endif; ?>
        <h2 class="text-sm font-bold uppercase text-sky-400 border-b border-slate-800 pb-3">
            <?php echo $action === 'edit' ? 'Edit Sub-category' : 'Add Sub-category'; ?>
        </h2>
        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Category *</label>
            <select name="category_id" required class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
                <option value="">— Select Category —</option>
                <?php foreach ($all_categories as $c): ?>
                <option value="<?php echo (int)$c['id']; ?>" <?php echo (int)$val['category_id'] === (int)$c['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($c['name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Name *</label>
            <input type="text" name="name" value="<?php echo htmlspecialchars($val['name']); ?>" required
                class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
        </div>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
                <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Slug <span class="text-slate-600 normal-case">(খালি রাখলে অটো)</span></label>
                <input type="text" name="slug" value="<?php echo htmlspecialchars($val['slug']); ?>"
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            </div>
            <div>
                <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Sort Order</label>
                <input type="number" name="sort_order" value="<?php echo (int)$val['sort_order']; ?>" min="0"
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            </div>
        </div>
        <label class="flex items-center gap-3 cursor-pointer">
            <input type="checkbox" name="is_active" value="1" <?php echo $val['is_active'] ? 'checked' : ''; ?> class="accent-sky-500 w-4 h-4">
            <span class="text-sm font-semibold text-slate-300">Active</span>
        </label>
        <button type="submit" class="w-full bg-sky-500 hover:bg-sky-600 text-slate-950 font-black py-3.5 rounded-xl text-xs uppercase">
            <i class="fa-solid fa-floppy-disk mr-2"></i> Save Sub-category
        </button>
    </form>

    <?php elseif ($tab === 'companies' && ($action === 'add' || $action === 'edit')):
        $val = ['category_id'=>0,'name'=>'','slug'=>'','logo_url'=>'','catalog_url'=>'','is_active'=>1];
        if ($action === 'edit' && $edit_id > 0) {
            $existing = get_company_by_id($edit_id);
            if ($existing) $val = array_merge($val, $existing);
        }
    ?>
    <form method="post" enctype="multipart/form-data" class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 space-y-5 max-w-2xl">
        <input type="hidden" name="form_action" value="save_company">
        <?php if ($action === 'edit'): ?><input type="hidden" name="company_id" value="<?php echo $edit_id; ?>"><?php endif; ?>
        <h2 class="text-sm font-bold uppercase text-sky-400 border-b border-slate-800 pb-3">
            <?php echo $action === 'edit' ? 'Edit Company' : 'Add Company'; ?>
        </h2>
        <div class="p-3 rounded-xl bg-sky-500/10 border border-sky-500/30 text-[11px] text-sky-200 leading-relaxed">
            কোম্পানি এখন <strong>ক্যাটাগরি লেভেলে</strong> — সব সাব-ক্যাটাগরিতে একই ব্র্যান্ড দেখাবে। ক্যাটালগ একবার দিলেই যথেষ্ট।
        </div>
        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Category *</label>
            <select name="category_id" required class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
                <option value="">— Select Category —</option>
                <?php foreach ($all_categories as $c): ?>
                <option value="<?php echo (int)$c['id']; ?>" <?php echo (int)$val['category_id'] === (int)$c['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($c['name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Company Name *</label>
            <input type="text" name="name" value="<?php echo htmlspecialchars($val['name']); ?>" required
                placeholder="Otis, Perkins, LONGi..." class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
        </div>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
                <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Slug <span class="text-slate-600 normal-case">(খালি রাখলে অটো)</span></label>
                <input type="text" name="slug" value="<?php echo htmlspecialchars($val['slug']); ?>"
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            </div>
            <div>
                <label class="block text-xs font-bold uppercase text-slate-400 mb-2">Logo URL <span class="text-slate-600 normal-case">(optional)</span></label>
                <input type="text" name="logo_url" value="<?php echo htmlspecialchars($val['logo_url']); ?>"
                    placeholder="https://..." class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            </div>
        </div>

        <div class="border border-slate-800 rounded-2xl p-4 space-y-3">
            <p class="text-xs font-bold uppercase text-slate-300">Product Catalog (PDF) — একবার</p>
            <p class="text-[10px] text-slate-500">Google Drive লিংক, hosting URL, অথবা সরাসরি PDF আপলোড</p>
            <?php if (!empty($val['catalog_url'])): ?>
            <p class="text-[11px] text-emerald-400 break-all"><i class="fa-solid fa-file-pdf mr-1"></i><?php echo htmlspecialchars($val['catalog_url']); ?></p>
            <?php endif; ?>
            <div>
                <label class="block text-[10px] font-bold uppercase text-slate-500 mb-1.5">Upload PDF</label>
                <input type="file" name="catalog_file" accept="application/pdf,.pdf"
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2.5 text-xs text-slate-400 file:mr-3 file:py-1 file:px-3 file:rounded-lg file:border-0 file:bg-sky-500 file:text-slate-950 file:text-xs file:font-bold">
            </div>
            <div>
                <label class="block text-[10px] font-bold uppercase text-slate-500 mb-1.5">Or Catalog Link (Drive / URL)</label>
                <input type="text" name="catalog_url" value="<?php echo htmlspecialchars($val['catalog_url'] ?? ''); ?>"
                    placeholder="https://drive.google.com/... or https://yoursite.com/file.pdf"
                    class="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
            </div>
        </div>

        <label class="flex items-center gap-3 cursor-pointer">
            <input type="checkbox" name="is_active" value="1" <?php echo $val['is_active'] ? 'checked' : ''; ?> class="accent-sky-500 w-4 h-4">
            <span class="text-sm font-semibold text-slate-300">Active</span>
        </label>
        <button type="submit" class="w-full bg-sky-500 hover:bg-sky-600 text-slate-950 font-black py-3.5 rounded-xl text-xs uppercase">
            <i class="fa-solid fa-floppy-disk mr-2"></i> Save Company
        </button>
    </form>

    <?php elseif ($tab === 'categories'): ?>
    <div class="bg-slate-900 border border-slate-800/80 rounded-2xl overflow-hidden">
        <table class="w-full text-left text-sm">
            <thead class="bg-slate-950 text-[10px] uppercase text-slate-500 tracking-wider">
                <tr>
                    <th class="px-4 py-3">#</th>
                    <th class="px-4 py-3">Name</th>
                    <th class="px-4 py-3 hidden sm:table-cell">Image</th>
                    <th class="px-4 py-3 hidden md:table-cell">Icon</th>
                    <th class="px-4 py-3">Status</th>
                    <th class="px-4 py-3 text-right">Action</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-800/80">
                <?php if (empty($all_categories)): ?>
                <tr><td colspan="6" class="px-4 py-10 text-center text-slate-500 text-xs">কোনো ক্যাটাগরি নেই।</td></tr>
                <?php else: foreach ($all_categories as $i => $c): ?>
                <tr class="hover:bg-slate-800/40">
                    <td class="px-4 py-3 text-slate-500"><?php echo $i + 1; ?></td>
                    <td class="px-4 py-3 font-semibold text-white"><?php echo htmlspecialchars($c['name']); ?></td>
                    <td class="px-4 py-3 hidden sm:table-cell">
                        <?php if (!empty($c['image_url'])):
                            $thumb = (strpos($c['image_url'], 'http') === 0) ? $c['image_url'] : '../' . ltrim($c['image_url'], '/');
                        ?>
                        <img src="<?php echo htmlspecialchars($thumb); ?>" class="w-12 h-10 object-cover rounded-lg border border-slate-700" alt="">
                        <?php else: ?>
                        <span class="text-slate-600 text-xs">—</span>
                        <?php endif; ?>
                    </td>
                    <td class="px-4 py-3 text-sky-400 hidden md:table-cell"><i class="fa-solid <?php echo htmlspecialchars($c['icon'] ?: 'fa-folder'); ?>"></i></td>
                    <td class="px-4 py-3">
                        <span class="text-[9px] font-bold uppercase px-2 py-0.5 rounded-full <?php echo $c['is_active'] ? 'bg-emerald-500/20 text-emerald-400' : 'bg-slate-700 text-slate-400'; ?>">
                            <?php echo $c['is_active'] ? 'Active' : 'Off'; ?>
                        </span>
                    </td>
                    <td class="px-4 py-3 text-right space-x-1">
                        <a href="?tab=categories&action=edit&id=<?php echo (int)$c['id']; ?>" class="inline-block px-3 py-1.5 bg-slate-800 hover:bg-sky-500 hover:text-slate-950 text-sky-400 rounded-lg text-xs font-bold">Edit</a>
                        <a href="?tab=categories&action=delete&id=<?php echo (int)$c['id']; ?>" onclick="return confirm('ক্যাটাগরি মুছবেন?');"
                            class="inline-block px-3 py-1.5 bg-slate-800 hover:bg-red-500 hover:text-white text-red-400 rounded-lg text-xs"><i class="fa-solid fa-trash"></i></a>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>

    <?php elseif ($tab === 'subcategories'): ?>
    <div class="bg-slate-900 border border-slate-800/80 rounded-2xl overflow-hidden">
        <table class="w-full text-left text-sm">
            <thead class="bg-slate-950 text-[10px] uppercase text-slate-500 tracking-wider">
                <tr>
                    <th class="px-4 py-3">#</th>
                    <th class="px-4 py-3">Sub-category</th>
                    <th class="px-4 py-3">Category</th>
                    <th class="px-4 py-3 hidden sm:table-cell">Slug</th>
                    <th class="px-4 py-3">Status</th>
                    <th class="px-4 py-3 text-right">Action</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-800/80">
                <?php if (empty($all_subcategories)): ?>
                <tr><td colspan="6" class="px-4 py-10 text-center text-slate-500 text-xs">কোনো সাব-ক্যাটাগরি নেই।</td></tr>
                <?php else: foreach ($all_subcategories as $i => $sc): ?>
                <tr class="hover:bg-slate-800/40">
                    <td class="px-4 py-3 text-slate-500"><?php echo $i + 1; ?></td>
                    <td class="px-4 py-3 font-semibold text-white"><?php echo htmlspecialchars($sc['name']); ?></td>
                    <td class="px-4 py-3 text-slate-400 text-xs"><?php echo htmlspecialchars($sc['category_name'] ?: '—'); ?></td>
                    <td class="px-4 py-3 text-slate-400 hidden sm:table-cell text-xs"><?php echo htmlspecialchars($sc['slug']); ?></td>
                    <td class="px-4 py-3">
                        <span class="text-[9px] font-bold uppercase px-2 py-0.5 rounded-full <?php echo $sc['is_active'] ? 'bg-emerald-500/20 text-emerald-400' : 'bg-slate-700 text-slate-400'; ?>">
                            <?php echo $sc['is_active'] ? 'Active' : 'Off'; ?>
                        </span>
                    </td>
                    <td class="px-4 py-3 text-right space-x-1">
                        <a href="?tab=subcategories&action=edit&id=<?php echo (int)$sc['id']; ?>" class="inline-block px-3 py-1.5 bg-slate-800 hover:bg-sky-500 hover:text-slate-950 text-sky-400 rounded-lg text-xs font-bold">Edit</a>
                        <a href="?tab=subcategories&action=delete&id=<?php echo (int)$sc['id']; ?>" onclick="return confirm('সাব-ক্যাটাগরি মুছবেন?');"
                            class="inline-block px-3 py-1.5 bg-slate-800 hover:bg-red-500 hover:text-white text-red-400 rounded-lg text-xs"><i class="fa-solid fa-trash"></i></a>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>

    <?php else: ?>
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-3">
        <p class="text-[11px] text-slate-400">এক কোম্পানি = এক ক্যাটালগ (ক্যাটাগরির সব সাব-ক্যাটাগরিতে শেয়ার)</p>
        <a href="../install-nine.php" class="inline-flex items-center gap-2 text-[10px] font-bold uppercase bg-amber-500/20 text-amber-300 border border-amber-500/40 px-3 py-2 rounded-lg hover:bg-amber-500/30">
            <i class="fa-solid fa-object-group"></i> Merge Duplicate Companies
        </a>
    </div>
    <div class="bg-slate-900 border border-slate-800/80 rounded-2xl overflow-hidden">
        <table class="w-full text-left text-sm">
            <thead class="bg-slate-950 text-[10px] uppercase text-slate-500 tracking-wider">
                <tr>
                    <th class="px-4 py-3">#</th>
                    <th class="px-4 py-3">Company</th>
                    <th class="px-4 py-3">Category</th>
                    <th class="px-4 py-3 hidden md:table-cell">Catalog</th>
                    <th class="px-4 py-3">Status</th>
                    <th class="px-4 py-3 text-right">Action</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-800/80">
                <?php if (empty($all_companies)): ?>
                <tr><td colspan="6" class="px-4 py-10 text-center text-slate-500 text-xs">কোনো কোম্পানি নেই।</td></tr>
                <?php else: foreach ($all_companies as $i => $co): ?>
                <tr class="hover:bg-slate-800/40">
                    <td class="px-4 py-3 text-slate-500"><?php echo $i + 1; ?></td>
                    <td class="px-4 py-3 font-semibold text-white"><?php echo htmlspecialchars($co['name']); ?></td>
                    <td class="px-4 py-3 text-slate-400 text-xs"><?php echo htmlspecialchars($co['category_name'] ?: '—'); ?></td>
                    <td class="px-4 py-3 hidden md:table-cell text-xs">
                        <?php if (!empty($co['catalog_url'])): ?>
                        <span class="text-emerald-400"><i class="fa-solid fa-file-pdf mr-1"></i>Yes</span>
                        <?php else: ?>
                        <span class="text-slate-600">—</span>
                        <?php endif; ?>
                    </td>
                    <td class="px-4 py-3">
                        <span class="text-[9px] font-bold uppercase px-2 py-0.5 rounded-full <?php echo $co['is_active'] ? 'bg-emerald-500/20 text-emerald-400' : 'bg-slate-700 text-slate-400'; ?>">
                            <?php echo $co['is_active'] ? 'Active' : 'Off'; ?>
                        </span>
                    </td>
                    <td class="px-4 py-3 text-right space-x-1">
                        <a href="?tab=companies&action=edit&id=<?php echo (int)$co['id']; ?>" class="inline-block px-3 py-1.5 bg-slate-800 hover:bg-sky-500 hover:text-slate-950 text-sky-400 rounded-lg text-xs font-bold">Edit</a>
                        <a href="?tab=companies&action=delete&id=<?php echo (int)$co['id']; ?>" onclick="return confirm('কোম্পানি মুছবেন?');"
                            class="inline-block px-3 py-1.5 bg-slate-800 hover:bg-red-500 hover:text-white text-red-400 rounded-lg text-xs"><i class="fa-solid fa-trash"></i></a>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>

</main>

<?php
require_once 'layout-footer.php';
@unlink(__DIR__ . '/categories-clean-tmp.php');
?>
