';
}
}
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);
}
?>
Brand Media | Pure Chemical Admin
Please fix the following:
Brand media is stored in the existing
brand_media table.
New uploads are registered in the existing
media table, and their IDs are saved
in brand_media.media_id .
Deleting an assignment removes only the brand-media link;
the shared media file is kept for other possible uses.
0 ||
$filterRole !== ''
): ?>
ID
Brand
Media
Role
Order
Status
Actions
#
Media #
Active
● Inactive
No brand media found
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;
?>
1): ?>