📁 File Manager
Editing:
/home/wvl7mof7402e/public_html/chem/admin/categories.php
<?php /** * Pure Chemical Admin * Categories Management * * Uses existing `categories` table only. * No new table required. */ if (session_status() === PHP_SESSION_NONE) { session_start(); } /* |-------------------------------------------------------------------------- | Database |-------------------------------------------------------------------------- */ $dbCandidates = [ __DIR__ . '/includes/db.php', __DIR__ . '/db.php', ]; $dbLoaded = false; foreach ($dbCandidates as $dbFile) { if (file_exists($dbFile)) { require_once $dbFile; $dbLoaded = true; break; } } if (!$dbLoaded || !isset($pdo) || !($pdo instanceof PDO)) { http_response_code(500); exit('Database connection not available.'); } /* |-------------------------------------------------------------------------- | Auth |-------------------------------------------------------------------------- */ $authCandidates = [ __DIR__ . '/includes/auth.php', __DIR__ . '/auth.php', ]; foreach ($authCandidates as $authFile) { if (file_exists($authFile)) { require_once $authFile; break; } } /* |-------------------------------------------------------------------------- | Functions |-------------------------------------------------------------------------- */ $functionCandidates = [ __DIR__ . '/includes/functions.php', __DIR__ . '/functions.php', ]; foreach ($functionCandidates as $functionFile) { if (file_exists($functionFile)) { require_once $functionFile; break; } } /* |-------------------------------------------------------------------------- | CSRF |-------------------------------------------------------------------------- */ $csrfCandidates = [ __DIR__ . '/includes/csrf.php', __DIR__ . '/csrf.php', ]; foreach ($csrfCandidates as $csrfFile) { if (file_exists($csrfFile)) { require_once $csrfFile; break; } } /* |-------------------------------------------------------------------------- | Fallback helpers |-------------------------------------------------------------------------- */ if (!function_exists('e')) { function e($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); } } if (!function_exists('slugify')) { function slugify(string $text): string { $text = trim($text); if ($text === '') { return ''; } $text = strtolower($text); $text = preg_replace('/[^a-z0-9]+/i', '-', $text); $text = trim($text, '-'); return $text ?: ''; } } if (!function_exists('csrf_token')) { function csrf_token(): string { if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } return $_SESSION['csrf_token']; } } if (!function_exists('csrf_field')) { function csrf_field(): string { return '<input type="hidden" name="csrf_token" value="' . e(csrf_token()) . '">'; } } if (!function_exists('verify_csrf')) { function verify_csrf(): bool { $token = $_POST['csrf_token'] ?? ''; return !empty($token) && !empty($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token); } } /* |-------------------------------------------------------------------------- | Admin authentication fallback |-------------------------------------------------------------------------- */ if (function_exists('requireAdmin')) { requireAdmin(); } else { if ( empty($_SESSION['admin_id']) && empty($_SESSION['admin_logged_in']) ) { header('Location: login.php'); exit; } } /* |-------------------------------------------------------------------------- | Variables |-------------------------------------------------------------------------- */ $page_title = 'Categories'; $active_menu = 'categories'; $message = ''; $message_type = ''; $allowedTypes = [ 'product', 'industry', 'service', 'blog', 'document', ]; /* |-------------------------------------------------------------------------- | Detect category_type enum dynamically |-------------------------------------------------------------------------- | | This prevents an invalid enum value if the actual DB enum differs. | */ $categoryTypes = []; try { $columnStmt = $pdo->query("SHOW COLUMNS FROM categories LIKE 'category_type'"); $columnInfo = $columnStmt->fetch(); if ($columnInfo && !empty($columnInfo['Type'])) { if (preg_match("/^enum\((.*)\)$/i", $columnInfo['Type'], $matches)) { $enumString = $matches[1]; $categoryTypes = str_getcsv( $enumString, ',', "'" ); $categoryTypes = array_values( array_filter( array_map('trim', $categoryTypes), static function ($value) { return $value !== ''; } ) ); } } } catch (Throwable $e) { $categoryTypes = []; } if (empty($categoryTypes)) { $categoryTypes = $allowedTypes; } /* |-------------------------------------------------------------------------- | Current edit ID |-------------------------------------------------------------------------- */ $editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0; $editingCategory = null; /* |-------------------------------------------------------------------------- | POST Actions |-------------------------------------------------------------------------- */ if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (!verify_csrf()) { $message = 'Security verification failed. Please refresh the page and try again.'; $message_type = 'error'; } else { $action = $_POST['action'] ?? ''; /* |-------------------------------------------------------------------------- | SAVE CATEGORY |-------------------------------------------------------------------------- */ if ($action === 'save') { $id = (int)($_POST['id'] ?? 0); $parentId = (int)($_POST['parent_id'] ?? 0); $categoryType = trim($_POST['category_type'] ?? ''); $name = trim($_POST['name'] ?? ''); $slug = trim($_POST['slug'] ?? ''); $shortDesc = trim($_POST['short_description'] ?? ''); $description = trim($_POST['description'] ?? ''); $imageId = trim($_POST['image_id'] ?? ''); $bannerId = trim($_POST['banner_id'] ?? ''); $sortOrder = (int)($_POST['sort_order'] ?? 0); $status = isset($_POST['status']) ? 1 : 0; /* |-------------------------------------------------------------------------- | Validation |-------------------------------------------------------------------------- */ if ($categoryType === '') { $message = 'Please select category type.'; $message_type = 'error'; } elseif (!in_array($categoryType, $categoryTypes, true)) { $message = 'Invalid category type selected.'; $message_type = 'error'; } elseif ($name === '') { $message = 'Category name is required.'; $message_type = 'error'; } else { /* |-------------------------------------------------------------------------- | Slug |-------------------------------------------------------------------------- */ if ($slug === '') { $slug = slugify($name); } else { $slug = slugify($slug); } if ($slug === '') { $message = 'Please provide a valid category name or slug.'; $message_type = 'error'; } else { /* |-------------------------------------------------------------------------- | Parent validation |-------------------------------------------------------------------------- */ if ($parentId > 0) { if ($id > 0 && $parentId === $id) { $message = 'A category cannot be its own parent.'; $message_type = 'error'; } else { $parentCheck = $pdo->prepare(" SELECT id FROM categories WHERE id = ? LIMIT 1 "); $parentCheck->execute([$parentId]); if (!$parentCheck->fetchColumn()) { $parentId = 0; } } } /* |-------------------------------------------------------------------------- | Slug duplicate check |-------------------------------------------------------------------------- */ if ($message_type !== 'error') { $slugSql = " SELECT id FROM categories WHERE slug = ? "; $slugParams = [$slug]; if ($id > 0) { $slugSql .= " AND id != ?"; $slugParams[] = $id; } $slugSql .= " LIMIT 1"; $slugStmt = $pdo->prepare($slugSql); $slugStmt->execute($slugParams); if ($slugStmt->fetchColumn()) { /* |-------------------------------------------------------------------------- | Make unique slug automatically |-------------------------------------------------------------------------- */ $baseSlug = $slug; $counter = 2; while (true) { $newSlug = $baseSlug . '-' . $counter; $checkSql = " SELECT id FROM categories WHERE slug = ? "; $checkParams = [$newSlug]; if ($id > 0) { $checkSql .= " AND id != ?"; $checkParams[] = $id; } $checkSql .= " LIMIT 1"; $checkStmt = $pdo->prepare($checkSql); $checkStmt->execute($checkParams); if (!$checkStmt->fetchColumn()) { $slug = $newSlug; break; } $counter++; if ($counter > 9999) { $message = 'Unable to generate a unique slug.'; $message_type = 'error'; break; } } } } /* |-------------------------------------------------------------------------- | Save |-------------------------------------------------------------------------- */ if ($message_type !== 'error') { $imageValue = ($imageId !== '' && ctype_digit($imageId)) ? (int)$imageId : null; $bannerValue = ($bannerId !== '' && ctype_digit($bannerId)) ? (int)$bannerId : null; if ($id > 0) { $update = $pdo->prepare(" UPDATE categories SET parent_id = ?, category_type = ?, name = ?, slug = ?, short_description = ?, description = ?, image_id = ?, banner_id = ?, sort_order = ?, status = ? WHERE id = ? LIMIT 1 "); $update->execute([ $parentId > 0 ? $parentId : null, $categoryType, $name, $slug, $shortDesc !== '' ? $shortDesc : null, $description !== '' ? $description : null, $imageValue, $bannerValue, $sortOrder, $status, $id ]); $message = 'Category updated successfully.'; $message_type = 'success'; } else { $insert = $pdo->prepare(" INSERT INTO categories ( parent_id, category_type, name, slug, short_description, description, image_id, banner_id, sort_order, status ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) "); $insert->execute([ $parentId > 0 ? $parentId : null, $categoryType, $name, $slug, $shortDesc !== '' ? $shortDesc : null, $description !== '' ? $description : null, $imageValue, $bannerValue, $sortOrder, $status ]); $message = 'Category created successfully.'; $message_type = 'success'; } /* |-------------------------------------------------------------------------- | Reset edit mode |-------------------------------------------------------------------------- */ $editId = 0; $editingCategory = null; } } } } /* |-------------------------------------------------------------------------- | DELETE |-------------------------------------------------------------------------- */ elseif ($action === 'delete') { $id = (int)($_POST['id'] ?? 0); if ($id <= 0) { $message = 'Invalid category ID.'; $message_type = 'error'; } else { try { /* |-------------------------------------------------------------------------- | Check children |-------------------------------------------------------------------------- */ $childStmt = $pdo->prepare(" SELECT COUNT(*) FROM categories WHERE parent_id = ? "); $childStmt->execute([$id]); $childCount = (int)$childStmt->fetchColumn(); if ($childCount > 0) { $message = 'This category has child categories. Please move or delete the child categories first.'; $message_type = 'error'; } else { /* |-------------------------------------------------------------------------- | Delete category |-------------------------------------------------------------------------- */ $delete = $pdo->prepare(" DELETE FROM categories WHERE id = ? LIMIT 1 "); $delete->execute([$id]); if ($delete->rowCount() > 0) { $message = 'Category deleted successfully.'; $message_type = 'success'; } else { $message = 'Category not found.'; $message_type = 'error'; } } } catch (Throwable $e) { $message = 'Category could not be deleted because it is being used by other records.'; $message_type = 'error'; } } } /* |-------------------------------------------------------------------------- | SINGLE STATUS |-------------------------------------------------------------------------- */ elseif ($action === 'toggle_status') { $id = (int)($_POST['id'] ?? 0); if ($id > 0) { $stmt = $pdo->prepare(" UPDATE categories SET status = IF(status = 1, 0, 1) WHERE id = ? LIMIT 1 "); $stmt->execute([$id]); $message = 'Category status updated.'; $message_type = 'success'; } } /* |-------------------------------------------------------------------------- | BULK STATUS |-------------------------------------------------------------------------- */ elseif ($action === 'bulk_status') { $ids = $_POST['selected_ids'] ?? []; $bulkStatus = isset($_POST['bulk_status']) ? (int)$_POST['bulk_status'] : -1; if ( !is_array($ids) || empty($ids) || !in_array($bulkStatus, [0, 1], true) ) { $message = 'Please select categories and a valid status.'; $message_type = 'error'; } else { $cleanIds = []; foreach ($ids as $selectedId) { $selectedId = (int)$selectedId; if ($selectedId > 0) { $cleanIds[] = $selectedId; } } $cleanIds = array_values(array_unique($cleanIds)); if (!empty($cleanIds)) { $placeholders = implode( ',', array_fill(0, count($cleanIds), '?') ); $stmt = $pdo->prepare(" UPDATE categories SET status = ? WHERE id IN ($placeholders) "); $stmt->execute( array_merge([$bulkStatus], $cleanIds) ); $message = count($cleanIds) . ' categor' . (count($cleanIds) === 1 ? 'y' : 'ies') . ' updated successfully.'; $message_type = 'success'; } } } } } /* |-------------------------------------------------------------------------- | Load edit category |-------------------------------------------------------------------------- */ if ($editId > 0) { $editStmt = $pdo->prepare(" SELECT * FROM categories WHERE id = ? LIMIT 1 "); $editStmt->execute([$editId]); $editingCategory = $editStmt->fetch(); if (!$editingCategory) { $editId = 0; } } /* |-------------------------------------------------------------------------- | Filters |-------------------------------------------------------------------------- */ $search = trim($_GET['search'] ?? ''); $type = trim($_GET['type'] ?? ''); $status = $_GET['status'] ?? ''; $page = max( 1, (int)($_GET['page'] ?? 1) ); $perPage = 12; if ($type !== '' && !in_array($type, $categoryTypes, true)) { $type = ''; } if (!in_array($status, ['', '1', '0'], true)) { $status = ''; } /* |-------------------------------------------------------------------------- | Build WHERE |-------------------------------------------------------------------------- */ $where = []; $params = []; if ($search !== '') { $where[] = " ( c.name LIKE ? OR c.slug LIKE ? OR c.short_description LIKE ? OR c.description LIKE ? ) "; $likeSearch = '%' . $search . '%'; $params[] = $likeSearch; $params[] = $likeSearch; $params[] = $likeSearch; $params[] = $likeSearch; } if ($type !== '') { $where[] = "c.category_type = ?"; $params[] = $type; } if ($status !== '') { $where[] = "c.status = ?"; $params[] = (int)$status; } $whereSql = ''; if (!empty($where)) { $whereSql = 'WHERE ' . implode(' AND ', $where); } /* |-------------------------------------------------------------------------- | Statistics |-------------------------------------------------------------------------- */ $stats = [ 'total' => 0, 'active' => 0, 'inactive' => 0, 'parents' => 0, ]; try { $stats['total'] = (int)$pdo ->query("SELECT COUNT(*) FROM categories") ->fetchColumn(); $stats['active'] = (int)$pdo ->query("SELECT COUNT(*) FROM categories WHERE status = 1") ->fetchColumn(); $stats['inactive'] = (int)$pdo ->query("SELECT COUNT(*) FROM categories WHERE status = 0") ->fetchColumn(); $stats['parents'] = (int)$pdo ->query(" SELECT COUNT(*) FROM categories WHERE parent_id IS NULL OR parent_id = 0 ") ->fetchColumn(); } catch (Throwable $e) { // Keep page working even if statistics query fails. } /* |-------------------------------------------------------------------------- | Count filtered records |-------------------------------------------------------------------------- */ $countSql = " SELECT COUNT(*) FROM categories c $whereSql "; $countStmt = $pdo->prepare($countSql); $countStmt->execute($params); $totalRows = (int)$countStmt->fetchColumn(); $totalPages = max( 1, (int)ceil($totalRows / $perPage) ); if ($page > $totalPages) { $page = $totalPages; } $offset = ($page - 1) * $perPage; /* |-------------------------------------------------------------------------- | Category List |-------------------------------------------------------------------------- */ $listSql = " SELECT c.*, p.name AS parent_name FROM categories c LEFT JOIN categories p ON p.id = c.parent_id $whereSql ORDER BY c.sort_order ASC, c.id DESC LIMIT $perPage OFFSET $offset "; $listStmt = $pdo->prepare($listSql); $listStmt->execute($params); $categories = $listStmt->fetchAll(); /* |-------------------------------------------------------------------------- | Parent Categories |-------------------------------------------------------------------------- | | Load all categories so nested parent dropdown can work. | */ $allCategoriesStmt = $pdo->query(" SELECT id, parent_id, category_type, name, status FROM categories ORDER BY category_type ASC, sort_order ASC, name ASC "); $allCategories = $allCategoriesStmt->fetchAll(); /* |-------------------------------------------------------------------------- | Parent tree helper |-------------------------------------------------------------------------- */ function buildCategoryTree(array $items, $parentId = null, int $level = 0, int $excludeId = 0): array { $tree = []; foreach ($items as $item) { $itemParent = $item['parent_id']; $itemParent = ($itemParent === null || (int)$itemParent === 0) ? null : (int)$itemParent; $normalizedParent = $parentId === null ? null : (int)$parentId; if ($itemParent !== $normalizedParent) { continue; } if ((int)$item['id'] === $excludeId) { continue; } $item['_level'] = $level; $tree[] = $item; $children = buildCategoryTree( $items, (int)$item['id'], $level + 1, $excludeId ); foreach ($children as $child) { $tree[] = $child; } } return $tree; } $parentOptions = buildCategoryTree( $allCategories, null, 0, $editId ); /* |-------------------------------------------------------------------------- | Pagination URL helper |-------------------------------------------------------------------------- */ function categoryPageUrl(int $pageNumber): string { $query = $_GET; $query['page'] = $pageNumber; return '?' . http_build_query($query); } /* |-------------------------------------------------------------------------- | Header |-------------------------------------------------------------------------- | | Existing includes/header.php already contains: | - Sidebar | - Topbar | - Admin layout | */ $headerLoaded = false; $headerCandidates = [ __DIR__ . '/includes/header.php', __DIR__ . '/header.php', ]; foreach ($headerCandidates as $headerFile) { if (file_exists($headerFile)) { require_once $headerFile; $headerLoaded = true; break; } } if (!$headerLoaded) { ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><?= e($page_title) ?> | Pure Chemical Admin</title> </head> <body> <?php } ?> <style> /* ========================================================= PURE CHEMICAL — CATEGORIES PREMIUM MODERN ADMIN UI ========================================================= */ .pc-category-page { --pc-primary: #2563eb; --pc-primary-dark: #1d4ed8; --pc-success: #059669; --pc-warning: #d97706; --pc-danger: #dc2626; --pc-text: #172033; --pc-muted: #64748b; --pc-border: #e6eaf0; --pc-bg: #f6f8fb; --pc-white: #ffffff; padding: 26px; background: var(--pc-bg); min-height: calc(100vh - 80px); color: var(--pc-text); } /* Header */ .pc-page-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 20px; margin-bottom: 24px; } .pc-page-title { margin: 0; font-size: 27px; line-height: 1.2; font-weight: 800; letter-spacing: -0.5px; } .pc-page-subtitle { margin: 7px 0 0; color: var(--pc-muted); font-size: 14px; } .pc-primary-btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 44px; padding: 0 17px; border: 0; border-radius: 12px; background: var(--pc-primary); color: #fff; text-decoration: none; font-weight: 700; font-size: 13px; cursor: pointer; box-shadow: 0 8px 20px rgba(37, 99, 235, .18); transition: .2s ease; } .pc-primary-btn:hover { background: var(--pc-primary-dark); color: #fff; transform: translateY(-1px); } /* Alerts */ .pc-alert { display: flex; align-items: center; gap: 11px; padding: 14px 16px; margin-bottom: 20px; border-radius: 13px; font-size: 14px; font-weight: 600; } .pc-alert-success { background: #ecfdf5; color: #047857; border: 1px solid #bbf7d0; } .pc-alert-error { background: #fef2f2; color: #b91c1c; border: 1px solid #fecaca; } /* Stats */ .pc-stat-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; margin-bottom: 22px; } .pc-stat-card { position: relative; overflow: hidden; background: #fff; border: 1px solid var(--pc-border); border-radius: 17px; padding: 19px; box-shadow: 0 8px 28px rgba(15, 23, 42, .045); } .pc-stat-card::after { content: ""; position: absolute; width: 75px; height: 75px; right: -28px; top: -28px; border-radius: 50%; background: rgba(37, 99, 235, .055); } .pc-stat-top { display: flex; align-items: center; justify-content: space-between; gap: 10px; } .pc-stat-label { color: var(--pc-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: .5px; } .pc-stat-icon { width: 38px; height: 38px; display: flex; align-items: center; justify-content: center; border-radius: 11px; background: #eff6ff; color: var(--pc-primary); font-size: 16px; } .pc-stat-value { margin-top: 13px; font-size: 27px; line-height: 1; font-weight: 800; } /* Main Grid */ .pc-content-grid { display: grid; grid-template-columns: minmax(330px, 390px) minmax(0, 1fr); gap: 20px; align-items: start; } /* Cards */ .pc-card { background: #fff; border: 1px solid var(--pc-border); border-radius: 17px; box-shadow: 0 8px 28px rgba(15, 23, 42, .045); overflow: hidden; } .pc-card-head { padding: 18px 20px; border-bottom: 1px solid var(--pc-border); display: flex; justify-content: space-between; align-items: center; gap: 12px; } .pc-card-title { margin: 0; font-size: 16px; font-weight: 800; } .pc-card-desc { margin: 4px 0 0; color: var(--pc-muted); font-size: 12px; } .pc-card-body { padding: 20px; } /* Form */ .pc-form-group { margin-bottom: 16px; } .pc-form-label { display: block; margin-bottom: 7px; color: #334155; font-size: 12px; font-weight: 750; } .pc-required { color: var(--pc-danger); } .pc-input, .pc-select, .pc-textarea { width: 100%; border: 1px solid #dce2ea; border-radius: 11px; background: #fff; color: #172033; padding: 11px 12px; font-size: 13px; outline: none; transition: .2s ease; box-sizing: border-box; } .pc-input:focus, .pc-select:focus, .pc-textarea:focus { border-color: #93c5fd; box-shadow: 0 0 0 4px rgba(37, 99, 235, .08); } .pc-textarea { min-height: 100px; resize: vertical; line-height: 1.6; } .pc-input-help { margin-top: 6px; color: #94a3b8; font-size: 11px; } .pc-form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } .pc-checkbox-row { display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 10px 12px; border: 1px solid #e2e8f0; border-radius: 11px; background: #fafbfc; } .pc-checkbox-row input { width: 17px; height: 17px; accent-color: var(--pc-primary); } .pc-checkbox-label { font-size: 13px; font-weight: 650; } .pc-form-actions { display: flex; gap: 9px; margin-top: 19px; } .pc-btn { display: inline-flex; align-items: center; justify-content: center; gap: 7px; min-height: 41px; padding: 0 14px; border-radius: 10px; border: 1px solid transparent; font-size: 12px; font-weight: 750; text-decoration: none; cursor: pointer; transition: .2s ease; } .pc-btn-primary { background: var(--pc-primary); color: #fff; } .pc-btn-primary:hover { background: var(--pc-primary-dark); color: #fff; } .pc-btn-light { background: #f8fafc; color: #475569; border-color: #e2e8f0; } .pc-btn-light:hover { background: #f1f5f9; } .pc-btn-danger { background: #fef2f2; color: #b91c1c; border-color: #fecaca; } .pc-btn-danger:hover { background: #fee2e2; } .pc-btn-success { background: #ecfdf5; color: #047857; border-color: #bbf7d0; } .pc-btn-sm { min-height: 34px; padding: 0 10px; border-radius: 8px; font-size: 11px; } /* Filter */ .pc-filter { padding: 16px 18px; border-bottom: 1px solid var(--pc-border); background: #fcfdff; } .pc-filter-grid { display: grid; grid-template-columns: minmax(180px, 1.5fr) 160px 140px auto; gap: 9px; } .pc-search-wrap { position: relative; } .pc-search-wrap svg { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #94a3b8; pointer-events: none; } .pc-search-wrap .pc-input { padding-left: 38px; } /* Table */ .pc-table-wrap { overflow-x: auto; } .pc-table { width: 100%; border-collapse: collapse; min-width: 850px; } .pc-table th { background: #f8fafc; color: #64748b; font-size: 10px; text-transform: uppercase; letter-spacing: .6px; font-weight: 800; padding: 12px 15px; text-align: left; white-space: nowrap; border-bottom: 1px solid var(--pc-border); } .pc-table td { padding: 14px 15px; border-bottom: 1px solid #edf0f4; vertical-align: middle; font-size: 12px; } .pc-table tbody tr { transition: .15s ease; } .pc-table tbody tr:hover { background: #fbfdff; } .pc-check { width: 16px; height: 16px; accent-color: var(--pc-primary); } .pc-category-info { display: flex; align-items: center; gap: 11px; min-width: 220px; } .pc-category-icon { width: 40px; height: 40px; flex: 0 0 40px; border-radius: 11px; display: flex; align-items: center; justify-content: center; background: linear-gradient( 135deg, #eff6ff, #dbeafe ); color: var(--pc-primary); font-size: 15px; } .pc-category-name { font-weight: 800; color: #172033; } .pc-category-slug { margin-top: 3px; color: #94a3b8; font-size: 10px; } .pc-parent { color: #64748b; font-size: 11px; } .pc-badge { display: inline-flex; align-items: center; gap: 5px; padding: 5px 8px; border-radius: 999px; font-size: 10px; line-height: 1; font-weight: 800; white-space: nowrap; } .pc-badge::before { content: ""; width: 5px; height: 5px; border-radius: 50%; background: currentColor; } .pc-badge-active { color: #047857; background: #ecfdf5; } .pc-badge-inactive { color: #b91c1c; background: #fef2f2; } .pc-type-badge { display: inline-flex; padding: 5px 8px; border-radius: 7px; background: #f1f5f9; color: #475569; font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .35px; } .pc-actions { display: flex; align-items: center; gap: 6px; } /* Bulk */ .pc-bulk { display: none; padding: 11px 15px; background: #eff6ff; border-bottom: 1px solid #dbeafe; align-items: center; justify-content: space-between; gap: 10px; } .pc-bulk.show { display: flex; } .pc-bulk-left { font-size: 12px; font-weight: 700; color: #1e40af; } .pc-bulk-right { display: flex; align-items: center; gap: 7px; } /* Empty */ .pc-empty { text-align: center; padding: 60px 20px; } .pc-empty-icon { width: 55px; height: 55px; margin: 0 auto 13px; display: flex; align-items: center; justify-content: center; border-radius: 15px; background: #f1f5f9; color: #94a3b8; font-size: 22px; } .pc-empty h3 { margin: 0; font-size: 15px; } .pc-empty p { margin: 6px 0 0; color: #94a3b8; font-size: 12px; } /* Pagination */ .pc-pagination { padding: 15px 17px; display: flex; justify-content: space-between; align-items: center; gap: 15px; border-top: 1px solid var(--pc-border); } .pc-pagination-info { color: #64748b; font-size: 11px; } .pc-pagination-links { display: flex; align-items: center; gap: 5px; } .pc-page-link { min-width: 31px; height: 31px; padding: 0 8px; display: inline-flex; align-items: center; justify-content: center; border-radius: 8px; color: #64748b; background: #f8fafc; border: 1px solid #e2e8f0; text-decoration: none; font-size: 11px; font-weight: 700; } .pc-page-link:hover { background: #eff6ff; color: var(--pc-primary); border-color: #bfdbfe; } .pc-page-link.active { background: var(--pc-primary); border-color: var(--pc-primary); color: #fff; } /* Responsive */ @media (max-width: 1200px) { .pc-content-grid { grid-template-columns: 1fr; } .pc-stat-grid { grid-template-columns: repeat(2, 1fr); } } @media (max-width: 850px) { .pc-page-head { flex-direction: column; } .pc-filter-grid { grid-template-columns: 1fr 1fr; } } @media (max-width: 600px) { .pc-category-page { padding: 15px; } .pc-stat-grid { grid-template-columns: 1fr 1fr; gap: 10px; } .pc-stat-card { padding: 14px; } .pc-stat-value { font-size: 22px; } .pc-form-row { grid-template-columns: 1fr; } .pc-filter-grid { grid-template-columns: 1fr; } .pc-pagination { flex-direction: column; align-items: flex-start; } } </style> <div class="pc-category-page"> <!-- ===================================================== PAGE HEADER ===================================================== --> <div class="pc-page-head"> <div> <h1 class="pc-page-title">Categories</h1> <p class="pc-page-subtitle"> Manage product, industry, service, blog and other website categories. </p> </div> <a href="categories.php" class="pc-primary-btn" > <span>+</span> Add Category </a> </div> <!-- ===================================================== ALERT ===================================================== --> <?php if ($message !== ''): ?> <div class="pc-alert <?= $message_type === 'success' ? 'pc-alert-success' : 'pc-alert-error' ?>"> <?php if ($message_type === 'success'): ?> <span>✓</span> <?php else: ?> <span>!</span> <?php endif; ?> <span><?= e($message) ?></span> </div> <?php endif; ?> <!-- ===================================================== STATS ===================================================== --> <div class="pc-stat-grid"> <div class="pc-stat-card"> <div class="pc-stat-top"> <div class="pc-stat-label"> Total Categories </div> <div class="pc-stat-icon"> ☷ </div> </div> <div class="pc-stat-value"> <?= number_format($stats['total']) ?> </div> </div> <div class="pc-stat-card"> <div class="pc-stat-top"> <div class="pc-stat-label"> Active </div> <div class="pc-stat-icon"> ✓ </div> </div> <div class="pc-stat-value"> <?= number_format($stats['active']) ?> </div> </div> <div class="pc-stat-card"> <div class="pc-stat-top"> <div class="pc-stat-label"> Inactive </div> <div class="pc-stat-icon"> ○ </div> </div> <div class="pc-stat-value"> <?= number_format($stats['inactive']) ?> </div> </div> <div class="pc-stat-card"> <div class="pc-stat-top"> <div class="pc-stat-label"> Parent Categories </div> <div class="pc-stat-icon"> ⌂ </div> </div> <div class="pc-stat-value"> <?= number_format($stats['parents']) ?> </div> </div> </div> <!-- ===================================================== MAIN CONTENT ===================================================== --> <div class="pc-content-grid"> <!-- ================================================= FORM ================================================= --> <div class="pc-card"> <div class="pc-card-head"> <div> <h2 class="pc-card-title"> <?= $editingCategory ? 'Edit Category' : 'Create Category' ?> </h2> <p class="pc-card-desc"> <?= $editingCategory ? 'Update category information.' : 'Add a new category to your website.' ?> </p> </div> </div> <div class="pc-card-body"> <form method="post" action="" autocomplete="off" > <?= csrf_field() ?> <input type="hidden" name="action" value="save" > <input type="hidden" name="id" value="<?= $editingCategory ? (int)$editingCategory['id'] : 0 ?>" > <!-- Category Type --> <div class="pc-form-group"> <label class="pc-form-label"> Category Type <span class="pc-required">*</span> </label> <select name="category_type" class="pc-select" required > <option value=""> Select category type </option> <?php foreach ($categoryTypes as $categoryTypeOption): ?> <option value="<?= e($categoryTypeOption) ?>" <?= ( ($editingCategory['category_type'] ?? '') === $categoryTypeOption ) ? 'selected' : '' ?> > <?= e(ucwords(str_replace('_', ' ', $categoryTypeOption))) ?> </option> <?php endforeach; ?> </select> </div> <!-- Parent --> <div class="pc-form-group"> <label class="pc-form-label"> Parent Category </label> <select name="parent_id" class="pc-select" > <option value="0"> — No Parent / Top Level — </option> <?php foreach ($parentOptions as $parentOption): ?> <option value="<?= (int)$parentOption['id'] ?>" <?= ( (int)($editingCategory['parent_id'] ?? 0) === (int)$parentOption['id'] ) ? 'selected' : '' ?> > <?= str_repeat('— ', (int)$parentOption['_level']) ?> <?= e($parentOption['name']) ?> <?= !$parentOption['status'] ? ' (Inactive)' : '' ?> </option> <?php endforeach; ?> </select> <div class="pc-input-help"> Select a parent to create a nested category. </div> </div> <!-- Name --> <div class="pc-form-group"> <label class="pc-form-label"> Category Name <span class="pc-required">*</span> </label> <input type="text" name="name" id="categoryName" class="pc-input" maxlength="255" required value="<?= e($editingCategory['name'] ?? '') ?>" placeholder="Enter category name" > </div> <!-- Slug --> <div class="pc-form-group"> <label class="pc-form-label"> Slug </label> <input type="text" name="slug" id="categorySlug" class="pc-input" maxlength="255" value="<?= e($editingCategory['slug'] ?? '') ?>" placeholder="category-slug" > <div class="pc-input-help"> Leave blank to generate automatically from category name. </div> </div> <!-- Short Description --> <div class="pc-form-group"> <label class="pc-form-label"> Short Description </label> <textarea name="short_description" class="pc-textarea" style="min-height:80px" maxlength="65535" placeholder="Short category description..." ><?= e($editingCategory['short_description'] ?? '') ?></textarea> </div> <!-- Description --> <div class="pc-form-group"> <label class="pc-form-label"> Description </label> <textarea name="description" class="pc-textarea" style="min-height:130px" placeholder="Full category description..." ><?= e($editingCategory['description'] ?? '') ?></textarea> </div> <!-- Image / Banner --> <div class="pc-form-row"> <div class="pc-form-group"> <label class="pc-form-label"> Image ID </label> <input type="number" min="1" name="image_id" class="pc-input" value="<?= e($editingCategory['image_id'] ?? '') ?>" placeholder="Media ID" > <div class="pc-input-help"> Existing media record ID. </div> </div> <div class="pc-form-group"> <label class="pc-form-label"> Banner ID </label> <input type="number" min="1" name="banner_id" class="pc-input" value="<?= e($editingCategory['banner_id'] ?? '') ?>" placeholder="Media ID" > <div class="pc-input-help"> Existing banner media ID. </div> </div> </div> <!-- Sort --> <div class="pc-form-row"> <div class="pc-form-group"> <label class="pc-form-label"> Sort Order </label> <input type="number" name="sort_order" class="pc-input" value="<?= e($editingCategory['sort_order'] ?? 0) ?>" min="0" step="1" > </div> <div class="pc-form-group"> <label class="pc-form-label"> Status </label> <label class="pc-checkbox-row"> <input type="checkbox" name="status" value="1" <?= ( !isset($editingCategory['status']) || (int)$editingCategory['status'] === 1 ) ? 'checked' : '' ?> > <span class="pc-checkbox-label"> Category is active </span> </label> </div> </div> <!-- Actions --> <div class="pc-form-actions"> <button type="submit" class="pc-btn pc-btn-primary" > <?= $editingCategory ? '✓ Update Category' : '+ Create Category' ?> </button> <?php if ($editingCategory): ?> <a href="categories.php" class="pc-btn pc-btn-light" > Cancel </a> <?php endif; ?> </div> </form> </div> </div> <!-- ================================================= LIST ================================================= --> <div class="pc-card"> <div class="pc-card-head"> <div> <h2 class="pc-card-title"> All Categories </h2> <p class="pc-card-desc"> <?= number_format($totalRows) ?> matching categories </p> </div> </div> <!-- Filters --> <form method="get" class="pc-filter" > <div class="pc-filter-grid"> <div class="pc-search-wrap"> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" > <circle cx="11" cy="11" r="7" ></circle> <path d="m20 20-3.5-3.5"></path> </svg> <input type="text" name="search" class="pc-input" placeholder="Search categories..." value="<?= e($search) ?>" > </div> <select name="type" class="pc-select" > <option value=""> All Types </option> <?php foreach ($categoryTypes as $filterType): ?> <option value="<?= e($filterType) ?>" <?= $type === $filterType ? 'selected' : '' ?> > <?= e(ucwords(str_replace('_', ' ', $filterType))) ?> </option> <?php endforeach; ?> </select> <select name="status" class="pc-select" > <option value=""> All Status </option> <option value="1" <?= $status === '1' ? 'selected' : '' ?> > Active </option> <option value="0" <?= $status === '0' ? 'selected' : '' ?> > Inactive </option> </select> <button type="submit" class="pc-btn pc-btn-primary" > Filter </button> </div> </form> <!-- Bulk --> <form method="post" id="bulkForm" > <?= csrf_field() ?> <input type="hidden" name="action" value="bulk_status" > <input type="hidden" name="bulk_status" id="bulkStatus" value="" > <div class="pc-bulk" id="bulkBar" > <div class="pc-bulk-left"> <span id="selectedCount">0</span> selected </div> <div class="pc-bulk-right"> <button type="button" class="pc-btn pc-btn-success pc-btn-sm" onclick="submitBulkStatus(1)" > Activate </button> <button type="button" class="pc-btn pc-btn-danger pc-btn-sm" onclick="submitBulkStatus(0)" > Deactivate </button> </div> </div> <!-- Table --> <?php if (!empty($categories)): ?> <div class="pc-table-wrap"> <table class="pc-table"> <thead> <tr> <th style="width:35px"> <input type="checkbox" class="pc-check" id="selectAll" > </th> <th> Category </th> <th> Type </th> <th> Parent </th> <th> Order </th> <th> Status </th> <th> Actions </th> </tr> </thead> <tbody> <?php foreach ($categories as $category): ?> <tr> <td> <input type="checkbox" class="pc-check category-check" name="selected_ids[]" value="<?= (int)$category['id'] ?>" > </td> <td> <div class="pc-category-info"> <div class="pc-category-icon"> ▦ </div> <div> <div class="pc-category-name"> <?= e($category['name']) ?> </div> <div class="pc-category-slug"> /<?= e($category['slug']) ?> </div> </div> </div> </td> <td> <span class="pc-type-badge"> <?= e( strtoupper( str_replace( '_', ' ', $category['category_type'] ) ) ) ?> </span> </td> <td> <?php if (!empty($category['parent_name'])): ?> <span class="pc-parent"> ↳ <?= e($category['parent_name']) ?> </span> <?php else: ?> <span class="pc-parent" style="color:#94a3b8" > Top Level </span> <?php endif; ?> </td> <td> <strong> <?= (int)$category['sort_order'] ?> </strong> </td> <td> <?php if ((int)$category['status'] === 1): ?> <span class="pc-badge pc-badge-active"> Active </span> <?php else: ?> <span class="pc-badge pc-badge-inactive"> Inactive </span> <?php endif; ?> </td> <td> <div class="pc-actions"> <a href="categories.php?edit=<?= (int)$category['id'] ?>" class="pc-btn pc-btn-light pc-btn-sm" title="Edit" > Edit </a> <button type="button" class="pc-btn pc-btn-light pc-btn-sm" onclick="toggleCategoryStatus(<?= (int)$category['id'] ?>)" > <?= (int)$category['status'] === 1 ? 'Disable' : 'Enable' ?> </button> <button type="button" class="pc-btn pc-btn-danger pc-btn-sm" onclick="deleteCategory(<?= (int)$category['id'] ?>)" > Delete </button> </div> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> <?php else: ?> <div class="pc-empty"> <div class="pc-empty-icon"> ▦ </div> <h3> No categories found </h3> <p> Create your first category or change the filters. </p> </div> <?php endif; ?> </form> <!-- Pagination --> <?php if ($totalRows > 0): ?> <div class="pc-pagination"> <div class="pc-pagination-info"> Showing <strong> <?= number_format($offset + 1) ?> </strong> - <strong> <?= number_format( min($offset + $perPage, $totalRows) ) ?> </strong> of <strong> <?= number_format($totalRows) ?> </strong> </div> <?php if ($totalPages > 1): ?> <div class="pc-pagination-links"> <?php if ($page > 1): ?> <a href="<?= e(categoryPageUrl($page - 1)) ?>" class="pc-page-link" > ‹ </a> <?php endif; ?> <?php $startPage = max(1, $page - 2); $endPage = min($totalPages, $page + 2); for ($paginationPage = $startPage; $paginationPage <= $endPage; $paginationPage++): ?> <a href="<?= e(categoryPageUrl($paginationPage)) ?>" class="pc-page-link <?= $paginationPage === $page ? 'active' : '' ?>" > <?= $paginationPage ?> </a> <?php endfor; ?> <?php if ($page < $totalPages): ?> <a href="<?= e(categoryPageUrl($page + 1)) ?>" class="pc-page-link" > › </a> <?php endif; ?> </div> <?php endif; ?> </div> <?php endif; ?> </div> </div> </div> <!-- ========================================================= HIDDEN ACTION FORMS ========================================================= --> <form method="post" id="statusForm" style="display:none" > <?= csrf_field() ?> <input type="hidden" name="action" value="toggle_status" > <input type="hidden" name="id" id="statusCategoryId" value="" > </form> <form method="post" id="deleteForm" style="display:none" > <?= csrf_field() ?> <input type="hidden" name="action" value="delete" > <input type="hidden" name="id" id="deleteCategoryId" value="" > </form> <script> /* |-------------------------------------------------------------------------- | Category Name → Slug |-------------------------------------------------------------------------- */ (function () { const nameInput = document.getElementById('categoryName'); const slugInput = document.getElementById('categorySlug'); if (!nameInput || !slugInput) { return; } let slugManuallyChanged = <?= $editingCategory ? 'true' : 'false' ?>; slugInput.addEventListener('input', function () { slugManuallyChanged = this.value.trim() !== ''; }); nameInput.addEventListener('input', function () { if (slugManuallyChanged) { return; } const value = this.value .toLowerCase() .trim() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); slugInput.value = value; }); })(); /* |-------------------------------------------------------------------------- | Select All |-------------------------------------------------------------------------- */ (function () { const selectAll = document.getElementById('selectAll'); const checks = document.querySelectorAll('.category-check'); const bulkBar = document.getElementById('bulkBar'); const selectedCount = document.getElementById('selectedCount'); function updateBulkBar() { const selected = document.querySelectorAll( '.category-check:checked' ).length; if (selected > 0) { bulkBar.classList.add('show'); } else { bulkBar.classList.remove('show'); } selectedCount.textContent = selected; if (selectAll) { selectAll.checked = checks.length > 0 && selected === checks.length; } } if (selectAll) { selectAll.addEventListener('change', function () { checks.forEach(function (checkbox) { checkbox.checked = selectAll.checked; }); updateBulkBar(); }); } checks.forEach(function (checkbox) { checkbox.addEventListener( 'change', updateBulkBar ); }); updateBulkBar(); })(); /* |-------------------------------------------------------------------------- | Bulk Status |-------------------------------------------------------------------------- */ function submitBulkStatus(status) { const selected = document.querySelectorAll( '.category-check:checked' ); if (!selected.length) { alert('Please select at least one category.'); return; } const actionText = status === 1 ? 'activate' : 'deactivate'; if (!confirm( 'Are you sure you want to ' + actionText + ' the selected categories?' )) { return; } document.getElementById('bulkStatus').value = status; document.getElementById('bulkForm').submit(); } /* |-------------------------------------------------------------------------- | Toggle Status |-------------------------------------------------------------------------- */ function toggleCategoryStatus(id) { if (!id) { return; } if (!confirm('Change category status?')) { return; } document.getElementById( 'statusCategoryId' ).value = id; document.getElementById( 'statusForm' ).submit(); } /* |-------------------------------------------------------------------------- | Delete |-------------------------------------------------------------------------- */ function deleteCategory(id) { if (!id) { return; } const confirmed = confirm( 'Are you sure you want to delete this category?\n\n' + 'This action cannot be undone.' ); if (!confirmed) { return; } document.getElementById( 'deleteCategoryId' ).value = id; document.getElementById( 'deleteForm' ).submit(); } </script> <?php /* |-------------------------------------------------------------------------- | Footer |-------------------------------------------------------------------------- */ $footerCandidates = [ __DIR__ . '/includes/footer.php', __DIR__ . '/footer.php', ]; $footerLoaded = false; foreach ($footerCandidates as $footerFile) { if (file_exists($footerFile)) { require_once $footerFile; $footerLoaded = true; break; } } if (!$footerLoaded) { ?> </body> </html> <?php } ?>
Save
Cancel