📁 File Manager
Editing:
/home/wvl7mof7402e/public_html/chem/admin/section_media.php
<?php /** * PURE CHEMICAL ADMIN * section_media.php * * Existing table: section_media * No new table is created. */ if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); } require_once __DIR__ . '/includes/db.php'; if (file_exists(__DIR__ . '/includes/auth.php')) { require_once __DIR__ . '/includes/auth.php'; } 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'; } if (function_exists('requireAdmin')) { requireAdmin(); } /* ========================================================= HELPERS ========================================================= */ function sm_e($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); } function sm_post_string(string $key, ?string $default = null): ?string { if (!isset($_POST[$key])) { return $default; } return trim((string)$_POST[$key]); } function sm_post_int(string $key, int $default = 0): int { if (!isset($_POST[$key]) || !is_numeric($_POST[$key])) { return $default; } return (int)$_POST[$key]; } function sm_csrf_field(): string { if (function_exists('csrf_field')) { return (string)csrf_field(); } if (empty($_SESSION['section_media_csrf'])) { $_SESSION['section_media_csrf'] = bin2hex(random_bytes(32)); } return '<input type="hidden" name="csrf_token" value="' . sm_e($_SESSION['section_media_csrf']) . '">'; } function sm_verify_csrf(): bool { if (function_exists('csrf_verify')) { return (bool)csrf_verify(); } $token = $_POST['csrf_token'] ?? ''; return !empty($_SESSION['section_media_csrf']) && is_string($token) && hash_equals($_SESSION['section_media_csrf'], $token); } /* ========================================================= FLASH ========================================================= */ $success = $_SESSION['section_media_success'] ?? ''; $error = $_SESSION['section_media_error'] ?? ''; unset( $_SESSION['section_media_success'], $_SESSION['section_media_error'] ); /* ========================================================= POST ACTIONS ========================================================= */ if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (!sm_verify_csrf()) { $_SESSION['section_media_error'] = 'Security verification failed. Please try again.'; header('Location: section_media.php'); exit; } $action = $_POST['action'] ?? ''; /* ===================================================== SAVE ===================================================== */ if ($action === 'save') { $id = sm_post_int('id'); $sectionId = sm_post_int('section_id'); $mediaId = sm_post_int('media_id'); $mediaRole = sm_post_string('media_role', 'image'); $externalUrl = sm_post_string('external_url'); $title = sm_post_string('title'); $caption = sm_post_string('caption'); $altText = sm_post_string('alt_text'); $sortOrder = sm_post_int('sort_order', 0); $status = isset($_POST['status']) ? 1 : 0; $allowedRoles = [ 'image', 'video', 'poster', 'background', 'pdf' ]; $errors = []; if ($sectionId <= 0) { $errors[] = 'Please select a section.'; } $uploadedFile = $_FILES['media_upload'] ?? null; $hasUploadedFile = is_array($uploadedFile) && (int)($uploadedFile['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE; if (!in_array($mediaRole, $allowedRoles, true)) { $errors[] = 'Invalid media role selected.'; } if ($sortOrder < 0) { $sortOrder = 0; } /* --------------------------------------------- Verify section --------------------------------------------- */ if (!$errors) { try { $stmt = $pdo->prepare( "SELECT id FROM page_sections WHERE id = ? LIMIT 1" ); $stmt->execute([$sectionId]); if (!$stmt->fetchColumn()) { $errors[] = 'Selected section does not exist.'; } } catch (Throwable $e) { error_log( 'section_media section validation: ' . $e->getMessage() ); $errors[] = 'Unable to verify selected section.'; } } /* --------------------------------------------- Optional upload into the existing media table --------------------------------------------- */ if (!$errors && $hasUploadedFile) { $uploadError = (int)($uploadedFile['error'] ?? UPLOAD_ERR_NO_FILE); if ($uploadError !== UPLOAD_ERR_OK) { $errors[] = 'Upload failed. Please select the file again (PHP upload error ' . $uploadError . ').'; } elseif ((int)($uploadedFile['size'] ?? 0) > 20 * 1024 * 1024) { $errors[] = 'File is too large. Maximum upload size is 20 MB.'; } else { $tmpPath = (string)($uploadedFile['tmp_name'] ?? ''); $originalName = basename((string)($uploadedFile['name'] ?? 'upload')); $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION)); $finfo = new finfo(FILEINFO_MIME_TYPE); $mimeType = $tmpPath !== '' && is_file($tmpPath) ? (string)$finfo->file($tmpPath) : ''; $allowedUploads = [ 'jpg' => ['image/jpeg', 'image'], 'jpeg' => ['image/jpeg', 'image'], 'png' => ['image/png', 'image'], 'gif' => ['image/gif', 'image'], 'webp' => ['image/webp', 'image'], 'mp4' => ['video/mp4', 'video'], 'webm' => ['video/webm', 'video'], 'pdf' => ['application/pdf', 'pdf'] ]; if (!isset($allowedUploads[$extension]) || $mimeType !== $allowedUploads[$extension][0]) { $errors[] = 'Unsupported file. Use JPG, PNG, GIF, WEBP, MP4, WEBM or PDF.'; } elseif ($tmpPath === '' || !is_uploaded_file($tmpPath)) { $errors[] = 'Uploaded file could not be verified. Please try again.'; } else { $uploadDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'media'; if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) { $errors[] = 'Could not create uploads/media folder. Check folder permissions.'; } else { $safeName = bin2hex(random_bytes(16)) . '.' . $extension; $destination = $uploadDir . DIRECTORY_SEPARATOR . $safeName; $relativePath = 'uploads/media/' . $safeName; if (!move_uploaded_file($tmpPath, $destination)) { $errors[] = 'Could not save uploaded file. Check uploads/media folder permissions.'; } else { try { $width = null; $height = null; if ($allowedUploads[$extension][1] === 'image') { $imageInfo = @getimagesize($destination); if (is_array($imageInfo)) { $width = (int)$imageInfo[0]; $height = (int)$imageInfo[1]; } } $mediaInsert = $pdo->prepare( "INSERT INTO media (original_name, file_name, file_path, mime_type, file_type, extension, file_size, width, height, alt_text, title, caption, uploaded_by, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, 1)" ); $mediaInsert->execute([ $originalName, $safeName, $relativePath, $mimeType, $allowedUploads[$extension][1], $extension, (int)filesize($destination), $width, $height, $altText !== '' ? $altText : null, $title !== '' ? $title : $originalName, $caption !== '' ? $caption : null ]); $mediaId = (int)$pdo->lastInsertId(); if ($mediaId <= 0) { throw new RuntimeException('Media row was not created.'); } } catch (Throwable $e) { @unlink($destination); error_log('section_media upload database error: ' . $e->getMessage()); $errors[] = 'File was uploaded but its media record could not be saved. Check the media table and PHP error log.'; } } } } } } if (!$errors && $mediaId <= 0) { $errors[] = 'Please choose an existing media item or upload a file.'; } /* --------------------------------------------- Verify media --------------------------------------------- */ if (!$errors) { try { $stmt = $pdo->prepare( "SELECT id FROM media WHERE id = ? LIMIT 1" ); $stmt->execute([$mediaId]); if (!$stmt->fetchColumn()) { $errors[] = 'Selected media record does not exist.'; } } catch (Throwable $e) { error_log( 'section_media media validation: ' . $e->getMessage() ); $errors[] = 'Unable to verify media record.'; } } if (!$errors) { try { if ($id > 0) { /* --------------------------------- UPDATE --------------------------------- */ $check = $pdo->prepare( "SELECT id FROM section_media WHERE id = ? LIMIT 1" ); $check->execute([$id]); if (!$check->fetchColumn()) { throw new RuntimeException( 'Section media record not found.' ); } $stmt = $pdo->prepare( "UPDATE section_media SET section_id = ?, media_id = ?, media_role = ?, external_url = ?, title = ?, caption = ?, alt_text = ?, sort_order = ?, status = ? WHERE id = ?" ); $stmt->execute([ $sectionId, $mediaId, $mediaRole, $externalUrl !== '' ? $externalUrl : null, $title !== '' ? $title : null, $caption !== '' ? $caption : null, $altText !== '' ? $altText : null, $sortOrder, $status, $id ]); $_SESSION['section_media_success'] = 'Section media updated successfully.'; } else { /* --------------------------------- INSERT --------------------------------- */ $stmt = $pdo->prepare( "INSERT INTO section_media ( section_id, media_id, media_role, external_url, title, caption, alt_text, sort_order, status ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" ); $stmt->execute([ $sectionId, $mediaId, $mediaRole, $externalUrl !== '' ? $externalUrl : null, $title !== '' ? $title : null, $caption !== '' ? $caption : null, $altText !== '' ? $altText : null, $sortOrder, $status ]); $_SESSION['section_media_success'] = 'Section media added successfully.'; } } catch (Throwable $e) { error_log( 'section_media save error: ' . $e->getMessage() ); $_SESSION['section_media_error'] = 'Unable to save section media. Please try again.'; } } else { $_SESSION['section_media_error'] = implode(' ', $errors); } header('Location: section_media.php'); exit; } /* ===================================================== DELETE ===================================================== */ if ($action === 'delete') { $id = sm_post_int('id'); if ($id <= 0) { $_SESSION['section_media_error'] = 'Invalid section media ID.'; header('Location: section_media.php'); exit; } try { $stmt = $pdo->prepare( "DELETE FROM section_media WHERE id = ?" ); $stmt->execute([$id]); $_SESSION['section_media_success'] = 'Section media deleted successfully.'; } catch (Throwable $e) { error_log( 'section_media delete error: ' . $e->getMessage() ); $_SESSION['section_media_error'] = 'Unable to delete section media.'; } header('Location: section_media.php'); exit; } } /* ========================================================= FILTERS ========================================================= */ $search = trim((string)($_GET['search'] ?? '')); $filterSection = isset($_GET['section_id']) ? (int)$_GET['section_id'] : 0; $filterRole = trim((string)($_GET['media_role'] ?? '')); $filterStatus = isset($_GET['status']) ? (string)$_GET['status'] : ''; $editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0; /* ========================================================= SECTIONS ========================================================= */ $sections = []; try { $stmt = $pdo->query( "SELECT ps.id, ps.page_id, ps.title, ps.section_type, ps.sort_order, p.title AS page_title, p.slug AS page_slug FROM page_sections ps LEFT JOIN pages p ON p.id = ps.page_id ORDER BY p.title ASC, ps.sort_order ASC, ps.id DESC" ); $sections = $stmt->fetchAll(); } catch (Throwable $e) { error_log( 'section_media sections error: ' . $e->getMessage() ); $sections = []; } /* ========================================================= MEDIA ROLES ========================================================= */ $mediaRoles = [ 'image' => 'Image', 'video' => 'Video', 'poster' => 'Poster', 'background' => 'Background', 'pdf' => 'PDF' ]; /* ========================================================= EXISTING MEDIA OPTIONS ========================================================= */ $mediaOptions = []; try { $stmt = $pdo->query( "SELECT id, original_name, file_name, file_type, mime_type, file_path FROM media WHERE status = 1 ORDER BY id DESC LIMIT 1000" ); $mediaOptions = $stmt->fetchAll(); } catch (Throwable $e) { error_log('section_media media options error: ' . $e->getMessage()); $mediaOptions = []; } /* ========================================================= EDIT RECORD ========================================================= */ $editItem = null; if ($editId > 0) { try { $stmt = $pdo->prepare( "SELECT * FROM section_media WHERE id = ? LIMIT 1" ); $stmt->execute([$editId]); $editItem = $stmt->fetch() ?: null; } catch (Throwable $e) { error_log( 'section_media edit error: ' . $e->getMessage() ); } } /* ========================================================= LIST ========================================================= */ $where = []; $params = []; if ($search !== '') { $where[] = "( sm.title LIKE ? OR sm.caption LIKE ? OR sm.alt_text LIKE ? OR sm.external_url LIKE ? OR sm.media_role LIKE ? OR CAST(sm.media_id AS CHAR) LIKE ? )"; $like = '%' . $search . '%'; $params[] = $like; $params[] = $like; $params[] = $like; $params[] = $like; $params[] = $like; $params[] = $like; } if ($filterSection > 0) { $where[] = "sm.section_id = ?"; $params[] = $filterSection; } if ($filterRole !== '') { $where[] = "sm.media_role = ?"; $params[] = $filterRole; } if ($filterStatus === '1' || $filterStatus === '0') { $where[] = "sm.status = ?"; $params[] = (int)$filterStatus; } $whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : ''; $items = []; try { $sql = " SELECT sm.*, m.original_name AS media_original_name, m.file_name AS media_file_name, m.file_path AS media_file_path, m.mime_type AS media_mime_type, ps.title AS section_title, ps.section_type, ps.page_id, p.title AS page_title, p.slug AS page_slug FROM section_media sm LEFT JOIN media m ON m.id = sm.media_id LEFT JOIN page_sections ps ON ps.id = sm.section_id LEFT JOIN pages p ON p.id = ps.page_id {$whereSql} ORDER BY p.title ASC, ps.sort_order ASC, sm.sort_order ASC, sm.id DESC LIMIT 500 "; $stmt = $pdo->prepare($sql); $stmt->execute($params); $items = $stmt->fetchAll(); } catch (Throwable $e) { error_log( 'section_media listing error: ' . $e->getMessage() ); $items = []; if ($error === '') { $error = 'Unable to load section media.'; } } /* ========================================================= STATS ========================================================= */ $totalMedia = 0; $activeMedia = 0; $inactiveMedia = 0; try { $stmt = $pdo->query( "SELECT COUNT(*) AS total, COALESCE(SUM(status = 1), 0) AS active, COALESCE(SUM(status = 0), 0) AS inactive FROM section_media" ); $stats = $stmt->fetch() ?: []; $totalMedia = (int)($stats['total'] ?? 0); $activeMedia = (int)($stats['active'] ?? 0); $inactiveMedia = (int)($stats['inactive'] ?? 0); } catch (Throwable $e) { // Safe fallback. } /* ========================================================= FORM ========================================================= */ $form = [ 'id' => '', 'section_id' => '', 'media_id' => '', 'media_role' => 'image', 'external_url' => '', 'title' => '', 'caption' => '', 'alt_text' => '', 'sort_order' => 0, 'status' => 1 ]; if ($editItem) { foreach ($form as $key => $value) { if (array_key_exists($key, $editItem)) { $form[$key] = $editItem[$key]; } } } $isEditing = !empty($form['id']); /* ========================================================= SIDEBAR ========================================================= */ require_once __DIR__ . '/sidebar.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" > <title>Section Media | Pure Chemical Admin</title> <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" > <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-soft: #ecfdf5; --text: #172033; --muted: #64748b; --border: #e5e7eb; --bg: #f6f8fb; --white: #fff; --success: #059669; --danger: #dc2626; --warning: #d97706; --sidebar-width: 285px; --radius: 18px; --shadow: 0 12px 40px rgba(15, 23, 42, .07); } * { box-sizing: border-box; } body { margin: 0; background: var(--bg); color: var(--text); font-family: Inter, sans-serif; font-size: 14px; } button, input, select, textarea { font: inherit; } a { text-decoration: none; color: inherit; } /* ========================================= MAIN ========================================= */ .sm-main { margin-left: var(--sidebar-width); min-height: 100vh; } /* ========================================= TOPBAR ========================================= */ .sm-topbar { position: sticky; top: 0; z-index: 70; min-height: 76px; padding: 0 28px; background: rgba(255, 255, 255, .94); backdrop-filter: blur(18px); border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; gap: 20px; } .sm-top-left { display: flex; align-items: center; gap: 14px; } .sm-mobile-btn { display: none; width: 42px; height: 42px; border: 1px solid var(--border); background: #fff; border-radius: 12px; cursor: pointer; } .sm-heading h1 { margin: 0; font-size: 20px; font-weight: 800; letter-spacing: -.4px; } .sm-heading p { margin: 4px 0 0; color: var(--muted); font-size: 12px; } .sm-top-badge { display: inline-flex; align-items: center; gap: 7px; padding: 9px 13px; border-radius: 999px; background: var(--primary-soft); color: var(--primary-dark); font-size: 12px; font-weight: 750; } /* ========================================= CONTAINER ========================================= */ .sm-container { max-width: 1600px; margin: 0 auto; padding: 28px; } /* ========================================= ALERT ========================================= */ .sm-alert { display: flex; gap: 11px; align-items: flex-start; padding: 14px 16px; margin-bottom: 20px; border-radius: 13px; border: 1px solid; } .sm-alert-success { color: #047857; background: #ecfdf5; border-color: #a7f3d0; } .sm-alert-danger { color: #b91c1c; background: #fef2f2; border-color: #fecaca; } /* ========================================= STATS ========================================= */ .sm-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; margin-bottom: 22px; } .sm-stat { background: var(--white); border: 1px solid var(--border); border-radius: var(--radius); padding: 20px; box-shadow: var(--shadow); } .sm-stat-icon { width: 42px; height: 42px; display: flex; align-items: center; justify-content: center; border-radius: 12px; background: var(--primary-soft); color: var(--primary); margin-bottom: 14px; } .sm-stat-value { font-size: 25px; font-weight: 800; } .sm-stat-label { margin-top: 6px; color: var(--muted); font-size: 11px; } /* ========================================= GRID ========================================= */ .sm-grid { display: grid; grid-template-columns: minmax(0, 1fr) 420px; gap: 22px; align-items: start; } .sm-card { background: #fff; border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; } .sm-card-header { padding: 19px 21px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; gap: 15px; } .sm-card-title { display: flex; align-items: center; gap: 11px; } .sm-title-icon { width: 38px; height: 38px; display: flex; align-items: center; justify-content: center; border-radius: 11px; background: var(--primary-soft); color: var(--primary); } .sm-card-title h2 { margin: 0; font-size: 15px; font-weight: 800; } .sm-card-title p { margin: 3px 0 0; color: var(--muted); font-size: 11px; } .sm-card-body { padding: 21px; } /* ========================================= FILTER ========================================= */ .sm-filters { padding: 17px 21px; border-bottom: 1px solid var(--border); background: #fafbfc; } .sm-filter-grid { display: grid; grid-template-columns: 1.6fr 1fr 1fr 120px auto; gap: 10px; } /* ========================================= INPUTS ========================================= */ .sm-field { margin-bottom: 15px; } .sm-field label { display: block; margin-bottom: 7px; color: #334155; font-size: 11px; font-weight: 750; } .sm-input, .sm-select, .sm-textarea { width: 100%; border: 1px solid #dbe1e8; background: #fff; color: var(--text); border-radius: 11px; outline: none; transition: .18s ease; } .sm-input, .sm-select { height: 43px; padding: 0 13px; } .sm-textarea { min-height: 110px; padding: 12px 13px; resize: vertical; line-height: 1.6; } .sm-textarea.large { min-height: 145px; } .sm-input:focus, .sm-select:focus, .sm-textarea:focus { border-color: rgba(15, 118, 110, .55); box-shadow: 0 0 0 4px rgba(15, 118, 110, .08); } .sm-help { margin-top: 5px; color: #94a3b8; font-size: 10px; line-height: 1.45; } /* ========================================= BUTTON ========================================= */ .sm-btn { min-height: 42px; padding: 0 15px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; border-radius: 11px; border: 1px solid transparent; font-size: 12px; font-weight: 750; cursor: pointer; transition: .18s ease; } .sm-btn:hover { transform: translateY(-1px); } .sm-btn-primary { background: var(--primary); color: #fff; box-shadow: 0 7px 18px rgba(15, 118, 110, .18); } .sm-btn-primary:hover { background: var(--primary-dark); } .sm-btn-light { background: #fff; color: #334155; border-color: var(--border); } /* ========================================= TABLE ========================================= */ .sm-table-wrap { overflow-x: auto; } .sm-table { width: 100%; min-width: 950px; border-collapse: collapse; } .sm-table th { padding: 12px 16px; background: #f8fafc; border-bottom: 1px solid var(--border); color: #64748b; font-size: 10px; text-transform: uppercase; letter-spacing: .5px; text-align: left; } .sm-table td { padding: 14px 16px; border-bottom: 1px solid #eef1f4; vertical-align: middle; font-size: 12px; } .sm-table tbody tr:hover { background: #fbfefd; } .sm-media-cell { display: flex; align-items: center; gap: 11px; } .sm-media-icon { width: 39px; height: 39px; flex: 0 0 auto; display: flex; align-items: center; justify-content: center; border-radius: 10px; background: var(--primary-soft); color: var(--primary); } .sm-media-title { font-weight: 750; } .sm-media-sub { margin-top: 3px; color: #94a3b8; font-size: 10px; max-width: 250px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .sm-section-name { font-weight: 700; } .sm-page-name { margin-top: 4px; color: #94a3b8; font-size: 10px; } .sm-role { display: inline-flex; padding: 5px 8px; border-radius: 7px; background: #f1f5f9; color: #475569; font-size: 10px; font-weight: 750; } .sm-id { display: inline-flex; min-width: 30px; height: 28px; align-items: center; justify-content: center; padding: 0 7px; background: #f8fafc; border: 1px solid var(--border); border-radius: 8px; color: #64748b; font-size: 10px; font-weight: 750; } .sm-status { display: inline-flex; align-items: center; gap: 6px; padding: 6px 9px; border-radius: 999px; font-size: 10px; font-weight: 750; } .sm-status::before { content: ""; width: 6px; height: 6px; border-radius: 50%; } .sm-active { color: #047857; background: #ecfdf5; } .sm-active::before { background: #10b981; } .sm-inactive { color: #b45309; background: #fffbeb; } .sm-inactive::before { background: #f59e0b; } .sm-actions { display: flex; align-items: center; justify-content: flex-end; gap: 6px; } .sm-icon-btn { width: 34px; height: 34px; display: inline-flex; align-items: center; justify-content: center; border: 1px solid var(--border); background: #fff; border-radius: 9px; color: #64748b; cursor: pointer; transition: .18s ease; } .sm-icon-btn:hover { color: var(--primary); background: var(--primary-soft); border-color: rgba(15, 118, 110, .25); } .sm-icon-btn.delete:hover { color: var(--danger); background: #fef2f2; border-color: #fecaca; } /* ========================================= FORM ========================================= */ .sm-form-card { position: sticky; top: 98px; } .sm-form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; } .sm-full { grid-column: 1 / -1; } .sm-edit-banner { display: flex; align-items: center; gap: 8px; margin-bottom: 18px; padding: 11px 13px; border-radius: 10px; background: #fffbeb; border: 1px solid #fde68a; color: #92400e; font-size: 11px; font-weight: 700; } .sm-toggle { padding: 13px 14px; border: 1px solid var(--border); background: #fafbfc; border-radius: 11px; display: flex; align-items: center; justify-content: space-between; } .sm-toggle strong { display: block; font-size: 12px; } .sm-toggle span.text { display: block; margin-top: 3px; color: var(--muted); font-size: 10px; } .sm-switch { position: relative; width: 42px; height: 23px; } .sm-switch input { opacity: 0; width: 0; height: 0; } .sm-slider { position: absolute; inset: 0; border-radius: 999px; background: #cbd5e1; cursor: pointer; transition: .2s; } .sm-slider::before { content: ""; position: absolute; width: 17px; height: 17px; left: 3px; top: 3px; background: #fff; border-radius: 50%; box-shadow: 0 1px 4px rgba(0,0,0,.2); transition: .2s; } .sm-switch input:checked + .sm-slider { background: var(--primary); } .sm-switch input:checked + .sm-slider::before { transform: translateX(19px); } .sm-form-actions { margin-top: 20px; padding-top: 18px; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; gap: 9px; } /* ========================================= EMPTY ========================================= */ .sm-empty { padding: 55px 25px; text-align: center; color: var(--muted); } .sm-empty-icon { width: 55px; height: 55px; margin: 0 auto 14px; display: flex; align-items: center; justify-content: center; border-radius: 16px; background: #f1f5f9; color: #94a3b8; font-size: 21px; } .sm-empty h3 { margin: 0 0 6px; color: #334155; font-size: 14px; } .sm-empty p { margin: 0; font-size: 11px; } /* ========================================= RESPONSIVE ========================================= */ @media (max-width: 1250px) { .sm-grid { grid-template-columns: 1fr; } .sm-form-card { position: static; } .sm-filter-grid { grid-template-columns: 1fr 1fr; } } @media (max-width: 991px) { .sm-main { margin-left: 0; } .sm-mobile-btn { display: inline-flex; align-items: center; justify-content: center; } .sm-container { padding: 20px; } .sm-stats { grid-template-columns: repeat(2, 1fr); } } @media (max-width: 650px) { .sm-topbar { padding: 0 15px; } .sm-top-badge { display: none; } .sm-container { padding: 15px; } .sm-stats { gap: 10px; } .sm-stat { padding: 15px; } .sm-stat-value { font-size: 21px; } .sm-filter-grid, .sm-form-grid { grid-template-columns: 1fr; } .sm-full { grid-column: auto; } .sm-card-header, .sm-card-body, .sm-filters { padding: 16px; } } </style> </head> <body> <div class="sm-main"> <!-- ================================================= TOPBAR ================================================== --> <header class="sm-topbar"> <div class="sm-top-left"> <button type="button" class="sm-mobile-btn" id="smMobileBtn" aria-label="Open sidebar" > <i class="fa-solid fa-bars"></i> </button> <div class="sm-heading"> <h1> Section Media </h1> <p> Manage media attached to page sections </p> </div> </div> <div class="sm-top-badge"> <i class="fa-solid fa-photo-film"></i> Section Media </div> </header> <main class="sm-container"> <!-- ================================================= ALERTS ================================================== --> <?php if ($success): ?> <div class="sm-alert sm-alert-success"> <i class="fa-solid fa-circle-check"></i> <div> <?= sm_e($success) ?> </div> </div> <?php endif; ?> <?php if ($error): ?> <div class="sm-alert sm-alert-danger"> <i class="fa-solid fa-circle-exclamation"></i> <div> <?= sm_e($error) ?> </div> </div> <?php endif; ?> <!-- ================================================= STATS ================================================== --> <section class="sm-stats"> <div class="sm-stat"> <div class="sm-stat-icon"> <i class="fa-solid fa-photo-film"></i> </div> <div class="sm-stat-value"> <?= number_format($totalMedia) ?> </div> <div class="sm-stat-label"> Total Section Media </div> </div> <div class="sm-stat"> <div class="sm-stat-icon"> <i class="fa-solid fa-circle-check"></i> </div> <div class="sm-stat-value"> <?= number_format($activeMedia) ?> </div> <div class="sm-stat-label"> Active Media </div> </div> <div class="sm-stat"> <div class="sm-stat-icon"> <i class="fa-solid fa-circle-pause"></i> </div> <div class="sm-stat-value"> <?= number_format($inactiveMedia) ?> </div> <div class="sm-stat-label"> Inactive Media </div> </div> <div class="sm-stat"> <div class="sm-stat-icon"> <i class="fa-solid fa-layer-group"></i> </div> <div class="sm-stat-value"> <?= number_format(count($sections)) ?> </div> <div class="sm-stat-label"> Available Sections </div> </div> </section> <!-- ================================================= MAIN GRID ================================================== --> <section class="sm-grid"> <!-- ================================================= LIST ================================================== --> <div class="sm-card"> <div class="sm-card-header"> <div class="sm-card-title"> <div class="sm-title-icon"> <i class="fa-solid fa-photo-film"></i> </div> <div> <h2> Section Media Library </h2> <p> Media assigned to page sections </p> </div> </div> </div> <!-- FILTERS --> <form method="get" class="sm-filters" > <div class="sm-filter-grid"> <input type="search" name="search" class="sm-input" placeholder="Search title, caption, URL, media ID..." value="<?= sm_e($search) ?>" > <select name="section_id" class="sm-select" > <option value=""> All Sections </option> <?php foreach ($sections as $section): ?> <option value="<?= (int)$section['id'] ?>" <?= $filterSection === (int)$section['id'] ? 'selected' : '' ?> > <?= sm_e( ($section['page_title'] ? $section['page_title'] . ' → ' : '' ) . ($section['title'] ?: 'Section #' . $section['id'] ) ) ?> </option> <?php endforeach; ?> </select> <select name="media_role" class="sm-select" > <option value=""> All Roles </option> <?php foreach ($mediaRoles as $roleKey => $roleName): ?> <option value="<?= sm_e($roleKey) ?>" <?= $filterRole === $roleKey ? 'selected' : '' ?> > <?= sm_e($roleName) ?> </option> <?php endforeach; ?> </select> <select name="status" class="sm-select" > <option value=""> Status </option> <option value="1" <?= $filterStatus === '1' ? 'selected' : '' ?> > Active </option> <option value="0" <?= $filterStatus === '0' ? 'selected' : '' ?> > Inactive </option> </select> <button type="submit" class="sm-btn sm-btn-primary" > <i class="fa-solid fa-filter"></i> Filter </button> </div> </form> <!-- TABLE --> <div class="sm-table-wrap"> <?php if (!$items): ?> <div class="sm-empty"> <div class="sm-empty-icon"> <i class="fa-regular fa-images"></i> </div> <h3> No section media found </h3> <p> Add your first section media using the form. </p> </div> <?php else: ?> <table class="sm-table"> <thead> <tr> <th> Media </th> <th> Section </th> <th> Role </th> <th> Media ID </th> <th> Order </th> <th> Status </th> <th style="text-align:right;"> Actions </th> </tr> </thead> <tbody> <?php foreach ($items as $item): ?> <?php $role = (string)( $item['media_role'] ?? 'image' ); $roleIcon = 'fa-image'; if ($role === 'video') { $roleIcon = 'fa-video'; } elseif ($role === 'poster') { $roleIcon = 'fa-clapperboard'; } elseif ($role === 'background') { $roleIcon = 'fa-panorama'; } elseif ($role === 'pdf') { $roleIcon = 'fa-file-pdf'; } ?> <tr> <!-- MEDIA --> <td> <div class="sm-media-cell"> <div class="sm-media-icon"> <i class="fa-solid <?= sm_e($roleIcon) ?>"></i> </div> <div> <div class="sm-media-title"> <?= sm_e( $item['title'] ?: ($item['media_original_name'] ?? '') ?: 'Media #' . $item['media_id'] ) ?> </div> <?php if (!empty($item['alt_text'])): ?> <div class="sm-media-sub"> <?= sm_e( $item['alt_text'] ) ?> </div> <?php elseif (!empty($item['external_url'])): ?> <div class="sm-media-sub"> <?= sm_e( $item['external_url'] ) ?> </div> <?php elseif (!empty($item['caption'])): ?> <div class="sm-media-sub"> <?= sm_e( $item['caption'] ) ?> </div> <?php endif; ?> </div> </div> </td> <!-- SECTION --> <td> <div class="sm-section-name"> <?= sm_e( $item['section_title'] ?: 'Section #' . $item['section_id'] ) ?> </div> <?php if (!empty($item['page_title'])): ?> <div class="sm-page-name"> <i class="fa-regular fa-file-lines"></i> <?= sm_e( $item['page_title'] ) ?> </div> <?php endif; ?> </td> <!-- ROLE --> <td> <span class="sm-role"> <?= sm_e( ucfirst($role) ) ?> </span> </td> <!-- MEDIA ID --> <td> <span class="sm-id"> #<?= (int)$item['media_id'] ?> </span> </td> <!-- ORDER --> <td> <span class="sm-id"> <?= (int)$item['sort_order'] ?> </span> </td> <!-- STATUS --> <td> <?php if ((int)$item['status'] === 1): ?> <span class="sm-status sm-active"> Active </span> <?php else: ?> <span class="sm-status sm-inactive"> Inactive </span> <?php endif; ?> </td> <!-- ACTIONS --> <td> <div class="sm-actions"> <a href="?edit=<?= (int)$item['id'] ?>" class="sm-icon-btn" title="Edit" > <i class="fa-solid fa-pen"></i> </a> <form method="post" style="display:inline;" onsubmit="return confirm('Delete this section media record? This action cannot be undone.');" > <?= sm_csrf_field() ?> <input type="hidden" name="action" value="delete" > <input type="hidden" name="id" value="<?= (int)$item['id'] ?>" > <button type="submit" class="sm-icon-btn delete" title="Delete" > <i class="fa-solid fa-trash"></i> </button> </form> </div> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php endif; ?> </div> </div> <!-- ================================================= FORM ================================================== --> <div class="sm-card sm-form-card"> <div class="sm-card-header"> <div class="sm-card-title"> <div class="sm-title-icon"> <i class="fa-solid <?= $isEditing ? 'fa-pen' : 'fa-plus' ?>"></i> </div> <div> <h2> <?= $isEditing ? 'Edit Section Media' : 'Add Section Media' ?> </h2> <p> <?= $isEditing ? 'Update existing media mapping' : 'Attach media to a section' ?> </p> </div> </div> </div> <div class="sm-card-body"> <?php if ($isEditing): ?> <div class="sm-edit-banner"> <i class="fa-solid fa-pen-to-square"></i> Editing section media #<?= (int)$form['id'] ?> </div> <?php endif; ?> <form method="post" enctype="multipart/form-data" autocomplete="off" > <?= sm_csrf_field() ?> <input type="hidden" name="action" value="save" > <?php if ($isEditing): ?> <input type="hidden" name="id" value="<?= (int)$form['id'] ?>" > <?php endif; ?> <div class="sm-form-grid"> <!-- SECTION --> <div class="sm-field sm-full"> <label> Section <span style="color:#dc2626;">*</span> </label> <select name="section_id" class="sm-select" required > <option value=""> Select section </option> <?php foreach ($sections as $section): ?> <option value="<?= (int)$section['id'] ?>" <?= (int)$form['section_id'] === (int)$section['id'] ? 'selected' : '' ?> > <?= sm_e( ($section['page_title'] ? $section['page_title'] . ' → ' : '' ) . ($section['title'] ?: 'Section #' . $section['id'] ) . ($section['section_type'] ? ' [' . $section['section_type'] . ']' : '' ) ) ?> </option> <?php endforeach; ?> </select> <div class="sm-help"> Select the existing page section for this media. </div> </div> <!-- EXISTING MEDIA OR FILE UPLOAD --> <div class="sm-field sm-full"> <label>Choose Existing Media</label> <select name="media_id" class="sm-select" id="smMediaSelect"> <option value="">Select from Media Library (or upload below)</option> <?php foreach ($mediaOptions as $mediaOption): ?> <option value="<?= (int)$mediaOption['id'] ?>" <?= (int)$form['media_id'] === (int)$mediaOption['id'] ? 'selected' : '' ?>> #<?= (int)$mediaOption['id'] ?> — <?= sm_e($mediaOption['original_name'] ?: $mediaOption['file_name']) ?> (<?= sm_e($mediaOption['file_type']) ?>) </option> <?php endforeach; ?> </select> <div class="sm-help">Select an existing file from the media library, or upload a new one below.</div> </div> <div class="sm-field sm-full"> <label>Upload New File</label> <input type="file" name="media_upload" class="sm-input" accept=".jpg,.jpeg,.png,.gif,.webp,.mp4,.webm,.pdf"> <div class="sm-help">JPG, PNG, GIF, WEBP, MP4, WEBM or PDF; maximum 20 MB. Uploaded files are saved to the existing media table and linked to this section.</div> </div> <!-- ROLE --> <div class="sm-field"> <label> Media Role <span style="color:#dc2626;">*</span> </label> <select name="media_role" class="sm-select" required > <?php foreach ($mediaRoles as $roleKey => $roleName): ?> <option value="<?= sm_e($roleKey) ?>" <?= $form['media_role'] === $roleKey ? 'selected' : '' ?> > <?= sm_e($roleName) ?> </option> <?php endforeach; ?> </select> </div> <!-- TITLE --> <div class="sm-field sm-full"> <label> Title </label> <input type="text" name="title" class="sm-input" maxlength="255" placeholder="Media title" value="<?= sm_e( $form['title'] ) ?>" > </div> <!-- EXTERNAL URL --> <div class="sm-field sm-full"> <label> External URL </label> <input type="text" name="external_url" class="sm-input" maxlength="1000" placeholder="https://example.com/video.mp4" value="<?= sm_e( $form['external_url'] ) ?>" > <div class="sm-help"> Optional external media source. Leave empty when using an existing media record only. </div> </div> <!-- CAPTION --> <div class="sm-field sm-full"> <label> Caption </label> <textarea name="caption" class="sm-textarea" placeholder="Optional media caption..." ><?= sm_e( $form['caption'] ) ?></textarea> </div> <!-- ALT TEXT --> <div class="sm-field sm-full"> <label> Alt Text </label> <input type="text" name="alt_text" class="sm-input" maxlength="255" placeholder="Describe the media for accessibility" value="<?= sm_e( $form['alt_text'] ) ?>" > <div class="sm-help"> Recommended for image-based media. </div> </div> <!-- SORT --> <div class="sm-field"> <label> Sort Order </label> <input type="number" name="sort_order" class="sm-input" min="0" value="<?= (int)$form['sort_order'] ?>" > </div> <!-- STATUS --> <div class="sm-field"> <label> Visibility </label> <div class="sm-toggle"> <div> <strong> Publish Media </strong> <span class="text"> Active media can appear on frontend. </span> </div> <label class="sm-switch"> <input type="checkbox" name="status" value="1" <?= (int)$form['status'] === 1 ? 'checked' : '' ?> > <span class="sm-slider"></span> </label> </div> </div> </div> <!-- FORM ACTIONS --> <div class="sm-form-actions"> <?php if ($isEditing): ?> <a href="section_media.php" class="sm-btn sm-btn-light" > <i class="fa-solid fa-xmark"></i> Cancel </a> <?php else: ?> <button type="reset" class="sm-btn sm-btn-light" > <i class="fa-solid fa-rotate-left"></i> Reset </button> <?php endif; ?> <button type="submit" class="sm-btn sm-btn-primary" > <i class="fa-solid <?= $isEditing ? 'fa-floppy-disk' : 'fa-plus' ?>"></i> <?= $isEditing ? 'Update Media' : 'Add Media' ?> </button> </div> </form> </div> </div> </section> </main> </div> <script> (function () { const uploadInput = document.querySelector('input[name="media_upload"]'); const mediaSelect = document.getElementById('smMediaSelect'); if (uploadInput && mediaSelect) { uploadInput.addEventListener('change', function () { if (uploadInput.files && uploadInput.files.length) mediaSelect.value = ''; }); mediaSelect.addEventListener('change', function () { if (mediaSelect.value) uploadInput.value = ''; }); } const btn = document.getElementById('smMobileBtn'); const sidebar = document.getElementById('pcSidebar'); if (!btn || !sidebar) { return; } btn.addEventListener('click', function () { sidebar.classList.toggle( 'pc-sidebar-open' ); document.body.classList.toggle( 'pc-sidebar-mobile-open' ); }); document.addEventListener('click', function (event) { if ( window.innerWidth <= 991 && sidebar.classList.contains('pc-sidebar-open') && !sidebar.contains(event.target) && !btn.contains(event.target) ) { sidebar.classList.remove( 'pc-sidebar-open' ); document.body.classList.remove( 'pc-sidebar-mobile-open' ); } }); })(); </script> </body> </html>
Save
Cancel