📁 File Manager
Editing:
/home/wvl7mof7402e/public_html/chem/admin/brand_media.php
<?php /** * Pure Chemical Admin * Brand Media Management * * Existing tables used: * - brands * - brand_media * - media * * No new table is created. */ 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(); } /* ========================================================= COMMON 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('brand_media_csrf_field')) { function brand_media_csrf_field() { if (empty($_SESSION['brand_media_csrf'])) { $_SESSION['brand_media_csrf'] = bin2hex(random_bytes(32)); } return '<input type="hidden" name="csrf_token" value="' . e($_SESSION['brand_media_csrf']) . '">'; } } if (!function_exists('brand_media_verify_csrf')) { function brand_media_verify_csrf() { $token = $_POST['csrf_token'] ?? ''; if ( empty($_SESSION['brand_media_csrf']) || empty($token) ) { return false; } return hash_equals( $_SESSION['brand_media_csrf'], $token ); } } /* ========================================================= FLASH ========================================================= */ $flash = $_SESSION['brand_media_flash'] ?? null; unset($_SESSION['brand_media_flash']); /* ========================================================= MEDIA ROLE ENUM ========================================================= */ $mediaRoleOptions = []; try { $roleStmt = $pdo->query( "SHOW COLUMNS FROM brand_media LIKE 'media_role'" ); $roleColumn = $roleStmt->fetch(); if ( $roleColumn && !empty($roleColumn['Type']) ) { if ( preg_match( "/^enum\((.*)\)$/i", $roleColumn['Type'], $matches ) ) { $values = str_getcsv( $matches[1], ',', "'" ); foreach ($values as $value) { $value = str_replace( "''", "'", $value ); if ($value !== '') { $mediaRoleOptions[] = $value; } } } } } catch (Throwable $e) { $mediaRoleOptions = []; } /* * Fallback only if database enum metadata * could not be read. */ if (!$mediaRoleOptions) { $mediaRoleOptions = [ 'logo', 'image', 'gallery', 'video', 'document' ]; } /* Existing media library records for the media selector. */ $availableMedia = []; try { $mediaStmt = $pdo->query(" SELECT id, original_name, file_name, file_path, mime_type, file_type FROM media WHERE status = 1 ORDER BY id DESC "); $availableMedia = $mediaStmt->fetchAll(PDO::FETCH_ASSOC); } catch (Throwable $e) { $availableMedia = []; } /* ========================================================= GET EDIT ID ========================================================= */ $editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0; /* ========================================================= FORM DEFAULTS ========================================================= */ $form = [ 'id' => 0, 'brand_id' => '', 'media_id' => '', 'media_role' => $mediaRoleOptions[0] ?? 'logo', 'sort_order' => '0' ]; $errors = []; /* ========================================================= LOAD EDIT RECORD ========================================================= */ if ($editId > 0) { try { $editStmt = $pdo->prepare(" SELECT id, brand_id, media_id, media_role, sort_order FROM brand_media WHERE id = ? LIMIT 1 "); $editStmt->execute([$editId]); $editRecord = $editStmt->fetch(); if ($editRecord) { $form = [ 'id' => (int)$editRecord['id'], 'brand_id' => (string)$editRecord['brand_id'], 'media_id' => (string)$editRecord['media_id'], 'media_role' => (string)$editRecord['media_role'], 'sort_order' => (string)$editRecord['sort_order'] ]; } else { $editId = 0; $flash = [ 'type' => 'danger', 'message' => 'Brand media record not found.' ]; } } catch (Throwable $e) { $editId = 0; $flash = [ 'type' => 'danger', 'message' => 'Unable to load brand media record.' ]; } } /* ========================================================= POST ACTION ========================================================= */ if ($_SERVER['REQUEST_METHOD'] === 'POST') { $action = $_POST['action'] ?? ''; /* ===================================================== SAVE ===================================================== */ if ($action === 'save') { if (!brand_media_verify_csrf()) { $errors[] = 'Security verification failed. Please refresh the page and try again.'; } /* --------------------------------------------- FORM DATA --------------------------------------------- */ $form['id'] = isset($_POST['id']) ? (int)$_POST['id'] : 0; $form['brand_id'] = isset($_POST['brand_id']) ? (string)(int)$_POST['brand_id'] : ''; $form['media_id'] = isset($_POST['media_id']) ? (string)(int)$_POST['media_id'] : ''; $form['media_role'] = trim($_POST['media_role'] ?? ''); $form['sort_order'] = (string)max( 0, (int)($_POST['sort_order'] ?? 0) ); /* * Optional upload: create a real media row first, then use its * generated ID in brand_media.media_id. */ if ( empty($errors) && isset($_FILES['media_file']) && is_array($_FILES['media_file']) && (int)($_FILES['media_file']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE ) { $upload = $_FILES['media_file']; $uploadError = (int)($upload['error'] ?? UPLOAD_ERR_NO_FILE); if ($uploadError !== UPLOAD_ERR_OK) { $errors[] = 'File upload failed. Please select the file again.'; } elseif (!is_uploaded_file($upload['tmp_name'] ?? '')) { $errors[] = 'Invalid uploaded file.'; } elseif ((int)($upload['size'] ?? 0) > 20 * 1024 * 1024) { $errors[] = 'File size must be 20 MB or less.'; } else { $originalName = basename((string)$upload['name']); $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION)); $finfo = new finfo(FILEINFO_MIME_TYPE); $mimeType = (string)$finfo->file($upload['tmp_name']); $allowedMimeExtensions = [ 'image/jpeg' => ['jpg', 'jpeg'], 'image/png' => ['png'], 'image/gif' => ['gif'], 'image/webp' => ['webp'], 'image/svg+xml' => ['svg'], 'image/avif' => ['avif'], 'video/mp4' => ['mp4'], 'video/webm' => ['webm'], 'video/quicktime' => ['mov'], 'audio/mpeg' => ['mp3'], 'audio/wav' => ['wav'], 'audio/ogg' => ['ogg'], 'application/pdf' => ['pdf'], 'text/plain' => ['txt'], 'application/msword' => ['doc'], 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => ['docx'], 'application/vnd.ms-excel' => ['xls'], 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => ['xlsx'], 'application/vnd.ms-powerpoint' => ['ppt'], 'application/vnd.openxmlformats-officedocument.presentationml.presentation' => ['pptx'] ]; if ( !isset($allowedMimeExtensions[$mimeType]) || !in_array($extension, $allowedMimeExtensions[$mimeType], true) ) { $errors[] = 'Unsupported file type. Upload an image, video, audio, PDF, or supported document.'; } else { $fileType = 'document'; if (strpos($mimeType, 'image/') === 0) { $fileType = 'image'; } elseif (strpos($mimeType, 'video/') === 0) { $fileType = 'video'; } elseif (strpos($mimeType, 'audio/') === 0) { $fileType = 'audio'; } elseif ($mimeType === 'application/pdf') { $fileType = 'pdf'; } $uploadDirectory = __DIR__ . '/uploads/media'; if (!is_dir($uploadDirectory) && !mkdir($uploadDirectory, 0755, true) && !is_dir($uploadDirectory)) { $errors[] = 'Unable to create uploads/media directory. Check folder permissions.'; } elseif (!is_writable($uploadDirectory)) { $errors[] = 'The uploads/media directory is not writable.'; } else { $safeBase = bin2hex(random_bytes(16)); $storedName = $safeBase . '.' . $extension; $absolutePath = $uploadDirectory . '/' . $storedName; $relativePath = 'uploads/media/' . $storedName; if (!move_uploaded_file($upload['tmp_name'], $absolutePath)) { $errors[] = 'Unable to move uploaded file to uploads/media.'; } else { try { $mediaInsert = $pdo->prepare(" INSERT INTO media (original_name, file_name, file_path, mime_type, file_type, extension, file_size, status) VALUES (:original_name, :file_name, :file_path, :mime_type, :file_type, :extension, :file_size, 1) "); $mediaInsert->execute([ ':original_name' => $originalName, ':file_name' => $storedName, ':file_path' => $relativePath, ':mime_type' => $mimeType, ':file_type' => $fileType, ':extension' => $extension, ':file_size' => (int)$upload['size'] ]); $form['media_id'] = (string)$pdo->lastInsertId(); } catch (Throwable $uploadDbError) { @unlink($absolutePath); error_log('Brand media upload database error: ' . $uploadDbError->getMessage()); $errors[] = 'The file was uploaded but could not be registered in the media table. Check the media.file_type ENUM and required columns.'; } } } } } } /* ================================================= VALIDATION ================================================= */ $brandId = (int)$form['brand_id']; $mediaId = (int)$form['media_id']; /* --------------------------------------------- Brand --------------------------------------------- */ if ($brandId <= 0) { $errors[] = 'Please select a valid brand.'; } else { try { $brandCheck = $pdo->prepare(" SELECT id FROM brands WHERE id = ? LIMIT 1 "); $brandCheck->execute([ $brandId ]); if (!$brandCheck->fetch()) { $errors[] = 'Selected brand does not exist.'; } } catch (Throwable $e) { $errors[] = 'Unable to validate selected brand.'; } } /* --------------------------------------------- Media --------------------------------------------- */ if ($mediaId <= 0) { $errors[] = 'Please select an existing media record or upload a new file.'; } else { try { $mediaCheck = $pdo->prepare(" SELECT id FROM media WHERE id = ? LIMIT 1 "); $mediaCheck->execute([ $mediaId ]); if (!$mediaCheck->fetch()) { $errors[] = 'Selected Media ID does not exist in the media table.'; } } catch (Throwable $e) { $errors[] = 'Unable to validate Media ID.'; } } /* --------------------------------------------- Media role --------------------------------------------- */ if ( !in_array( $form['media_role'], $mediaRoleOptions, true ) ) { $errors[] = 'Invalid media role selected.'; } /* ================================================= DUPLICATE CHECK ================================================= */ if (!$errors) { try { if ($form['id'] > 0) { $duplicateStmt = $pdo->prepare(" SELECT id FROM brand_media WHERE brand_id = ? AND media_id = ? AND media_role = ? AND id <> ? LIMIT 1 "); $duplicateStmt->execute([ $brandId, $mediaId, $form['media_role'], $form['id'] ]); } else { $duplicateStmt = $pdo->prepare(" SELECT id FROM brand_media WHERE brand_id = ? AND media_id = ? AND media_role = ? LIMIT 1 "); $duplicateStmt->execute([ $brandId, $mediaId, $form['media_role'] ]); } if ($duplicateStmt->fetch()) { $errors[] = 'This media is already assigned to this brand with the same role.'; } } catch (Throwable $e) { $errors[] = 'Unable to check duplicate media assignment.'; } } /* ================================================= INSERT / UPDATE ================================================= */ if (!$errors) { try { if ($form['id'] > 0) { $update = $pdo->prepare(" UPDATE brand_media SET brand_id = :brand_id, media_id = :media_id, media_role = :media_role, sort_order = :sort_order WHERE id = :id LIMIT 1 "); $update->bindValue( ':brand_id', $brandId, PDO::PARAM_INT ); $update->bindValue( ':media_id', $mediaId, PDO::PARAM_INT ); $update->bindValue( ':media_role', $form['media_role'], PDO::PARAM_STR ); $update->bindValue( ':sort_order', (int)$form['sort_order'], PDO::PARAM_INT ); $update->bindValue( ':id', $form['id'], PDO::PARAM_INT ); $update->execute(); $_SESSION['brand_media_flash'] = [ 'type' => 'success', 'message' => 'Brand media updated successfully.' ]; } else { $insert = $pdo->prepare(" INSERT INTO brand_media ( brand_id, media_id, media_role, sort_order ) VALUES ( :brand_id, :media_id, :media_role, :sort_order ) "); $insert->bindValue( ':brand_id', $brandId, PDO::PARAM_INT ); $insert->bindValue( ':media_id', $mediaId, PDO::PARAM_INT ); $insert->bindValue( ':media_role', $form['media_role'], PDO::PARAM_STR ); $insert->bindValue( ':sort_order', (int)$form['sort_order'], PDO::PARAM_INT ); $insert->execute(); $_SESSION['brand_media_flash'] = [ 'type' => 'success', 'message' => 'Brand media added successfully.' ]; } $redirectUrl = 'brand_media.php'; if ($brandId > 0) { $redirectUrl .= '?brand_id=' . $brandId; } header( 'Location: ' . $redirectUrl ); exit; } catch (PDOException $e) { error_log( 'Brand Media Save Error: ' . $e->getMessage() ); $errors[] = 'Unable to save brand media. Please try again.'; } } } /* ===================================================== DELETE ===================================================== */ if ($action === 'delete') { if (!brand_media_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 brand media record.'; } else { try { $delete = $pdo->prepare(" DELETE FROM brand_media WHERE id = ? LIMIT 1 "); $delete->execute([ $deleteId ]); $_SESSION['brand_media_flash'] = [ 'type' => 'success', 'message' => 'Brand media deleted successfully.' ]; header( 'Location: brand_media.php' ); exit; } catch (PDOException $e) { error_log( 'Brand Media Delete Error: ' . $e->getMessage() ); $errors[] = 'Unable to delete brand media.'; } } } } } /* ========================================================= LOAD BRANDS ========================================================= */ $brands = []; try { $brandStmt = $pdo->query(" SELECT id, parent_id, name, slug, brand_type, status, featured FROM brands ORDER BY sort_order ASC, name ASC "); $brands = $brandStmt->fetchAll(); } catch (Throwable $e) { $brands = []; } /* ========================================================= GET FILTERS ========================================================= */ $search = trim($_GET['q'] ?? ''); $filterBrandId = isset($_GET['brand_id']) ? (int)$_GET['brand_id'] : 0; $filterRole = trim($_GET['role'] ?? ''); $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1; $perPage = 15; /* ========================================================= BUILD WHERE ========================================================= */ $where = []; $params = []; if ($search !== '') { $where[] = " ( b.name LIKE :search1 OR b.slug LIKE :search2 OR bm.media_role LIKE :search3 OR m.original_name LIKE :search4 OR m.file_name LIKE :search5 ) "; $searchValue = '%' . $search . '%'; $params[':search1'] = $searchValue; $params[':search2'] = $searchValue; $params[':search3'] = $searchValue; $params[':search4'] = $searchValue; $params[':search5'] = $searchValue; } if ($filterBrandId > 0) { $where[] = 'bm.brand_id = :filter_brand_id'; $params[':filter_brand_id'] = $filterBrandId; } if ( $filterRole !== '' && in_array( $filterRole, $mediaRoleOptions, true ) ) { $where[] = 'bm.media_role = :filter_role'; $params[':filter_role'] = $filterRole; } $whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : ''; /* ========================================================= TOTAL RECORDS ========================================================= */ $totalRecords = 0; try { $countStmt = $pdo->prepare(" SELECT COUNT(*) FROM brand_media bm INNER JOIN brands b ON b.id = bm.brand_id LEFT JOIN media m ON m.id = bm.media_id $whereSql "); foreach ($params as $key => $value) { $countStmt->bindValue( $key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR ); } $countStmt->execute(); $totalRecords = (int)$countStmt->fetchColumn(); } catch (Throwable $e) { $totalRecords = 0; } /* ========================================================= PAGINATION ========================================================= */ $totalPages = max( 1, (int)ceil( $totalRecords / $perPage ) ); if ($page > $totalPages) { $page = $totalPages; } $offset = ($page - 1) * $perPage; /* ========================================================= LOAD MEDIA RECORDS ========================================================= */ $mediaRows = []; try { $listStmt = $pdo->prepare(" SELECT bm.id, bm.brand_id, bm.media_id, bm.media_role, bm.sort_order, 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, m.file_type AS media_file_type, b.name AS brand_name, b.slug AS brand_slug, b.brand_type AS brand_type, b.status AS brand_status FROM brand_media bm INNER JOIN brands b ON b.id = bm.brand_id LEFT JOIN media m ON m.id = bm.media_id $whereSql ORDER BY b.name ASC, bm.sort_order ASC, bm.id DESC LIMIT :limit OFFSET :offset "); foreach ($params as $key => $value) { $listStmt->bindValue( $key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR ); } $listStmt->bindValue( ':limit', $perPage, PDO::PARAM_INT ); $listStmt->bindValue( ':offset', $offset, PDO::PARAM_INT ); $listStmt->execute(); $mediaRows = $listStmt->fetchAll(); } catch (Throwable $e) { $mediaRows = []; } /* ========================================================= STATS ========================================================= */ $stats = [ 'total' => 0, 'logos' => 0, 'images' => 0, 'galleries' => 0 ]; try { $statsStmt = $pdo->query(" SELECT COUNT(*) AS total, SUM(media_role = 'logo') AS logos, SUM(media_role = 'image') AS images, SUM(media_role = 'gallery') AS galleries FROM brand_media "); $statsRow = $statsStmt->fetch(); if ($statsRow) { $stats['total'] = (int)$statsRow['total']; $stats['logos'] = (int)$statsRow['logos']; $stats['images'] = (int)$statsRow['images']; $stats['galleries'] = (int)$statsRow['galleries']; } } catch (Throwable $e) { /* Keep defaults */ } /* ========================================================= ADMIN ========================================================= */ $adminName = $_SESSION['ADMIN_NAME'] ?? $_SESSION['admin_name'] ?? $_SESSION['name'] ?? 'Administrator'; $adminRole = $_SESSION['ADMIN_ROLE'] ?? $_SESSION['admin_role'] ?? 'Administrator'; /* ========================================================= PAGINATION URL ========================================================= */ function brand_media_page_url( $page, $search, $brandId, $role ) { $query = [ 'page' => $page ]; if ($search !== '') { $query['q'] = $search; } if ($brandId > 0) { $query['brand_id'] = $brandId; } if ($role !== '') { $query['role'] = $role; } return 'brand_media.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>Brand Media | Pure Chemical Admin</title> <meta name="robots" content="noindex,nofollow" > <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 { --pc-primary: #0f766e; --pc-primary-dark: #115e59; --pc-primary-light: #14b8a6; --pc-bg: #f5f7fb; --pc-card: #ffffff; --pc-text: #172033; --pc-muted: #6b7280; --pc-border: #e5e7eb; --pc-success: #15803d; --pc-danger: #dc2626; --pc-warning: #d97706; --pc-shadow: 0 10px 35px rgba(15, 23, 42, .07); --pc-radius: 18px; } * { box-sizing: border-box; } html { scroll-behavior: smooth; } body { margin: 0; padding: 0; background: var(--pc-bg); color: var(--pc-text); font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; -webkit-font-smoothing: antialiased; } a { text-decoration: none; } button, input, select { font-family: inherit; } /* ===================================================== PAGE ===================================================== */ .pc-page { margin-left: 280px; min-height: 100vh; } /* ===================================================== TOPBAR ===================================================== */ .pc-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,.88); 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: 14px; min-width: 0; } .page-icon { width: 44px; height: 44px; display: flex; align-items: center; justify-content: center; flex: 0 0 44px; color: #fff; background: linear-gradient( 135deg, var(--pc-primary), var(--pc-primary-light) ); border-radius: 13px; box-shadow: 0 8px 20px rgba(15,118,110,.22); } .page-heading h1 { margin: 0; font-size: 17px; font-weight: 800; letter-spacing: -.02em; } .breadcrumb { display: flex; align-items: center; gap: 7px; margin-top: 4px; color: var(--pc-muted); font-size: 11px; font-weight: 500; } .breadcrumb a { color: var(--pc-primary); } .topbar-right { display: flex; align-items: center; gap: 12px; } .admin-pill { display: flex; align-items: center; gap: 10px; padding: 7px 12px 7px 7px; background: #fff; border: 1px solid var(--pc-border); border-radius: 14px; } .admin-avatar { width: 34px; height: 34px; display: flex; align-items: center; justify-content: center; color: #fff; background: linear-gradient( 135deg, var(--pc-primary), var(--pc-primary-light) ); border-radius: 10px; font-size: 13px; font-weight: 800; } .admin-info strong { display: block; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; } .admin-info span { display: block; margin-top: 2px; color: var(--pc-muted); font-size: 10px; } /* ===================================================== CONTENT ===================================================== */ .pc-content { max-width: 1550px; margin: 0 auto; padding: 30px; } .content-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; margin-bottom: 24px; } .content-title h2 { margin: 0; font-size: 27px; font-weight: 800; letter-spacing: -.04em; } .content-title p { margin: 8px 0 0; color: var(--pc-muted); font-size: 13px; line-height: 1.6; } /* ===================================================== BUTTON ===================================================== */ .btn { min-height: 43px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; padding: 0 15px; border-radius: 11px; border: 1px solid transparent; cursor: pointer; font-size: 12px; font-weight: 700; transition: .18s ease; } .btn:hover { transform: translateY(-1px); } .btn-primary { color: #fff; background: linear-gradient( 135deg, var(--pc-primary), var(--pc-primary-light) ); box-shadow: 0 8px 18px rgba(15,118,110,.18); } .btn-light { color: var(--pc-text); background: #fff; border-color: var(--pc-border); } .btn-danger { color: #b91c1c; background: #fff; border-color: #fecaca; } /* ===================================================== FLASH ===================================================== */ .alert { display: flex; align-items: flex-start; gap: 11px; padding: 14px 16px; margin-bottom: 20px; border-radius: 13px; font-size: 12px; 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-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 15px; margin-bottom: 22px; } .stat-card { display: flex; align-items: center; gap: 13px; padding: 18px; background: #fff; border: 1px solid var(--pc-border); border-radius: 16px; box-shadow: 0 7px 25px rgba(15,23,42,.045); } .stat-icon { width: 43px; height: 43px; display: flex; align-items: center; justify-content: center; flex: 0 0 43px; color: var(--pc-primary); background: #ecfdf5; border-radius: 12px; } .stat-card:nth-child(2) .stat-icon { color: #7c3aed; background: #f5f3ff; } .stat-card:nth-child(3) .stat-icon { color: #2563eb; background: #eff6ff; } .stat-card:nth-child(4) .stat-icon { color: #d97706; background: #fffbeb; } .stat-value { display: block; font-size: 21px; font-weight: 800; letter-spacing: -.03em; } .stat-label { display: block; margin-top: 3px; color: var(--pc-muted); font-size: 10px; font-weight: 600; } /* ===================================================== MAIN GRID ===================================================== */ .main-grid { display: grid; grid-template-columns: minmax(340px, .82fr) minmax(0, 1.8fr); gap: 22px; align-items: start; } .card { background: #fff; border: 1px solid rgba(226,232,240,.95); border-radius: var(--pc-radius); box-shadow: var(--pc-shadow); overflow: hidden; } .card-header { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 20px 22px; border-bottom: 1px solid var(--pc-border); } .card-header h3 { margin: 0; font-size: 15px; font-weight: 800; } .card-header p { margin: 5px 0 0; color: var(--pc-muted); font-size: 10px; } .card-body { padding: 22px; } /* ===================================================== FORM ===================================================== */ .form-group { margin-bottom: 17px; } .form-group:last-child { margin-bottom: 0; } .form-label { display: block; margin-bottom: 7px; color: #374151; font-size: 11px; font-weight: 800; } .required { color: #dc2626; } .form-control, .form-select { width: 100%; height: 45px; padding: 0 12px; color: var(--pc-text); background: #fff; border: 1px solid #dfe4ea; border-radius: 10px; outline: none; font-size: 12px; transition: .18s ease; } input[type="file"].form-control { width: 100%; min-height: 45px; height: auto; padding: 10px 12px; background: #fff; } .form-control:focus, .form-select:focus { border-color: var(--pc-primary); box-shadow: 0 0 0 4px rgba(15,118,110,.08); } .form-help { margin-top: 6px; 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: 12px; pointer-events: none; } .input-wrap .form-control { padding-left: 37px; } .form-actions { display: flex; gap: 9px; margin-top: 20px; } .form-actions .btn { flex: 1; } /* ===================================================== TABLE TOOLBAR (FIXED CUT/OVERFLOW ISSUE) ===================================================== */ .toolbar { display: grid; grid-template-columns: minmax(140px, 1.2fr) minmax(120px, 1fr) minmax(120px, 1fr) auto; gap: 8px; margin-bottom: 17px; align-items: center; } .toolbar .btn { height: 45px; white-space: nowrap; } /* ===================================================== TABLE ===================================================== */ .table-wrap { width: 100%; overflow-x: auto; } table { width: 100%; border-collapse: collapse; min-width: 800px; } thead th { padding: 12px 14px; text-align: left; color: #64748b; background: #f8fafc; border-bottom: 1px solid var(--pc-border); font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .055em; } tbody td { padding: 14px; border-bottom: 1px solid #edf0f3; vertical-align: middle; font-size: 11px; } tbody tr { transition: background .15s ease; } tbody tr:hover { background: #fbfdfd; } .record-id { color: #94a3b8; font-size: 10px; font-weight: 700; } .brand-name { color: #172033; font-size: 12px; font-weight: 800; } .brand-slug { margin-top: 3px; color: #94a3b8; font-size: 9px; } .media-id { display: inline-flex; align-items: center; gap: 5px; padding: 6px 9px; color: #334155; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 10px; font-weight: 800; } .role-badge { display: inline-flex; align-items: center; padding: 6px 9px; border-radius: 8px; color: #0f766e; background: #ecfdf5; border: 1px solid #a7f3d0; font-size: 9px; font-weight: 800; text-transform: capitalize; } .order-badge { display: inline-flex; min-width: 28px; justify-content: center; padding: 5px 7px; color: #475569; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 7px; font-size: 9px; font-weight: 800; } .status-dot { display: inline-flex; align-items: center; gap: 5px; color: var(--pc-success); font-size: 9px; font-weight: 700; } .status-dot::before { content: ""; width: 6px; height: 6px; background: #22c55e; border-radius: 50%; } .action-group { display: flex; gap: 6px; } .icon-btn { width: 32px; height: 32px; display: inline-flex; align-items: center; justify-content: center; border-radius: 9px; border: 1px solid var(--pc-border); background: #fff; cursor: pointer; font-size: 11px; transition: .17s ease; } .icon-btn.edit { color: var(--pc-primary); } .icon-btn.edit:hover { background: var(--pc-primary); color: #fff; border-color: var(--pc-primary); } .icon-btn.delete { color: #dc2626; } .icon-btn.delete:hover { color: #fff; background: #dc2626; border-color: #dc2626; } /* ===================================================== EMPTY ===================================================== */ .empty-state { padding: 55px 20px; text-align: center; } .empty-icon { width: 58px; height: 58px; display: flex; align-items: center; justify-content: center; margin: 0 auto 14px; color: var(--pc-primary); background: #ecfdf5; border-radius: 16px; font-size: 21px; } .empty-state h4 { margin: 0; font-size: 14px; font-weight: 800; } .empty-state p { max-width: 420px; margin: 7px auto 0; color: var(--pc-muted); font-size: 11px; line-height: 1.6; } /* ===================================================== PAGINATION ===================================================== */ .pagination { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 17px 20px; border-top: 1px solid var(--pc-border); } .pagination-info { color: var(--pc-muted); font-size: 10px; } .pagination-links { display: flex; gap: 5px; } .page-link { min-width: 31px; height: 31px; display: inline-flex; align-items: center; justify-content: center; padding: 0 8px; color: #64748b; background: #fff; border: 1px solid var(--pc-border); border-radius: 8px; font-size: 10px; font-weight: 700; } .page-link:hover { color: var(--pc-primary); border-color: rgba(15,118,110,.35); } .page-link.active { color: #fff; background: var(--pc-primary); border-color: var(--pc-primary); } /* ===================================================== RESPONSIVE ===================================================== */ @media (max-width: 1200px) { .pc-page { margin-left: 0; } .main-grid { grid-template-columns: 1fr; } } @media (max-width: 900px) { .stats-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .toolbar { grid-template-columns: 1fr 1fr; } } @media (max-width: 650px) { .pc-topbar { padding: 11px 16px; } .page-heading { display: none; } .pc-content { padding: 20px 15px; } .content-header { flex-direction: column; } .content-header .btn { width: 100%; } .stats-grid { grid-template-columns: 1fr; } .toolbar { grid-template-columns: 1fr; } .admin-info { display: none; } .card-header, .card-body { padding: 17px; } .pagination { flex-direction: column; align-items: stretch; } .pagination-links { justify-content: center; } } </style> </head> <body> <?php require_once __DIR__ . '/sidebar.php'; ?> <div class="pc-page"> <!-- ===================================================== STICKY TOPBAR ====================================================== --> <header class="pc-topbar"> <div class="topbar-left"> <div class="page-icon"> <i class="fa-solid fa-images"></i> </div> <div class="page-heading"> <h1> Brand Media </h1> <div class="breadcrumb"> <a href="index.php"> Dashboard </a> <i class="fa-solid fa-chevron-right"></i> <a href="brands.php"> Brands </a> <i class="fa-solid fa-chevron-right"></i> <span> Brand Media </span> </div> </div> </div> <div class="topbar-right"> <div class="admin-pill"> <div class="admin-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="pc-content"> <!-- PAGE HEADER --> <div class="content-header"> <div class="content-title"> <h2> Brand Media </h2> <p> Manage logos, images, galleries, videos and documents connected to your brands. </p> </div> <div> <a href="brands.php" class="btn btn-light" > <i class="fa-solid fa-arrow-left"></i> Back to Brands </a> </div> </div> <!-- ================================================= ALERT ================================================== --> <?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-grid"> <div class="stat-card"> <div class="stat-icon"> <i class="fa-solid fa-photo-film"></i> </div> <div> <span class="stat-value"> <?php echo number_format($stats['total']); ?> </span> <span class="stat-label"> Total Media Assignments </span> </div> </div> <div class="stat-card"> <div class="stat-icon"> <i class="fa-solid fa-copyright"></i> </div> <div> <span class="stat-value"> <?php echo number_format($stats['logos']); ?> </span> <span class="stat-label"> Brand Logos </span> </div> </div> <div class="stat-card"> <div class="stat-icon"> <i class="fa-solid fa-image"></i> </div> <div> <span class="stat-value"> <?php echo number_format($stats['images']); ?> </span> <span class="stat-label"> Brand Images </span> </div> </div> <div class="stat-card"> <div class="stat-icon"> <i class="fa-solid fa-images"></i> </div> <div> <span class="stat-value"> <?php echo number_format($stats['galleries']); ?> </span> <span class="stat-label"> Gallery Media </span> </div> </div> </div> <!-- ================================================= MAIN GRID ================================================== --> <div class="main-grid"> <!-- ================================================= ADD / EDIT ================================================== --> <section class="card"> <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 Brand Media <?php else: ?> <i class="fa-solid fa-plus" style="color:#0f766e;margin-right:6px;" ></i> Add Brand Media <?php endif; ?> </h3> <p> Connect an existing media record with a brand. </p> </div> <?php if ($editId > 0): ?> <a href="brand_media.php" class="btn btn-light" style="min-height:35px;" > Cancel </a> <?php endif; ?> </div> <div class="card-body"> <form method="post" action="" id="brandMediaForm" enctype="multipart/form-data" > <?php echo brand_media_csrf_field(); ?> <input type="hidden" name="action" value="save" > <input type="hidden" name="id" value="<?php echo (int)$form['id']; ?>" > <!-- BRAND --> <div class="form-group"> <label class="form-label"> Brand <span class="required"> * </span> </label> <select name="brand_id" class="form-select" required > <option value=""> — Select Brand — </option> <?php foreach ($brands as $brand): ?> <option value="<?php echo (int)$brand['id']; ?>" <?php echo (string)$form['brand_id'] === (string)$brand['id'] ? 'selected' : ''; ?> > <?php echo e( $brand['name'] ); ?> <?php if (!empty($brand['brand_type'])) { echo ' — ' . e( ucfirst( $brand['brand_type'] ) ); } ?> </option> <?php endforeach; ?> </select> <div class="form-help"> Select the existing brand to which this media belongs. </div> </div> <!-- EXISTING MEDIA SELECTOR --> <div class="form-group"> <label class="form-label"> Select Existing Media <span class="required">*</span> </label> <select name="media_id" class="form-select" id="media_id"> <option value="">— Select media from library —</option> <?php foreach ($availableMedia as $mediaItem): ?> <option value="<?php echo (int)$mediaItem['id']; ?>" <?php echo (string)$form['media_id'] === (string)$mediaItem['id'] ? 'selected' : ''; ?> > <?php echo '#' . (int)$mediaItem['id'] . ' — ' . e($mediaItem['original_name'] ?: $mediaItem['file_name']) . ' (' . e($mediaItem['file_type']) . ')'; ?> </option> <?php endforeach; ?> </select> <div class="form-help"> Select an existing record from the <strong>media</strong> table, or upload a new file below. </div> </div> <!-- UPLOAD MEDIA --> <div class="form-group"> <label class="form-label">Upload New Media (Optional)</label> <input type="file" name="media_file" id="media_file" class="form-control" accept="image/*,video/*,audio/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt" style="height:auto;padding:11px;" > <div class="form-help"> If a file is selected, it will be saved in uploads/media and registered in the media table. The uploaded file will be used instead of the selected existing media. </div> </div> <!-- ROLE --> <div class="form-group"> <label class="form-label"> Media Role <span class="required"> * </span> </label> <select name="media_role" class="form-select" required > <?php foreach ( $mediaRoleOptions as $role ): ?> <option value="<?php echo e($role); ?>" <?php echo $form['media_role'] === $role ? 'selected' : ''; ?> > <?php echo e( ucwords( str_replace( [ '-', '_' ], ' ', $role ) ) ); ?> </option> <?php endforeach; ?> </select> <div class="form-help"> Available values are loaded directly from the database ENUM. </div> </div> <!-- SORT ORDER --> <div class="form-group"> <label class="form-label"> Sort Order </label> <div class="input-wrap"> <i class="fa-solid fa-arrow-down-1-9" ></i> <input type="number" name="sort_order" class="form-control" value="<?php echo e( $form['sort_order'] ); ?>" min="0" step="1" > </div> <div class="form-help"> Lower number appears first. </div> </div> <!-- ACTION --> <div class="form-actions"> <?php if ($editId > 0): ?> <a href="brand_media.php" class="btn btn-light" > Cancel </a> <?php endif; ?> <button type="submit" class="btn btn-primary" id="saveMediaBtn" > <i class="fa-solid <?php echo $editId > 0 ? 'fa-floppy-disk' : 'fa-plus'; ?>" ></i> <?php echo $editId > 0 ? 'Update Media' : 'Add Media'; ?> </button> </div> </form> <!-- INFO --> <div style=" margin-top:20px; padding:13px; background:#f8fafc; border:1px solid #e5e7eb; border-radius:12px; color:#64748b; font-size:10px; line-height:1.6; " > <i class="fa-solid fa-circle-info" style="color:#0f766e;margin-right:5px;" ></i> Brand media is stored in the existing <strong>brand_media</strong> table. New uploads are registered in the existing <strong>media</strong> table, and their IDs are saved in <strong>brand_media.media_id</strong>. Deleting an assignment removes only the brand-media link; the shared media file is kept for other possible uses. </div> </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> Assigned Media </h3> <p> <?php echo number_format( $totalRecords ); ?> media assignments found. </p> </div> </div> <div class="card-body"> <!-- FILTER TOOLBAR --> <form method="get" action="brand_media.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 brand, slug or role..." > </div> <!-- BRAND FILTER --> <select name="brand_id" class="form-select" > <option value=""> All Brands </option> <?php foreach ($brands as $brand): ?> <option value="<?php echo (int)$brand['id']; ?>" <?php echo $filterBrandId === (int)$brand['id'] ? 'selected' : ''; ?> > <?php echo e( $brand['name'] ); ?> </option> <?php endforeach; ?> </select> <!-- ROLE FILTER --> <select name="role" class="form-select" > <option value=""> All Roles </option> <?php foreach ( $mediaRoleOptions as $role ): ?> <option value="<?php echo e($role); ?>" <?php echo $filterRole === $role ? 'selected' : ''; ?> > <?php echo e( ucwords( str_replace( [ '-', '_' ], ' ', $role ) ) ); ?> </option> <?php endforeach; ?> </select> <!-- FILTER --> <button type="submit" class="btn btn-primary" > <i class="fa-solid fa-filter" ></i> Filter </button> </form> <!-- RESET --> <?php if ( $search !== '' || $filterBrandId > 0 || $filterRole !== '' ): ?> <div style=" margin-bottom:15px; " > <a href="brand_media.php" style=" display:inline-flex; align-items:center; gap:6px; color:#0f766e; font-size:10px; font-weight:700; " > <i class="fa-solid fa-xmark" ></i> Clear all filters </a> </div> <?php endif; ?> </div> <!-- TABLE --> <div class="table-wrap"> <?php if ($mediaRows): ?> <table> <thead> <tr> <th> ID </th> <th> Brand </th> <th> Media </th> <th> Role </th> <th> Order </th> <th> Status </th> <th> Actions </th> </tr> </thead> <tbody> <?php foreach ( $mediaRows as $row ): ?> <tr> <!-- ID --> <td> <span class="record-id"> # <?php echo (int)$row['id']; ?> </span> </td> <!-- BRAND --> <td> <div class="brand-name"> <?php echo e( $row['brand_name'] ); ?> </div> <div class="brand-slug"> <?php echo e( $row['brand_slug'] ); ?> </div> </td> <!-- MEDIA --> <td> <span class="media-id" > <i class="fa-solid fa-photo-film" ></i> Media # <?php echo (int)$row['media_id']; ?> </span> <div class="brand-slug" style="max-width:220px;overflow-wrap:anywhere;"> <?php echo e($row['media_original_name'] ?: $row['media_file_name'] ?: 'Media file'); ?> </div> <?php if (!empty($row['media_file_path']) && strpos((string)$row['media_mime_type'], 'image/') === 0): ?> <div style="margin-top:7px;"> <img src="<?php echo e($row['media_file_path']); ?>" alt="<?php echo e($row['media_original_name'] ?: 'Media preview'); ?>" style="width:46px;height:46px;object-fit:cover;border-radius:8px;border:1px solid #e5e7eb;" loading="lazy" > </div> <?php endif; ?> </td> <!-- ROLE --> <td> <span class="role-badge" > <i class="fa-solid <?php switch ( $row['media_role'] ) { case 'logo': echo 'fa-copyright'; break; case 'gallery': echo 'fa-images'; break; case 'video': echo 'fa-video'; break; case 'document': echo 'fa-file-lines'; break; default: echo 'fa-image'; break; } ?>" style="margin-right:5px;" ></i> <?php echo e( ucwords( str_replace( [ '-', '_' ], ' ', $row['media_role'] ) ) ); ?> </span> </td> <!-- ORDER --> <td> <span class="order-badge" > <?php echo (int)$row['sort_order']; ?> </span> </td> <!-- STATUS --> <td> <?php if ( (int)$row['brand_status'] === 1 ): ?> <span class="status-dot" > Active </span> <?php else: ?> <span style=" color:#dc2626; font-size:9px; font-weight:700; " > ● Inactive </span> <?php endif; ?> </td> <!-- ACTIONS --> <td> <div class="action-group" > <!-- EDIT --> <a href="brand_media.php?edit=<?php echo (int)$row['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 brand media assignment?' ); " > <?php echo brand_media_csrf_field(); ?> <input type="hidden" name="action" value="delete" > <input type="hidden" name="id" value="<?php echo (int)$row['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: ?> <!-- EMPTY --> <div class="empty-state"> <div class="empty-icon"> <i class="fa-solid fa-photo-film" ></i> </div> <h4> No brand media found </h4> <p> <?php if ( $search !== '' || $filterBrandId > 0 || $filterRole !== '' ): echo 'No media assignment matches your current filters. Try clearing the filters or add a new brand media record.'; else: echo 'No brand media has been assigned yet. Use the form on the left to connect an existing media record with a brand.'; endif; ?> </p> </div> <?php endif; ?> </div> <!-- ================================================= PAGINATION ================================================== --> <?php if ($totalPages > 1): ?> <div class="pagination"> <div class="pagination-info"> Showing <?php echo $totalRecords > 0 ? ($offset + 1) : 0; ?> – <?php echo min( $offset + $perPage, $totalRecords ); ?> of <?php echo number_format( $totalRecords ); ?> records </div> <div class="pagination-links"> <?php if ($page > 1): ?> <a class="page-link" href="<?php echo e( brand_media_page_url( $page - 1, $search, $filterBrandId, $filterRole ) ); ?>" > <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( brand_media_page_url( $p, $search, $filterBrandId, $filterRole ) ); ?>" > <?php echo $p; ?> </a> <?php endfor; ?> <?php if ($page < $totalPages): ?> <a class="page-link" href="<?php echo e( brand_media_page_url( $page + 1, $search, $filterBrandId, $filterRole ) ); ?>" > <i class="fa-solid fa-chevron-right" ></i> </a> <?php endif; ?> </div> </div> <?php endif; ?> </section> </div> </main> </div> <script> document.addEventListener( 'DOMContentLoaded', function () { /* ===================================================== FORM LOADING STATE ===================================================== */ const form = document.getElementById( 'brandMediaForm' ); const button = document.getElementById( 'saveMediaBtn' ); if (form && button) { form.addEventListener( 'submit', function () { button.disabled = true; button.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Saving...'; } ); } /* ===================================================== AUTO SCROLL TO EDIT FORM ===================================================== */ const urlParams = new URLSearchParams( window.location.search ); if ( urlParams.has('edit') && form ) { setTimeout( function () { form.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 150 ); } } ); </script> </body> </html>
Save
Cancel