📁 File Manager
Editing:
/home/wvl7mof7402e/www/chem/admin/blog_posts.php
<?php /** * Pure Chemical Admin * Blog Posts Management * * Existing tables: * - blog_posts * - blog_categories * - users (blog post author references users.id) * - admins (authentication may still use this table) * - media * - blog_post_media (if present) * - blog_post_tags (if present) * * No new tables are created. */ /* ========================================================= SESSION ========================================================= */ if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); } /* ========================================================= DATABASE ========================================================= */ require_once __DIR__ . '/includes/db.php'; /* ========================================================= AUTH ========================================================= */ if (file_exists(__DIR__ . '/includes/auth.php')) { require_once __DIR__ . '/includes/auth.php'; } if (function_exists('requireAdmin')) { requireAdmin(); } /* ========================================================= FUNCTIONS ========================================================= */ if (file_exists(__DIR__ . '/includes/functions.php')) { require_once __DIR__ . '/includes/functions.php'; } if (file_exists(__DIR__ . '/includes/csrf.php')) { require_once __DIR__ . '/includes/csrf.php'; } /* ========================================================= SAFE HTML ========================================================= */ if (!function_exists('e')) { function e($value) { return htmlspecialchars( (string)$value, ENT_QUOTES, 'UTF-8' ); } } /* ========================================================= CSRF FALLBACK ========================================================= */ if (!function_exists('blog_posts_csrf_field')) { function blog_posts_csrf_field() { if (empty($_SESSION['blog_posts_csrf'])) { $_SESSION['blog_posts_csrf'] = bin2hex(random_bytes(32)); } return '<input type="hidden" name="csrf_token" value="' . e($_SESSION['blog_posts_csrf']) . '">'; } } if (!function_exists('blog_posts_verify_csrf')) { function blog_posts_verify_csrf() { $token = $_POST['csrf_token'] ?? ''; if ( empty($_SESSION['blog_posts_csrf']) || empty($token) ) { return false; } return hash_equals( $_SESSION['blog_posts_csrf'], $token ); } } /* ========================================================= SLUGIFY ========================================================= */ if (!function_exists('blog_slugify')) { function blog_slugify($text) { $text = trim($text); if ($text === '') { return ''; } $text = mb_strtolower( $text, 'UTF-8' ); $text = preg_replace( '/[^\pL\pN]+/u', '-', $text ); $text = trim( $text, '-' ); return $text; } } /* ========================================================= TABLE COLUMN CHECK ========================================================= */ if (!function_exists('blog_posts_has_column')) { function blog_posts_has_column( PDO $pdo, $table, $column ) { try { $stmt = $pdo->query( "SHOW COLUMNS FROM `" . str_replace('`', '', $table) . "` LIKE '" . str_replace("'", "''", $column) . "'" ); return (bool)$stmt->fetch(); } catch (Throwable $e) { return false; } } } /* ========================================================= FLASH ========================================================= */ $flash = $_SESSION['blog_posts_flash'] ?? null; unset( $_SESSION['blog_posts_flash'] ); /* ========================================================= ENUM STATUS ========================================================= */ $statusOptions = [ 'draft', 'published', 'inactive' ]; try { $statusStmt = $pdo->query( "SHOW COLUMNS FROM blog_posts LIKE 'status'" ); $statusColumn = $statusStmt->fetch(); if ( $statusColumn && !empty($statusColumn['Type']) ) { if ( preg_match( "/^enum\((.*)\)$/i", $statusColumn['Type'], $matches ) ) { $enumValues = str_getcsv( $matches[1], ',', "'" ); $parsedStatuses = []; foreach ($enumValues as $value) { $value = str_replace( "''", "'", $value ); if ($value !== '') { $parsedStatuses[] = $value; } } if ($parsedStatuses) { $statusOptions = $parsedStatuses; } } } } catch (Throwable $e) { /* Use known schema defaults */ } /* ========================================================= EDIT ID ========================================================= */ $editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0; /* ========================================================= FORM DEFAULTS ========================================================= */ $form = [ 'id' => 0, 'category_id' => '', 'author_id' => '', 'title' => '', 'slug' => '', 'excerpt' => '', 'content' => '', 'featured_image_id' => '', 'video_url' => '', 'status' => 'draft', 'featured' => 0, 'published_at' => '', 'views' => 0 ]; $errors = []; /* ========================================================= LOAD EDIT RECORD ========================================================= */ if ($editId > 0) { try { $editStmt = $pdo->prepare(" SELECT id, category_id, author_id, title, slug, excerpt, content, featured_image_id, video_url, status, featured, published_at, views FROM blog_posts WHERE id = ? LIMIT 1 "); $editStmt->execute([ $editId ]); $editRecord = $editStmt->fetch(); if ($editRecord) { $form = [ 'id' => (int)$editRecord['id'], 'category_id' => $editRecord['category_id'] !== null ? (string)$editRecord['category_id'] : '', 'author_id' => $editRecord['author_id'] !== null ? (string)$editRecord['author_id'] : '', 'title' => (string)$editRecord['title'], 'slug' => (string)$editRecord['slug'], 'excerpt' => (string)($editRecord['excerpt'] ?? ''), 'content' => (string)($editRecord['content'] ?? ''), 'featured_image_id' => $editRecord['featured_image_id'] !== null ? (string)$editRecord['featured_image_id'] : '', 'video_url' => (string)($editRecord['video_url'] ?? ''), 'status' => (string)$editRecord['status'], 'featured' => (int)$editRecord['featured'], 'published_at' => $editRecord['published_at'] ? date( 'Y-m-d\TH:i', strtotime( $editRecord['published_at'] ) ) : '', 'views' => (int)$editRecord['views'] ]; } else { $editId = 0; $flash = [ 'type' => 'danger', 'message' => 'Blog post not found.' ]; } } catch (Throwable $e) { $editId = 0; $flash = [ 'type' => 'danger', 'message' => 'Unable to load blog post.' ]; } } /* ========================================================= POST ACTIONS ========================================================= */ if ($_SERVER['REQUEST_METHOD'] === 'POST') { $action = $_POST['action'] ?? ''; /* ===================================================== SAVE ===================================================== */ if ($action === 'save') { /* ------------------------------------------------- CSRF ------------------------------------------------- */ if (!blog_posts_verify_csrf()) { $errors[] = 'Security verification failed. Please refresh the page and try again.'; } /* ------------------------------------------------- FORM VALUES ------------------------------------------------- */ $form['id'] = isset($_POST['id']) ? (int)$_POST['id'] : 0; $form['category_id'] = isset($_POST['category_id']) && $_POST['category_id'] !== '' ? (string)(int)$_POST['category_id'] : ''; $form['author_id'] = isset($_POST['author_id']) && $_POST['author_id'] !== '' ? (string)(int)$_POST['author_id'] : ''; $form['title'] = trim( $_POST['title'] ?? '' ); $form['slug'] = trim( $_POST['slug'] ?? '' ); $form['excerpt'] = trim( $_POST['excerpt'] ?? '' ); $form['content'] = $_POST['content'] ?? ''; $form['featured_image_id'] = isset($_POST['featured_image_id']) && $_POST['featured_image_id'] !== '' ? (string)(int)$_POST['featured_image_id'] : ''; $form['video_url'] = trim( $_POST['video_url'] ?? '' ); $form['status'] = trim( $_POST['status'] ?? 'draft' ); $form['featured'] = !empty($_POST['featured']) ? 1 : 0; $form['published_at'] = trim( $_POST['published_at'] ?? '' ); /* ================================================= BASIC VALIDATION ================================================== */ if ($form['title'] === '') { $errors[] = 'Blog post title is required.'; } elseif ( mb_strlen( $form['title'], 'UTF-8' ) > 500 ) { $errors[] = 'Blog post title cannot exceed 500 characters.'; } /* ------------------------------------------------- SLUG ------------------------------------------------- */ if ($form['slug'] === '') { $form['slug'] = blog_slugify( $form['title'] ); } else { $form['slug'] = blog_slugify( $form['slug'] ); } if ($form['slug'] === '') { $errors[] = 'A valid slug could not be generated.'; } if ( mb_strlen( $form['slug'], 'UTF-8' ) > 500 ) { $errors[] = 'Slug cannot exceed 500 characters.'; } /* ------------------------------------------------- STATUS ------------------------------------------------- */ if ( !in_array( $form['status'], $statusOptions, true ) ) { $errors[] = 'Invalid blog post status selected.'; } /* ================================================= CATEGORY VALIDATION ================================================== */ $categoryId = $form['category_id'] !== '' ? (int)$form['category_id'] : 0; if ($categoryId > 0) { try { $categoryCheck = $pdo->prepare(" SELECT id FROM blog_categories WHERE id = ? LIMIT 1 "); $categoryCheck->execute([ $categoryId ]); if (!$categoryCheck->fetch()) { $errors[] = 'Selected blog category does not exist.'; } } catch (Throwable $e) { $errors[] = 'Unable to validate selected category.'; } } /* ================================================= AUTHOR VALIDATION ================================================== */ $authorId = $form['author_id'] !== '' ? (int)$form['author_id'] : 0; if ($authorId > 0) { try { $authorCheck = $pdo->prepare(" SELECT id FROM users WHERE id = ? LIMIT 1 "); $authorCheck->execute([ $authorId ]); if (!$authorCheck->fetch()) { $errors[] = 'Selected author does not exist in the users table. Please choose a valid user or leave Author blank.'; } } catch (Throwable $e) { $errors[] = 'Unable to validate selected author.'; } } /* ================================================= OPTIONAL FEATURED IMAGE UPLOAD -> media TABLE ================================================== */ if ( isset($_FILES['featured_image_file']) && is_array($_FILES['featured_image_file']) && ($_FILES['featured_image_file']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE ) { $file = $_FILES['featured_image_file']; if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) { $errors[] = 'Image upload failed. Please try again.'; } elseif (($file['size'] ?? 0) > 8 * 1024 * 1024) { $errors[] = 'Image size must be 8 MB or less.'; } else { $tmp = $file['tmp_name'] ?? ''; $imageInfo = $tmp ? @getimagesize($tmp) : false; $mime = $imageInfo['mime'] ?? ''; $allowed = [ 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp' ]; if (!$imageInfo || !isset($allowed[$mime])) { $errors[] = 'Please upload a valid JPG, PNG, GIF, or WEBP image.'; } else { $destination = null; try { /* * This page is commonly inside /admin. Save uploads in the * project-root /uploads folder so stored paths resolve from * the public site, rather than accidentally creating * /admin/uploads. */ $parentRoot = dirname(__DIR__); // Support both /blog_posts.php and /admin/blog_posts.php layouts. $projectRoot = (is_file($parentRoot . '/index.php') || is_dir($parentRoot . '/assets')) ? $parentRoot : __DIR__; $uploadDir = $projectRoot . '/uploads/blog_posts'; if (!is_dir($uploadDir) && !mkdir($uploadDir, 0775, true) && !is_dir($uploadDir)) { throw new RuntimeException('Upload directory could not be created: ' . $uploadDir); } if (!is_writable($uploadDir)) { throw new RuntimeException('Upload directory is not writable: ' . $uploadDir); } $originalName = basename((string)($file['name'] ?? 'image')); $originalName = mb_substr($originalName, 0, 255, 'UTF-8'); $fileName = bin2hex(random_bytes(16)) . '.' . $allowed[$mime]; $relativePath = 'uploads/blog_posts/' . $fileName; $destination = $uploadDir . '/' . $fileName; if (!move_uploaded_file($tmp, $destination)) { throw new RuntimeException('move_uploaded_file failed. Check PHP upload_tmp_dir and folder permissions.'); } $size = (int)filesize($destination); $width = (int)$imageInfo[0]; $height = (int)$imageInfo[1]; // media.uploaded_by has a FOREIGN KEY to users.id (not admins.id). // Only save a session ID after verifying it exists in users; otherwise store NULL. $uploadedBy = (int)( $_SESSION['USER_ID'] ?? $_SESSION['user_id'] ?? $_SESSION['userId'] ?? $_SESSION['user']['id'] ?? 0 ); if ($uploadedBy > 0) { try { $userCheck = $pdo->prepare('SELECT id FROM users WHERE id = ? LIMIT 1'); $userCheck->execute([$uploadedBy]); if (!$userCheck->fetchColumn()) { $uploadedBy = 0; } } catch (Throwable $ignoreUserLookup) { // Uploads should still work if the session/table naming differs. $uploadedBy = 0; } } $mediaInsert = $pdo->prepare(" INSERT INTO media (folder_id, original_name, file_name, file_path, mime_type, file_type, extension, file_size, width, height, uploaded_by, status) VALUES (NULL, :original_name, :file_name, :file_path, :mime_type, 'image', :extension, :file_size, :width, :height, :uploaded_by, 1) "); $mediaInsert->bindValue(':original_name', $originalName, PDO::PARAM_STR); $mediaInsert->bindValue(':file_name', $fileName, PDO::PARAM_STR); $mediaInsert->bindValue(':file_path', $relativePath, PDO::PARAM_STR); $mediaInsert->bindValue(':mime_type', $mime, PDO::PARAM_STR); $mediaInsert->bindValue(':extension', $allowed[$mime], PDO::PARAM_STR); $mediaInsert->bindValue(':file_size', $size, PDO::PARAM_INT); $mediaInsert->bindValue(':width', $width, PDO::PARAM_INT); $mediaInsert->bindValue(':height', $height, PDO::PARAM_INT); if ($uploadedBy > 0) { $mediaInsert->bindValue(':uploaded_by', $uploadedBy, PDO::PARAM_INT); } else { $mediaInsert->bindValue(':uploaded_by', null, PDO::PARAM_NULL); } $mediaInsert->execute(); $form['featured_image_id'] = (string)(int)$pdo->lastInsertId(); } catch (Throwable $uploadError) { if ($destination && is_file($destination)) { @unlink($destination); } error_log('Blog featured image upload error: ' . $uploadError->getMessage()); // Show a useful diagnostic to an authenticated admin instead of masking the actual cause. $errors[] = 'Image save failed: ' . $uploadError->getMessage(); } } } } /* ================================================= FEATURED IMAGE VALIDATION ================================================== */ $featuredImageId = $form['featured_image_id'] !== '' ? (int)$form['featured_image_id'] : 0; if ($featuredImageId > 0) { try { $mediaCheck = $pdo->prepare(" SELECT id FROM media WHERE id = ? LIMIT 1 "); $mediaCheck->execute([ $featuredImageId ]); if (!$mediaCheck->fetch()) { $errors[] = 'Featured image Media ID does not exist.'; } } catch (Throwable $e) { $errors[] = 'Unable to validate featured image.'; } } /* ================================================= VIDEO URL ================================================== */ if ($form['video_url'] !== '') { if ( !filter_var( $form['video_url'], FILTER_VALIDATE_URL ) ) { $errors[] = 'Please enter a valid video URL.'; } else { $videoParts = parse_url( $form['video_url'] ); $videoScheme = strtolower( $videoParts['scheme'] ?? '' ); if ( !in_array( $videoScheme, [ 'http', 'https' ], true ) ) { $errors[] = 'Video URL must use HTTP or HTTPS.'; } } } /* ================================================= PUBLISHED DATE ================================================== */ $publishedAtSql = null; if ($form['published_at'] !== '') { $publishedTimestamp = strtotime( $form['published_at'] ); if ($publishedTimestamp === false) { $errors[] = 'Invalid published date/time.'; } else { $publishedAtSql = date( 'Y-m-d H:i:s', $publishedTimestamp ); } } /* * If status is published and no date was supplied, * automatically use current date/time. */ if ( $form['status'] === 'published' && $publishedAtSql === null ) { $publishedAtSql = date( 'Y-m-d H:i:s' ); } /* ================================================= SLUG DUPLICATE CHECK ================================================== */ if (!$errors) { try { if ($form['id'] > 0) { $slugCheck = $pdo->prepare(" SELECT id FROM blog_posts WHERE slug = ? AND id <> ? LIMIT 1 "); $slugCheck->execute([ $form['slug'], $form['id'] ]); } else { $slugCheck = $pdo->prepare(" SELECT id FROM blog_posts WHERE slug = ? LIMIT 1 "); $slugCheck->execute([ $form['slug'] ]); } if ($slugCheck->fetch()) { $errors[] = 'This slug is already used by another blog post.'; } } catch (Throwable $e) { $errors[] = 'Unable to check slug uniqueness.'; } } /* ================================================= INSERT / UPDATE ================================================== */ if (!$errors) { try { if ($form['id'] > 0) { /* ===================================== UPDATE ===================================== */ $update = $pdo->prepare(" UPDATE blog_posts SET category_id = :category_id, author_id = :author_id, title = :title, slug = :slug, excerpt = :excerpt, content = :content, featured_image_id = :featured_image_id, video_url = :video_url, status = :status, featured = :featured, published_at = :published_at WHERE id = :id LIMIT 1 "); if ($categoryId > 0) { $update->bindValue( ':category_id', $categoryId, PDO::PARAM_INT ); } else { $update->bindValue( ':category_id', null, PDO::PARAM_NULL ); } if ($authorId > 0) { $update->bindValue( ':author_id', $authorId, PDO::PARAM_INT ); } else { $update->bindValue( ':author_id', null, PDO::PARAM_NULL ); } $update->bindValue( ':title', $form['title'], PDO::PARAM_STR ); $update->bindValue( ':slug', $form['slug'], PDO::PARAM_STR ); if ($form['excerpt'] !== '') { $update->bindValue( ':excerpt', $form['excerpt'], PDO::PARAM_STR ); } else { $update->bindValue( ':excerpt', null, PDO::PARAM_NULL ); } if ($form['content'] !== '') { $update->bindValue( ':content', $form['content'], PDO::PARAM_STR ); } else { $update->bindValue( ':content', null, PDO::PARAM_NULL ); } if ($featuredImageId > 0) { $update->bindValue( ':featured_image_id', $featuredImageId, PDO::PARAM_INT ); } else { $update->bindValue( ':featured_image_id', null, PDO::PARAM_NULL ); } if ($form['video_url'] !== '') { $update->bindValue( ':video_url', $form['video_url'], PDO::PARAM_STR ); } else { $update->bindValue( ':video_url', null, PDO::PARAM_NULL ); } $update->bindValue( ':status', $form['status'], PDO::PARAM_STR ); $update->bindValue( ':featured', $form['featured'], PDO::PARAM_INT ); if ($publishedAtSql !== null) { $update->bindValue( ':published_at', $publishedAtSql, PDO::PARAM_STR ); } else { $update->bindValue( ':published_at', null, PDO::PARAM_NULL ); } $update->bindValue( ':id', $form['id'], PDO::PARAM_INT ); $update->execute(); $_SESSION['blog_posts_flash'] = [ 'type' => 'success', 'message' => 'Blog post updated successfully.' ]; header( 'Location: blog_posts.php?edit=' . $form['id'] ); exit; } else { /* ===================================== INSERT ===================================== */ $insert = $pdo->prepare(" INSERT INTO blog_posts ( category_id, author_id, title, slug, excerpt, content, featured_image_id, video_url, status, featured, published_at ) VALUES ( :category_id, :author_id, :title, :slug, :excerpt, :content, :featured_image_id, :video_url, :status, :featured, :published_at ) "); if ($categoryId > 0) { $insert->bindValue( ':category_id', $categoryId, PDO::PARAM_INT ); } else { $insert->bindValue( ':category_id', null, PDO::PARAM_NULL ); } if ($authorId > 0) { $insert->bindValue( ':author_id', $authorId, PDO::PARAM_INT ); } else { $insert->bindValue( ':author_id', null, PDO::PARAM_NULL ); } $insert->bindValue( ':title', $form['title'], PDO::PARAM_STR ); $insert->bindValue( ':slug', $form['slug'], PDO::PARAM_STR ); if ($form['excerpt'] !== '') { $insert->bindValue( ':excerpt', $form['excerpt'], PDO::PARAM_STR ); } else { $insert->bindValue( ':excerpt', null, PDO::PARAM_NULL ); } if ($form['content'] !== '') { $insert->bindValue( ':content', $form['content'], PDO::PARAM_STR ); } else { $insert->bindValue( ':content', null, PDO::PARAM_NULL ); } if ($featuredImageId > 0) { $insert->bindValue( ':featured_image_id', $featuredImageId, PDO::PARAM_INT ); } else { $insert->bindValue( ':featured_image_id', null, PDO::PARAM_NULL ); } if ($form['video_url'] !== '') { $insert->bindValue( ':video_url', $form['video_url'], PDO::PARAM_STR ); } else { $insert->bindValue( ':video_url', null, PDO::PARAM_NULL ); } $insert->bindValue( ':status', $form['status'], PDO::PARAM_STR ); $insert->bindValue( ':featured', $form['featured'], PDO::PARAM_INT ); if ($publishedAtSql !== null) { $insert->bindValue( ':published_at', $publishedAtSql, PDO::PARAM_STR ); } else { $insert->bindValue( ':published_at', null, PDO::PARAM_NULL ); } $insert->execute(); $newId = (int)$pdo->lastInsertId(); $_SESSION['blog_posts_flash'] = [ 'type' => 'success', 'message' => 'Blog post created successfully.' ]; header( 'Location: blog_posts.php?edit=' . $newId ); exit; } } catch (PDOException $e) { error_log( 'Blog Post Save Error: ' . $e->getMessage() ); $errors[] = 'Unable to save blog post. Please try again.'; } } } /* ===================================================== DELETE ===================================================== */ if ($action === 'delete') { if (!blog_posts_verify_csrf()) { $errors[] = 'Security verification failed. Please refresh the page and try again.'; } else { $deleteId = isset($_POST['id']) ? (int)$_POST['id'] : 0; if ($deleteId <= 0) { $errors[] = 'Invalid blog post ID.'; } else { try { $pdo->beginTransaction(); /* * Remove dependent rows only if those * tables contain blog_post_id. */ if ( blog_posts_has_column( $pdo, 'blog_post_media', 'blog_post_id' ) ) { $deleteMedia = $pdo->prepare(" DELETE FROM blog_post_media WHERE blog_post_id = ? "); $deleteMedia->execute([ $deleteId ]); } if ( blog_posts_has_column( $pdo, 'blog_post_tags', 'blog_post_id' ) ) { $deleteTags = $pdo->prepare(" DELETE FROM blog_post_tags WHERE blog_post_id = ? "); $deleteTags->execute([ $deleteId ]); } $delete = $pdo->prepare(" DELETE FROM blog_posts WHERE id = ? LIMIT 1 "); $delete->execute([ $deleteId ]); $pdo->commit(); $_SESSION['blog_posts_flash'] = [ 'type' => 'success', 'message' => 'Blog post deleted successfully.' ]; header( 'Location: blog_posts.php' ); exit; } catch (Throwable $e) { if ( $pdo->inTransaction() ) { $pdo->rollBack(); } error_log( 'Blog Post Delete Error: ' . $e->getMessage() ); $errors[] = 'Unable to delete blog post. Please try again.'; } } } } } /* ========================================================= LOAD ACTIVE IMAGE MEDIA ========================================================= */ $mediaItems = []; try { $mediaStmt = $pdo->query(" SELECT id, original_name, file_path FROM media WHERE status = 1 AND file_type = 'image' ORDER BY id DESC LIMIT 500 "); $mediaItems = $mediaStmt->fetchAll(PDO::FETCH_ASSOC); } catch (Throwable $e) { $mediaItems = []; } /* ========================================================= LOAD BLOG CATEGORIES ========================================================= */ $categories = []; try { $categoryStmt = $pdo->query(" SELECT id, name, slug FROM blog_categories ORDER BY name ASC "); $categories = $categoryStmt->fetchAll(); } catch (Throwable $e) { $categories = []; } /* ========================================================= LOAD AUTHORS FROM users (blog_posts.author_id REFERENCES users.id) ========================================================= */ $authors = []; $authorNameColumn = null; $authorEmailColumn = null; try { $userColumnsStmt = $pdo->query('SHOW COLUMNS FROM `users`'); $userColumnNames = array_column($userColumnsStmt->fetchAll(PDO::FETCH_ASSOC), 'Field'); foreach (['name', 'full_name', 'username', 'email'] as $candidate) { if (in_array($candidate, $userColumnNames, true)) { $authorNameColumn = $candidate; break; } } if (in_array('email', $userColumnNames, true)) { $authorEmailColumn = 'email'; } if ($authorNameColumn !== null) { $nameSql = '`' . $authorNameColumn . '`'; $emailSql = $authorEmailColumn !== null ? '`' . $authorEmailColumn . '`' : "''"; $authorsStmt = $pdo->query("SELECT id, {$nameSql} AS name, {$emailSql} AS email FROM users ORDER BY {$nameSql} ASC"); $authors = $authorsStmt->fetchAll(PDO::FETCH_ASSOC); } } catch (Throwable $e) { $authors = []; } // SQL expressions used by the posts list; column names are selected from a fixed whitelist above. $authorNameSelect = $authorNameColumn !== null ? 'a.`' . $authorNameColumn . '`' : 'NULL'; $authorEmailSelect = $authorEmailColumn !== null ? 'a.`' . $authorEmailColumn . '`' : 'NULL'; /* ========================================================= FILTERS ========================================================= */ $search = trim($_GET['q'] ?? ''); $filterCategory = isset($_GET['category']) ? (int)$_GET['category'] : 0; $filterStatus = trim($_GET['status'] ?? ''); $filterFeatured = isset($_GET['featured']) ? trim($_GET['featured']) : ''; $page = isset($_GET['page']) ? max( 1, (int)$_GET['page'] ) : 1; $perPage = 15; /* ========================================================= WHERE ========================================================= */ $where = []; $params = []; if ($search !== '') { $where[] = " ( bp.title LIKE :search1 OR bp.slug LIKE :search2 OR bp.excerpt LIKE :search3 ) "; $searchValue = '%' . $search . '%'; $params[':search1'] = $searchValue; $params[':search2'] = $searchValue; $params[':search3'] = $searchValue; } if ($filterCategory > 0) { $where[] = 'bp.category_id = :filter_category'; $params[':filter_category'] = $filterCategory; } if ( $filterStatus !== '' && in_array( $filterStatus, $statusOptions, true ) ) { $where[] = 'bp.status = :filter_status'; $params[':filter_status'] = $filterStatus; } if ( $filterFeatured === '1' || $filterFeatured === '0' ) { $where[] = 'bp.featured = :filter_featured'; $params[':filter_featured'] = (int)$filterFeatured; } $whereSql = $where ? 'WHERE ' . implode( ' AND ', $where ) : ''; /* ========================================================= TOTAL ========================================================= */ $totalPosts = 0; try { $countStmt = $pdo->prepare(" SELECT COUNT(*) FROM blog_posts bp $whereSql "); foreach ( $params as $key => $value ) { $countStmt->bindValue( $key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR ); } $countStmt->execute(); $totalPosts = (int)$countStmt->fetchColumn(); } catch (Throwable $e) { $totalPosts = 0; } /* ========================================================= PAGINATION ========================================================= */ $totalPages = max( 1, (int)ceil( $totalPosts / $perPage ) ); if ($page > $totalPages) { $page = $totalPages; } $offset = ($page - 1) * $perPage; /* ========================================================= LOAD POSTS ========================================================= */ $posts = []; try { $postStmt = $pdo->prepare(" SELECT bp.id, bp.category_id, bp.author_id, bp.title, bp.slug, bp.excerpt, bp.content, bp.featured_image_id, bp.video_url, bp.status, bp.featured, bp.published_at, bp.views, bp.created_at, bp.updated_at, bc.name AS category_name, {$authorNameSelect} AS author_name, {$authorEmailSelect} AS author_email FROM blog_posts bp LEFT JOIN blog_categories bc ON bc.id = bp.category_id LEFT JOIN users a ON a.id = bp.author_id $whereSql ORDER BY CASE WHEN bp.status = 'published' THEN 0 ELSE 1 END ASC, bp.featured DESC, COALESCE( bp.published_at, bp.created_at ) DESC, bp.id DESC LIMIT :limit OFFSET :offset "); foreach ( $params as $key => $value ) { $postStmt->bindValue( $key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR ); } $postStmt->bindValue( ':limit', $perPage, PDO::PARAM_INT ); $postStmt->bindValue( ':offset', $offset, PDO::PARAM_INT ); $postStmt->execute(); $posts = $postStmt->fetchAll(); } catch (Throwable $e) { $posts = []; } /* ========================================================= STATS ========================================================= */ $stats = [ 'total' => 0, 'published' => 0, 'draft' => 0, 'featured' => 0 ]; try { $statsStmt = $pdo->query(" SELECT COUNT(*) AS total, SUM( status = 'published' ) AS published, SUM( status = 'draft' ) AS draft, SUM( featured = 1 ) AS featured FROM blog_posts "); $statsRow = $statsStmt->fetch(); if ($statsRow) { $stats['total'] = (int)$statsRow['total']; $stats['published'] = (int)$statsRow['published']; $stats['draft'] = (int)$statsRow['draft']; $stats['featured'] = (int)$statsRow['featured']; } } catch (Throwable $e) { /* Defaults */ } /* ========================================================= ADMIN INFO ========================================================= */ $adminName = $_SESSION['ADMIN_NAME'] ?? $_SESSION['admin_name'] ?? $_SESSION['name'] ?? 'Administrator'; $adminRole = $_SESSION['ADMIN_ROLE'] ?? $_SESSION['admin_role'] ?? 'Administrator'; /* ========================================================= PAGINATION URL ========================================================= */ function blog_posts_page_url( $page, $search, $category, $status, $featured ) { $query = [ 'page' => $page ]; if ($search !== '') { $query['q'] = $search; } if ($category > 0) { $query['category'] = $category; } if ($status !== '') { $query['status'] = $status; } if ($featured !== '') { $query['featured'] = $featured; } return 'blog_posts.php?' . http_build_query($query); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" > <title> Blog Posts | Pure Chemical Admin </title> <meta name="robots" content="noindex,nofollow" > <!-- Google Font --> <link rel="preconnect" href="https://fonts.googleapis.com" > <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin > <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet" > <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" > <style> :root { --primary: #0f766e; --primary-dark: #115e59; --primary-light: #14b8a6; --bg: #f5f7fb; --card: #ffffff; --text: #172033; --muted: #6b7280; --border: #e5e7eb; --success: #15803d; --danger: #dc2626; --warning: #d97706; --purple: #7c3aed; --blue: #2563eb; --shadow: 0 12px 38px rgba(15,23,42,.065); --radius: 18px; } * { box-sizing: border-box; } html { scroll-behavior: smooth; } body { margin: 0; background: var(--bg); color: var(--text); font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; -webkit-font-smoothing: antialiased; } a { text-decoration: none; } button, input, select, textarea { font-family: inherit; } /* ===================================================== PAGE ===================================================== */ .page { margin-left: 280px; min-height: 100vh; } /* ===================================================== STICKY TOPBAR ===================================================== */ .topbar { position: sticky; top: 0; z-index: 900; min-height: 76px; display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 12px 30px; background: rgba(255,255,255,.90); backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px); border-bottom: 1px solid rgba(226,232,240,.9); box-shadow: 0 8px 30px rgba(15,23,42,.045); } .topbar-left { display: flex; align-items: center; gap: 13px; min-width: 0; } .page-icon { width: 44px; height: 44px; flex: 0 0 44px; display: flex; align-items: center; justify-content: center; color: #fff; background: linear-gradient( 135deg, var(--primary), var(--primary-light) ); border-radius: 13px; box-shadow: 0 8px 22px rgba(15,118,110,.20); } .heading h1 { margin: 0; font-size: 17px; font-weight: 800; letter-spacing: -.025em; } .breadcrumb { display: flex; align-items: center; gap: 7px; margin-top: 4px; color: var(--muted); font-size: 10px; } .breadcrumb a { color: var(--primary); } .admin-pill { display: flex; align-items: center; gap: 9px; padding: 6px 11px 6px 6px; background: #fff; border: 1px solid var(--border); border-radius: 14px; } .avatar { width: 34px; height: 34px; display: flex; align-items: center; justify-content: center; color: #fff; background: linear-gradient( 135deg, var(--primary), var(--primary-light) ); border-radius: 10px; font-size: 13px; font-weight: 800; } .admin-info strong { display: block; max-width: 150px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: 11px; } .admin-info span { display: block; margin-top: 2px; color: var(--muted); font-size: 9px; } /* ===================================================== CONTENT ===================================================== */ .content { max-width: 1600px; margin: 0 auto; padding: 30px; } .content-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; margin-bottom: 23px; } .title h2 { margin: 0; font-size: 28px; font-weight: 800; letter-spacing: -.045em; } .title p { margin: 8px 0 0; color: var(--muted); font-size: 12px; line-height: 1.65; } /* ===================================================== BUTTONS ===================================================== */ .btn { min-height: 43px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; padding: 0 15px; border: 1px solid transparent; border-radius: 11px; cursor: pointer; font-size: 11px; font-weight: 700; transition: .18s ease; } .btn:hover { transform: translateY(-1px); } .btn-primary { color: #fff; background: linear-gradient( 135deg, var(--primary), var(--primary-light) ); box-shadow: 0 8px 20px rgba(15,118,110,.18); } .btn-light { color: var(--text); background: #fff; border-color: var(--border); } .btn-danger { color: #b91c1c; background: #fff; border-color: #fecaca; } /* ===================================================== ALERTS ===================================================== */ .alert { display: flex; align-items: flex-start; gap: 10px; padding: 14px 16px; margin-bottom: 20px; border-radius: 13px; font-size: 11px; line-height: 1.5; } .alert-success { color: #166534; background: #f0fdf4; border: 1px solid #bbf7d0; } .alert-danger { color: #991b1b; background: #fef2f2; border: 1px solid #fecaca; } .error-list { margin: 7px 0 0; padding-left: 18px; } /* ===================================================== STATS ===================================================== */ .stats { display: grid; grid-template-columns: repeat(4, minmax(0,1fr)); gap: 15px; margin-bottom: 22px; } .stat { display: flex; align-items: center; gap: 13px; padding: 18px; background: #fff; border: 1px solid var(--border); border-radius: 16px; box-shadow: 0 7px 25px rgba(15,23,42,.045); } .stat-icon { width: 44px; height: 44px; flex: 0 0 44px; display: flex; align-items: center; justify-content: center; color: var(--primary); background: #ecfdf5; border-radius: 12px; } .stat:nth-child(2) .stat-icon { color: var(--success); background: #f0fdf4; } .stat:nth-child(3) .stat-icon { color: var(--warning); background: #fffbeb; } .stat:nth-child(4) .stat-icon { color: var(--purple); background: #f5f3ff; } .stat-value { display: block; font-size: 21px; font-weight: 800; letter-spacing: -.03em; } .stat-label { display: block; margin-top: 3px; color: var(--muted); font-size: 9px; font-weight: 600; } /* ===================================================== MAIN GRID ===================================================== */ .main-grid { display: grid; grid-template-columns: minmax(350px,.82fr) minmax(0,1.8fr); gap: 22px; align-items: start; } .card { background: #fff; border: 1px solid rgba(226,232,240,.95); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; } .card-header { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 20px 22px; border-bottom: 1px solid var(--border); } .card-header h3 { margin: 0; font-size: 15px; font-weight: 800; } .card-header p { margin: 5px 0 0; color: var(--muted); font-size: 9px; } .card-body { padding: 22px; } /* ===================================================== FORM ===================================================== */ .form-group { margin-bottom: 16px; } .form-label { display: block; margin-bottom: 7px; color: #374151; font-size: 10px; font-weight: 800; } .required { color: #dc2626; } .form-control, .form-select, .form-textarea { width: 100%; border: 1px solid #dfe4ea; border-radius: 10px; outline: none; color: var(--text); background: #fff; font-size: 11px; transition: .18s ease; } .form-control, .form-select { height: 44px; padding: 0 12px; } .form-textarea { min-height: 105px; resize: vertical; padding: 11px 12px; line-height: 1.6; } .form-control:focus, .form-select:focus, .form-textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 4px rgba(15,118,110,.08); } .form-help { margin-top: 5px; color: #8a94a6; font-size: 9px; line-height: 1.5; } .input-wrap { position: relative; } .input-wrap i { position: absolute; left: 13px; top: 50%; transform: translateY(-50%); color: #9ca3af; font-size: 11px; pointer-events: none; } .input-wrap .form-control { padding-left: 36px; } .two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } .three-col { display: grid; grid-template-columns: repeat(3,1fr); gap: 12px; } .form-actions { display: flex; gap: 9px; margin-top: 20px; } .form-actions .btn { flex: 1; } /* ===================================================== TOGGLE ===================================================== */ .toggle-box { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 12px 13px; background: #f8fafc; border: 1px solid #e5e7eb; border-radius: 11px; } .toggle-content strong { display: block; font-size: 10px; } .toggle-content span { display: block; margin-top: 3px; color: var(--muted); font-size: 8px; } .switch { position: relative; width: 43px; height: 24px; flex: 0 0 43px; } .switch input { display: none; } .slider { position: absolute; inset: 0; cursor: pointer; background: #cbd5e1; border-radius: 50px; transition: .2s; } .slider:before { content: ""; position: absolute; width: 18px; height: 18px; left: 3px; top: 3px; background: #fff; border-radius: 50%; transition: .2s; box-shadow: 0 2px 5px rgba(0,0,0,.15); } .switch input:checked + .slider { background: var(--primary); } .switch input:checked + .slider:before { transform: translateX(19px); } /* ===================================================== TOOLBAR ===================================================== */ .toolbar { display: grid; grid-template-columns: minmax(180px,1.5fr) minmax(140px,.8fr) minmax(130px,.7fr) minmax(120px,.65fr) auto; gap: 9px; margin-bottom: 15px; } .toolbar .btn { height: 44px; } /* ===================================================== TABLE ===================================================== */ .table-wrap { width: 100%; overflow-x: auto; } table { width: 100%; min-width: 980px; border-collapse: collapse; } thead th { padding: 12px 14px; text-align: left; color: #64748b; background: #f8fafc; border-bottom: 1px solid var(--border); font-size: 9px; font-weight: 800; text-transform: uppercase; letter-spacing: .055em; } tbody td { padding: 14px; vertical-align: middle; border-bottom: 1px solid #edf0f3; font-size: 10px; } tbody tr:hover { background: #fbfdfd; } .post-id { color: #94a3b8; font-size: 9px; font-weight: 800; } .post-title { max-width: 260px; color: var(--text); font-size: 11px; font-weight: 800; line-height: 1.45; } .post-slug { max-width: 260px; margin-top: 3px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; color: #94a3b8; font-size: 8px; } .category-badge { display: inline-flex; align-items: center; padding: 5px 8px; color: #2563eb; background: #eff6ff; border: 1px solid #bfdbfe; border-radius: 7px; font-size: 8px; font-weight: 800; } .author-name { font-size: 9px; font-weight: 700; } .author-email { margin-top: 2px; color: #94a3b8; font-size: 8px; } .status-badge { display: inline-flex; align-items: center; gap: 5px; padding: 5px 8px; border-radius: 7px; font-size: 8px; font-weight: 800; text-transform: capitalize; } .status-published { color: #166534; background: #f0fdf4; border: 1px solid #bbf7d0; } .status-draft { color: #92400e; background: #fffbeb; border: 1px solid #fde68a; } .status-inactive { color: #991b1b; background: #fef2f2; border: 1px solid #fecaca; } .featured-badge { display: inline-flex; align-items: center; gap: 5px; margin-top: 5px; color: #b45309; font-size: 8px; font-weight: 800; } .views { color: #475569; font-size: 9px; font-weight: 700; } .date { color: #64748b; font-size: 8px; line-height: 1.5; } .action-group { display: flex; gap: 5px; } .icon-btn { width: 31px; height: 31px; display: inline-flex; align-items: center; justify-content: center; background: #fff; border: 1px solid var(--border); border-radius: 8px; cursor: pointer; font-size: 10px; transition: .17s ease; } .icon-btn.edit { color: var(--primary); } .icon-btn.edit:hover { color: #fff; background: var(--primary); border-color: var(--primary); } .icon-btn.delete { color: #dc2626; } .icon-btn.delete:hover { color: #fff; background: #dc2626; border-color: #dc2626; } /* ===================================================== EMPTY ===================================================== */ .empty { padding: 60px 20px; text-align: center; } .empty-icon { width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; margin: 0 auto 14px; color: var(--primary); background: #ecfdf5; border-radius: 17px; font-size: 22px; } .empty h4 { margin: 0; font-size: 14px; font-weight: 800; } .empty p { max-width: 430px; margin: 7px auto 0; color: var(--muted); font-size: 10px; line-height: 1.6; } /* ===================================================== PAGINATION ===================================================== */ .pagination { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 16px 20px; border-top: 1px solid var(--border); } .pagination-info { color: var(--muted); font-size: 9px; } .pagination-links { display: flex; gap: 4px; } .page-link { min-width: 30px; height: 30px; display: inline-flex; align-items: center; justify-content: center; padding: 0 7px; color: #64748b; background: #fff; border: 1px solid var(--border); border-radius: 7px; font-size: 9px; font-weight: 700; } .page-link.active { color: #fff; background: var(--primary); border-color: var(--primary); } /* ===================================================== RESPONSIVE ===================================================== */ @media (max-width: 1250px) { .page { margin-left: 0; } .main-grid { grid-template-columns: 1fr; } } @media (max-width: 1000px) { .stats { grid-template-columns: repeat(2,1fr); } .toolbar { grid-template-columns: 1fr 1fr; } } @media (max-width: 650px) { .topbar { padding: 11px 15px; } .heading { display: none; } .content { padding: 20px 15px; } .content-header { flex-direction: column; } .content-header .btn { width: 100%; } .stats { grid-template-columns: 1fr; } .toolbar { grid-template-columns: 1fr; } .two-col, .three-col { grid-template-columns: 1fr; } .admin-info { display: none; } .card-body, .card-header { padding: 17px; } .pagination { flex-direction: column; align-items: stretch; } .pagination-links { justify-content: center; } } </style> </head> <body> <?php /* |-------------------------------------------------------------------------- | SEPARATE SIDEBAR |-------------------------------------------------------------------------- | | Existing admin/sidebar.php is included directly. | admin/header.php is intentionally NOT included. | */ require_once __DIR__ . '/sidebar.php'; ?> <div class="page"> <!-- ===================================================== STICKY TOPBAR ====================================================== --> <header class="topbar"> <div class="topbar-left"> <div class="page-icon"> <i class="fa-solid fa-newspaper" ></i> </div> <div class="heading"> <h1> Blog Posts </h1> <div class="breadcrumb"> <a href="index.php"> Dashboard </a> <i class="fa-solid fa-chevron-right" ></i> <span> Blog Posts </span> </div> </div> </div> <div> <div class="admin-pill"> <div class="avatar"> <?php echo e( strtoupper( substr( trim( $adminName ), 0, 1 ) ) ); ?> </div> <div class="admin-info"> <strong> <?php echo e( $adminName ); ?> </strong> <span> <?php echo e( $adminRole ); ?> </span> </div> </div> </div> </header> <!-- ===================================================== CONTENT ====================================================== --> <main class="content"> <!-- PAGE HEADER --> <div class="content-header"> <div class="title"> <h2> Blog Posts </h2> <p> Create, publish and manage your Pure Chemical blog content. </p> </div> <div> <?php if ($editId > 0): ?> <a href="blog_posts.php" class="btn btn-light" > <i class="fa-solid fa-plus" ></i> New Post </a> <?php else: ?> <a href="#post-form" class="btn btn-primary" > <i class="fa-solid fa-plus" ></i> Add Blog Post </a> <?php endif; ?> </div> </div> <!-- ================================================= FLASH ================================================== --> <?php if ($flash): ?> <div class="alert <?php echo ($flash['type'] ?? '') === 'success' ? 'alert-success' : 'alert-danger'; ?>" > <i class="fa-solid <?php echo ($flash['type'] ?? '') === 'success' ? 'fa-circle-check' : 'fa-circle-exclamation'; ?>" ></i> <div> <?php echo e( $flash['message'] ?? '' ); ?> </div> </div> <?php endif; ?> <!-- ================================================= ERRORS ================================================== --> <?php if ($errors): ?> <div class="alert alert-danger"> <i class="fa-solid fa-circle-exclamation" ></i> <div> <strong> Please fix the following: </strong> <ul class="error-list"> <?php foreach ( $errors as $error ): ?> <li> <?php echo e( $error ); ?> </li> <?php endforeach; ?> </ul> </div> </div> <?php endif; ?> <!-- ================================================= STATS ================================================== --> <div class="stats"> <!-- TOTAL --> <div class="stat"> <div class="stat-icon"> <i class="fa-solid fa-newspaper" ></i> </div> <div> <span class="stat-value"> <?php echo number_format( $stats['total'] ); ?> </span> <span class="stat-label"> Total Posts </span> </div> </div> <!-- PUBLISHED --> <div class="stat"> <div class="stat-icon"> <i class="fa-solid fa-circle-check" ></i> </div> <div> <span class="stat-value"> <?php echo number_format( $stats['published'] ); ?> </span> <span class="stat-label"> Published </span> </div> </div> <!-- DRAFT --> <div class="stat"> <div class="stat-icon"> <i class="fa-solid fa-file-pen" ></i> </div> <div> <span class="stat-value"> <?php echo number_format( $stats['draft'] ); ?> </span> <span class="stat-label"> Draft Posts </span> </div> </div> <!-- FEATURED --> <div class="stat"> <div class="stat-icon"> <i class="fa-solid fa-star" ></i> </div> <div> <span class="stat-value"> <?php echo number_format( $stats['featured'] ); ?> </span> <span class="stat-label"> Featured Posts </span> </div> </div> </div> <!-- ================================================= MAIN GRID ================================================== --> <div class="main-grid"> <!-- ================================================= FORM ================================================== --> <section class="card" id="post-form" > <div class="card-header"> <div> <h3> <?php if ($editId > 0): ?> <i class="fa-solid fa-pen-to-square" style=" color:#0f766e; margin-right:6px; " ></i> Edit Blog Post <?php else: ?> <i class="fa-solid fa-plus" style=" color:#0f766e; margin-right:6px; " ></i> Add Blog Post <?php endif; ?> </h3> <p> Manage complete blog content. </p> </div> <?php if ($editId > 0): ?> <a href="blog_posts.php" class="btn btn-light" style="min-height:34px;" > Cancel </a> <?php endif; ?> </div> <div class="card-body"> <form method="post" action="" id="postForm" enctype="multipart/form-data" > <?php echo blog_posts_csrf_field(); ?> <input type="hidden" name="action" value="save" > <input type="hidden" name="id" value="<?php echo (int)$form['id']; ?>" > <!-- TITLE --> <div class="form-group"> <label class="form-label" > Post Title <span class="required"> * </span> </label> <div class="input-wrap"> <i class="fa-solid fa-heading" ></i> <input type="text" name="title" id="postTitle" class="form-control" value="<?php echo e( $form['title'] ); ?>" maxlength="500" required placeholder="Enter blog post title" > </div> </div> <!-- SLUG --> <div class="form-group"> <label class="form-label" > Slug <span class="required"> * </span> </label> <div class="input-wrap"> <i class="fa-solid fa-link" ></i> <input type="text" name="slug" id="postSlug" class="form-control" value="<?php echo e( $form['slug'] ); ?>" maxlength="500" required placeholder="blog-post-slug" > </div> <div class="form-help"> URL-friendly slug. It is generated automatically from the title. </div> </div> <!-- CATEGORY + AUTHOR --> <div class="two-col"> <div class="form-group"> <label class="form-label" > Category </label> <select name="category_id" class="form-select" > <option value=""> No Category </option> <?php foreach ( $categories as $category ): ?> <option value="<?php echo (int)$category['id']; ?>" <?php echo (string)$form['category_id'] === (string)$category['id'] ? 'selected' : ''; ?> > <?php echo e( $category['name'] ); ?> </option> <?php endforeach; ?> </select> </div> <div class="form-group"> <label class="form-label" > Author </label> <select name="author_id" class="form-select" > <option value=""> No Author </option> <?php foreach ( $authors as $admin ): ?> <option value="<?php echo (int)$admin['id']; ?>" <?php echo (string)$form['author_id'] === (string)$admin['id'] ? 'selected' : ''; ?> > <?php echo e( $admin['name'] ?: $admin['email'] ); ?> <?php if ( !empty( $admin['email'] ) ) { echo ' — ' . e( $admin['email'] ); } ?> </option> <?php endforeach; ?> </select> </div> </div> <!-- EXCERPT --> <div class="form-group"> <label class="form-label" > Excerpt </label> <textarea name="excerpt" class="form-textarea" maxlength="65535" placeholder="Short summary of the blog post..." style="min-height:90px;" ><?php echo e( $form['excerpt'] ); ?></textarea> <div class="form-help"> Short description used in blog listings and cards. </div> </div> <!-- CONTENT --> <div class="form-group"> <label class="form-label" > Content <span class="required"> * </span> </label> <textarea name="content" class="form-textarea" style=" min-height:260px; " placeholder="Write the complete blog post content..." ><?php echo e( $form['content'] ); ?></textarea> <div class="form-help"> Long-form blog content is stored in the existing <strong>content</strong> column. </div> </div> <!-- IMAGE + VIDEO --> <div class="two-col"> <div class="form-group"> <label class="form-label">Featured Image</label> <select name="featured_image_id" class="form-select"> <option value="">No featured image</option> <?php foreach (($mediaItems ?? []) as $mediaItem): ?> <option value="<?php echo (int)$mediaItem['id']; ?>" <?php echo ((string)$form['featured_image_id'] === (string)$mediaItem['id']) ? 'selected' : ''; ?>> <?php echo e($mediaItem['original_name']); ?> (ID: <?php echo (int)$mediaItem['id']; ?>) </option> <?php endforeach; ?> </select> <div class="form-help">Existing image choose karein, ya neeche nayi image upload karein.</div> <label class="form-label" style="margin-top:12px;">Upload New Image</label> <input type="file" name="featured_image_file" class="form-control" accept="image/jpeg,image/png,image/gif,image/webp" style="padding:10px;height:auto;"> <div class="form-help">JPG, PNG, GIF, WEBP — maximum 8 MB. Upload automatically media table mein save hoga.</div> </div> <div class="form-group"> <label class="form-label" > Video URL </label> <div class="input-wrap"> <i class="fa-solid fa-video" ></i> <input type="url" name="video_url" class="form-control" value="<?php echo e( $form['video_url'] ); ?>" maxlength="1000" placeholder="https://..." > </div> <div class="form-help"> Optional HTTP/HTTPS video URL. </div> </div> </div> <!-- STATUS + PUBLISHED DATE --> <div class="two-col"> <div class="form-group"> <label class="form-label" > Status <span class="required"> * </span> </label> <select name="status" class="form-select" > <?php foreach ( $statusOptions as $status ): ?> <option value="<?php echo e( $status ); ?>" <?php echo $form['status'] === $status ? 'selected' : ''; ?> > <?php echo e( ucfirst( $status ) ); ?> </option> <?php endforeach; ?> </select> </div> <div class="form-group"> <label class="form-label" > Published At </label> <input type="datetime-local" name="published_at" class="form-control" value="<?php echo e( $form['published_at'] ); ?>" > <div class="form-help"> If status is Published and this is empty, current date/time is used. </div> </div> </div> <!-- FEATURED --> <div class="form-group"> <div class="toggle-box"> <div class="toggle-content"> <strong> Featured Blog Post </strong> <span> Show this post in featured blog sections. </span> </div> <label class="switch"> <input type="checkbox" name="featured" value="1" <?php echo (int)$form['featured'] === 1 ? 'checked' : ''; ?> > <span class="slider" ></span> </label> </div> </div> <!-- ACTIONS --> <div class="form-actions"> <?php if ($editId > 0): ?> <a href="blog_posts.php" class="btn btn-light" > Cancel </a> <?php endif; ?> <button type="submit" class="btn btn-primary" id="savePostBtn" > <i class="fa-solid <?php echo $editId > 0 ? 'fa-floppy-disk' : 'fa-plus'; ?>" ></i> <?php echo $editId > 0 ? 'Update Post' : 'Create Post'; ?> </button> </div> </form> </div> </section> <!-- ================================================= LIST ================================================== --> <section class="card"> <div class="card-header"> <div> <h3> <i class="fa-solid fa-layer-group" style=" color:#0f766e; margin-right:6px; " ></i> All Blog Posts </h3> <p> <?php echo number_format( $totalPosts ); ?> total posts </p> </div> </div> <div class="card-body"> <!-- FILTERS --> <form method="get" action="blog_posts.php" class="toolbar" > <!-- SEARCH --> <div class="input-wrap"> <i class="fa-solid fa-magnifying-glass" ></i> <input type="search" name="q" class="form-control" value="<?php echo e( $search ); ?>" placeholder="Search posts..." > </div> <!-- CATEGORY --> <select name="category" class="form-select" > <option value=""> All Categories </option> <?php foreach ( $categories as $category ): ?> <option value="<?php echo (int)$category['id']; ?>" <?php echo $filterCategory === (int)$category['id'] ? 'selected' : ''; ?> > <?php echo e( $category['name'] ); ?> </option> <?php endforeach; ?> </select> <!-- STATUS --> <select name="status" class="form-select" > <option value=""> All Status </option> <?php foreach ( $statusOptions as $status ): ?> <option value="<?php echo e( $status ); ?>" <?php echo $filterStatus === $status ? 'selected' : ''; ?> > <?php echo e( ucfirst( $status ) ); ?> </option> <?php endforeach; ?> </select> <!-- FEATURED --> <select name="featured" class="form-select" > <option value=""> Featured: All </option> <option value="1" <?php echo $filterFeatured === '1' ? 'selected' : ''; ?> > Featured </option> <option value="0" <?php echo $filterFeatured === '0' ? 'selected' : ''; ?> > Not Featured </option> </select> <!-- FILTER --> <button type="submit" class="btn btn-primary" > <i class="fa-solid fa-filter" ></i> Filter </button> </form> <?php if ( $search !== '' || $filterCategory > 0 || $filterStatus !== '' || $filterFeatured !== '' ): ?> <div style=" margin-bottom:15px; " > <a href="blog_posts.php" style=" display:inline-flex; align-items:center; gap:6px; color:#0f766e; font-size:9px; font-weight:800; " > <i class="fa-solid fa-xmark" ></i> Clear all filters </a> </div> <?php endif; ?> </div> <!-- TABLE --> <div class="table-wrap"> <?php if ($posts): ?> <table> <thead> <tr> <th> ID </th> <th> Post </th> <th> Category </th> <th> Author </th> <th> Status </th> <th> Views </th> <th> Published </th> <th> Actions </th> </tr> </thead> <tbody> <?php foreach ( $posts as $post ): ?> <tr> <!-- ID --> <td> <span class="post-id" > # <?php echo (int)$post['id']; ?> </span> </td> <!-- POST --> <td> <div class="post-title" > <?php echo e( $post['title'] ); ?> </div> <div class="post-slug" > <?php echo e( $post['slug'] ); ?> </div> <?php if ( (int)$post['featured'] === 1 ): ?> <div class="featured-badge" > <i class="fa-solid fa-star" ></i> Featured </div> <?php endif; ?> </td> <!-- CATEGORY --> <td> <?php if ( !empty( $post['category_name'] ) ): ?> <span class="category-badge" > <i class="fa-solid fa-folder" style=" margin-right:4px; " ></i> <?php echo e( $post['category_name'] ); ?> </span> <?php else: ?> <span style=" color:#94a3b8; font-size:9px; " > Uncategorized </span> <?php endif; ?> </td> <!-- AUTHOR --> <td> <?php if ( !empty( $post['author_name'] ) ): ?> <div class="author-name" > <?php echo e( $post['author_name'] ); ?> </div> <?php if ( !empty( $post['author_email'] ) ): ?> <div class="author-email" > <?php echo e( $post['author_email'] ); ?> </div> <?php endif; ?> <?php else: ?> <span style=" color:#94a3b8; font-size:9px; " > No author </span> <?php endif; ?> </td> <!-- STATUS --> <td> <span class="status-badge status-<?php echo e( $post['status'] ); ?>" > <?php if ( $post['status'] === 'published' ) { echo '<i class="fa-solid fa-circle-check"></i>'; } elseif ( $post['status'] === 'draft' ) { echo '<i class="fa-solid fa-file-pen"></i>'; } else { echo '<i class="fa-solid fa-ban"></i>'; } ?> <?php echo e( $post['status'] ); ?> </span> </td> <!-- VIEWS --> <td> <span class="views" > <i class="fa-solid fa-eye" style=" color:#94a3b8; margin-right:4px; " ></i> <?php echo number_format( (int)$post['views'] ); ?> </span> </td> <!-- DATE --> <td> <?php if ( !empty( $post['published_at'] ) ): ?> <div class="date" > <i class="fa-regular fa-calendar" ></i> <?php echo e( date( 'd M Y', strtotime( $post['published_at'] ) ) ); ?> <br> <?php echo e( date( 'h:i A', strtotime( $post['published_at'] ) ) ); ?> </div> <?php else: ?> <span style=" color:#94a3b8; font-size:8px; " > Not published </span> <?php endif; ?> </td> <!-- ACTIONS --> <td> <div class="action-group" > <!-- EDIT --> <a href="blog_posts.php?edit=<?php echo (int)$post['id']; ?>" class="icon-btn edit" title="Edit" > <i class="fa-solid fa-pen" ></i> </a> <!-- DELETE --> <form method="post" action="" style="margin:0;" onsubmit=" return confirm( 'Are you sure you want to delete this blog post? Related blog media/tag links will also be removed when those relations exist.' ); " > <?php echo blog_posts_csrf_field(); ?> <input type="hidden" name="action" value="delete" > <input type="hidden" name="id" value="<?php echo (int)$post['id']; ?>" > <button type="submit" class="icon-btn delete" title="Delete" > <i class="fa-solid fa-trash" ></i> </button> </form> </div> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php else: ?> <div class="empty"> <div class="empty-icon" > <i class="fa-solid fa-newspaper" ></i> </div> <h4> No blog posts found </h4> <p> <?php if ( $search !== '' || $filterCategory > 0 || $filterStatus !== '' || $filterFeatured !== '' ) { echo 'No blog post matches your current filters. Clear the filters or create a new post.'; } else { echo 'No blog posts have been created yet. Use the form to create your first actual blog post.'; } ?> </p> </div> <?php endif; ?> </div> <!-- ================================================= PAGINATION ================================================== --> <?php if ( $totalPages > 1 ): ?> <div class="pagination" > <div class="pagination-info" > Showing <?php echo $totalPosts > 0 ? $offset + 1 : 0; ?> – <?php echo min( $offset + $perPage, $totalPosts ); ?> of <?php echo number_format( $totalPosts ); ?> posts </div> <div class="pagination-links" > <?php if ( $page > 1 ): ?> <a class="page-link" href="<?php echo e( blog_posts_page_url( $page - 1, $search, $filterCategory, $filterStatus, $filterFeatured ) ); ?>" > <i class="fa-solid fa-chevron-left" ></i> </a> <?php endif; ?> <?php $startPage = max( 1, $page - 2 ); $endPage = min( $totalPages, $page + 2 ); for ( $p = $startPage; $p <= $endPage; $p++ ): ?> <a class="page-link <?php echo $p === $page ? 'active' : ''; ?>" href="<?php echo e( blog_posts_page_url( $p, $search, $filterCategory, $filterStatus, $filterFeatured ) ); ?>" > <?php echo $p; ?> </a> <?php endfor; ?> <?php if ( $page < $totalPages ): ?> <a class="page-link" href="<?php echo e( blog_posts_page_url( $page + 1, $search, $filterCategory, $filterStatus, $filterFeatured ) ); ?>" > <i class="fa-solid fa-chevron-right" ></i> </a> <?php endif; ?> </div> </div> <?php endif; ?> </section> </div> </main> </div> <script> /* ========================================================= BLOG POST JS ========================================================= */ document.addEventListener( 'DOMContentLoaded', function () { /* ===================================================== TITLE -> SLUG ===================================================== */ const title = document.getElementById( 'postTitle' ); const slug = document.getElementById( 'postSlug' ); let slugManuallyChanged = <?php echo $editId > 0 ? 'true' : 'false'; ?>; if (slug) { slug.addEventListener( 'input', function () { slugManuallyChanged = true; } ); } if (title && slug) { title.addEventListener( 'input', function () { if ( slugManuallyChanged ) { return; } let value = title.value .toLowerCase() .trim(); value = value.replace( /[^\p{L}\p{N}]+/gu, '-' ); value = value.replace( /^-+|-+$/g, '' ); slug.value = value; } ); } /* ===================================================== FORM LOADING ===================================================== */ const form = document.getElementById( 'postForm' ); const saveBtn = document.getElementById( 'savePostBtn' ); if ( form && saveBtn ) { form.addEventListener( 'submit', function () { saveBtn.disabled = true; saveBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Saving...'; } ); } /* ===================================================== EDIT FORM SCROLL ===================================================== */ const params = new URLSearchParams( window.location.search ); if ( params.has('edit') && form ) { setTimeout( function () { form.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 150 ); } } ); </script> </body> </html>
Save
Cancel