📁 File Manager
Editing:
/home/wvl7mof7402e/www/chem/admin/product_images.php
<?php /** * Pure Chemical Admin * File: admin/product_image.php * * Product Image / Product Media Manager * * Uses: * products * media * product_media * * No new database table required. */ if (session_status() === PHP_SESSION_NONE) { 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(); } else { if ( empty($_SESSION['admin_id']) && empty($_SESSION['admin_logged_in']) ) { header('Location: login.php'); exit; } } /* ========================================================= 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'; } if (!function_exists('pc_img_e')) { function pc_img_e($value) { return htmlspecialchars( (string)$value, ENT_QUOTES, 'UTF-8' ); } } /* ========================================================= CSRF ========================================================= */ function productImageCsrfToken() { if (function_exists('csrf_token')) { return csrf_token(); } if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } return $_SESSION['csrf_token']; } function productImageVerifyCsrf() { if (function_exists('csrf_verify')) { csrf_verify(); return; } if (function_exists('requireCsrf')) { requireCsrf(); return; } $token = $_POST['csrf_token'] ?? ''; if ( empty($_SESSION['csrf_token']) || empty($token) || !hash_equals( $_SESSION['csrf_token'], $token ) ) { header( 'Content-Type: application/json; charset=utf-8' ); echo json_encode([ 'success' => false, 'message' => 'Invalid security token.' ]); exit; } } function productImageJson( $success, $message, $extra = [] ) { header( 'Content-Type: application/json; charset=utf-8' ); echo json_encode( array_merge( [ 'success' => $success, 'message' => $message ], $extra ), JSON_UNESCAPED_UNICODE ); exit; } /* ========================================================= DETECT MEDIA TABLE COLUMNS ========================================================= */ $mediaColumns = []; try { $mediaColumnStmt = $pdo->query( "SHOW COLUMNS FROM media" ); foreach ( $mediaColumnStmt->fetchAll(PDO::FETCH_ASSOC) as $column ) { $mediaColumns[] = $column['Field']; } } catch (Throwable $e) { http_response_code(500); exit( 'Unable to read media table structure.' ); } /* * Find the most likely URL/path column. */ $mediaUrlColumn = null; $possibleUrlColumns = [ 'url', 'file_url', 'media_url', 'source_url', 'path', 'file_path', 'storage_path', 'relative_path', 'src', 'image_url', 'thumbnail_url', 'file' ]; foreach ( $possibleUrlColumns as $candidate ) { if ( in_array( $candidate, $mediaColumns, true ) ) { $mediaUrlColumn = $candidate; break; } } /* * Find useful title/name column. */ $mediaNameColumn = null; $possibleNameColumns = [ 'title', 'name', 'file_name', 'filename', 'original_name', 'alt_text' ]; foreach ( $possibleNameColumns as $candidate ) { if ( in_array( $candidate, $mediaColumns, true ) ) { $mediaNameColumn = $candidate; break; } } /* ========================================================= MEDIA URL HELPER ========================================================= */ function productMediaUrl($value) { $value = trim((string)$value); if ($value === '') { return ''; } /* * Absolute URL. */ if ( preg_match( '#^https?://#i', $value ) ) { return $value; } /* * Data URL. */ if ( strpos( $value, 'data:' ) === 0 ) { return $value; } /* * Root URL. */ if ( strpos( $value, '/' ) === 0 ) { return $value; } /* * Already relative to parent. */ if ( strpos( $value, '../' ) === 0 ) { return $value; } /* * Most admin pages are inside /admin, * so uploads/... needs ../uploads/... */ return '../' . ltrim( $value, '/' ); } /* ========================================================= AJAX ACTIONS ========================================================= */ if ($_SERVER['REQUEST_METHOD'] === 'POST') { $action = $_POST['action'] ?? ''; /* ===================================================== ADD PRODUCT IMAGE ===================================================== */ if ($action === 'add_image') { productImageVerifyCsrf(); $productId = (int)( $_POST['product_id'] ?? 0 ); $mediaId = (int)( $_POST['media_id'] ?? 0 ); $mediaRole = trim( $_POST['media_role'] ?? 'gallery' ); $title = trim( $_POST['title'] ?? '' ); $caption = trim( $_POST['caption'] ?? '' ); $altText = trim( $_POST['alt_text'] ?? '' ); $sortOrder = (int)( $_POST['sort_order'] ?? 0 ); /* --------------------------------------------- Validation --------------------------------------------- */ if ( $productId <= 0 || $mediaId <= 0 ) { productImageJson( false, 'Please select a product and image.' ); } $allowedRoles = [ 'featured', 'gallery', 'image' ]; if ( !in_array( $mediaRole, $allowedRoles, true ) ) { $mediaRole = 'gallery'; } /* --------------------------------------------- Product exists --------------------------------------------- */ $stmt = $pdo->prepare( " SELECT id, name FROM products WHERE id = ? LIMIT 1 " ); $stmt->execute([ $productId ]); $product = $stmt->fetch( PDO::FETCH_ASSOC ); if (!$product) { productImageJson( false, 'Selected product was not found.' ); } /* --------------------------------------------- Media exists --------------------------------------------- */ $stmt = $pdo->prepare( " SELECT id FROM media WHERE id = ? LIMIT 1 " ); $stmt->execute([ $mediaId ]); $media = $stmt->fetch( PDO::FETCH_ASSOC ); if (!$media) { productImageJson( false, 'Selected media was not found.' ); } /* --------------------------------------------- Duplicate check --------------------------------------------- */ $stmt = $pdo->prepare( " SELECT id FROM product_media WHERE product_id = ? AND media_id = ? LIMIT 1 " ); $stmt->execute([ $productId, $mediaId ]); if ($stmt->fetch()) { productImageJson( false, 'This image is already assigned to this product.' ); } /* --------------------------------------------- Featured image handling --------------------------------------------- */ try { $pdo->beginTransaction(); /* * If this is featured image, * remove previous featured relationship. */ if ($mediaRole === 'featured') { $stmt = $pdo->prepare( " UPDATE product_media SET media_role = 'gallery' WHERE product_id = ? AND media_role = 'featured' " ); $stmt->execute([ $productId ]); } /* ----------------------------------------- Insert relationship ----------------------------------------- */ $stmt = $pdo->prepare( " INSERT INTO product_media ( product_id, media_id, media_role, title, caption, alt_text, sort_order, created_at ) VALUES ( ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP ) " ); $stmt->execute([ $productId, $mediaId, $mediaRole, $title !== '' ? $title : null, $caption !== '' ? $caption : null, $altText !== '' ? $altText : null, $sortOrder ]); /* * Sync products.featured_image_id */ if ($mediaRole === 'featured') { $stmt = $pdo->prepare( " UPDATE products SET featured_image_id = ? WHERE id = ? " ); $stmt->execute([ $mediaId, $productId ]); } $pdo->commit(); productImageJson( true, 'Product image assigned successfully.' ); } catch (Throwable $e) { if ( $pdo->inTransaction() ) { $pdo->rollBack(); } error_log( 'Product Image Add Error: ' . $e->getMessage() ); productImageJson( false, 'Unable to assign product image.' ); } } /* ===================================================== REMOVE PRODUCT IMAGE ===================================================== */ if ($action === 'remove_image') { productImageVerifyCsrf(); $relationId = (int)( $_POST['relation_id'] ?? 0 ); if ($relationId <= 0) { productImageJson( false, 'Invalid product image.' ); } try { $pdo->beginTransaction(); /* * Get relation first. */ $stmt = $pdo->prepare( " SELECT id, product_id, media_id, media_role FROM product_media WHERE id = ? LIMIT 1 " ); $stmt->execute([ $relationId ]); $relation = $stmt->fetch( PDO::FETCH_ASSOC ); if (!$relation) { $pdo->rollBack(); productImageJson( false, 'Product image relationship not found.' ); } /* * Delete relationship only. * * Actual media file is NOT deleted. */ $stmt = $pdo->prepare( " DELETE FROM product_media WHERE id = ? LIMIT 1 " ); $stmt->execute([ $relationId ]); /* * If featured image was removed, * clear products.featured_image_id. */ if ( $relation['media_role'] === 'featured' ) { $stmt = $pdo->prepare( " UPDATE products SET featured_image_id = NULL WHERE id = ? AND featured_image_id = ? " ); $stmt->execute([ $relation['product_id'], $relation['media_id'] ]); } $pdo->commit(); productImageJson( true, 'Product image removed successfully.' ); } catch (Throwable $e) { if ( $pdo->inTransaction() ) { $pdo->rollBack(); } error_log( 'Product Image Remove Error: ' . $e->getMessage() ); productImageJson( false, 'Unable to remove product image.' ); } } /* ===================================================== CHANGE ROLE ===================================================== */ if ($action === 'change_role') { productImageVerifyCsrf(); $relationId = (int)( $_POST['relation_id'] ?? 0 ); $newRole = trim( $_POST['media_role'] ?? 'gallery' ); if ( !in_array( $newRole, [ 'featured', 'gallery', 'image' ], true ) ) { productImageJson( false, 'Invalid image role.' ); } $stmt = $pdo->prepare( " SELECT id, product_id, media_id, media_role FROM product_media WHERE id = ? LIMIT 1 " ); $stmt->execute([ $relationId ]); $relation = $stmt->fetch( PDO::FETCH_ASSOC ); if (!$relation) { productImageJson( false, 'Product image not found.' ); } try { $pdo->beginTransaction(); /* * Only one featured image * per product. */ if ( $newRole === 'featured' ) { $stmt = $pdo->prepare( " UPDATE product_media SET media_role = 'gallery' WHERE product_id = ? AND media_role = 'featured' AND id != ? " ); $stmt->execute([ $relation['product_id'], $relationId ]); } /* * Update role. */ $stmt = $pdo->prepare( " UPDATE product_media SET media_role = ? WHERE id = ? " ); $stmt->execute([ $newRole, $relationId ]); /* * Product featured image. */ if ( $newRole === 'featured' ) { $stmt = $pdo->prepare( " UPDATE products SET featured_image_id = ? WHERE id = ? " ); $stmt->execute([ $relation['media_id'], $relation['product_id'] ]); } elseif ( $relation['media_role'] === 'featured' ) { $stmt = $pdo->prepare( " UPDATE products SET featured_image_id = NULL WHERE id = ? AND featured_image_id = ? " ); $stmt->execute([ $relation['product_id'], $relation['media_id'] ]); } $pdo->commit(); productImageJson( true, 'Image role updated successfully.' ); } catch (Throwable $e) { if ( $pdo->inTransaction() ) { $pdo->rollBack(); } error_log( 'Product Image Role Error: ' . $e->getMessage() ); productImageJson( false, 'Unable to update image role.' ); } } productImageJson( false, 'Invalid action.' ); } /* ========================================================= FILTERS ========================================================= */ $productFilter = (int)( $_GET['product_id'] ?? 0 ); $roleFilter = trim( $_GET['role'] ?? '' ); $search = trim( $_GET['search'] ?? '' ); $page = max( 1, (int)( $_GET['page'] ?? 1 ) ); $perPage = 18; /* ========================================================= PRODUCTS ========================================================= */ $productStmt = $pdo->query( " SELECT id, name, product_code, slug, status FROM products ORDER BY name ASC " ); $products = $productStmt->fetchAll( PDO::FETCH_ASSOC ); /* ========================================================= MEDIA LIST ========================================================= */ $mediaSelect = [ 'id' ]; if ($mediaUrlColumn) { $mediaSelect[] = $mediaUrlColumn . ' AS media_source'; } else { $mediaSelect[] = 'NULL AS media_source'; } if ($mediaNameColumn) { $mediaSelect[] = $mediaNameColumn . ' AS media_name'; } else { $mediaSelect[] = 'NULL AS media_name'; } /* * Additional useful media fields * only if they exist. */ foreach ( [ 'mime_type', 'file_type', 'type', 'title', 'alt_text' ] as $optional ) { if ( in_array( $optional, $mediaColumns, true ) ) { $mediaSelect[] = $optional; } } $mediaSql = " SELECT " . implode( ', ', $mediaSelect ) . " FROM media ORDER BY id DESC LIMIT 500 "; $mediaStmt = $pdo->query( $mediaSql ); $mediaList = $mediaStmt->fetchAll( PDO::FETCH_ASSOC ); /* ========================================================= WHERE ========================================================= */ $where = []; $params = []; if ($productFilter > 0) { $where[] = 'pm.product_id = ?'; $params[] = $productFilter; } if ( in_array( $roleFilter, [ 'featured', 'gallery', 'image' ], true ) ) { $where[] = 'pm.media_role = ?'; $params[] = $roleFilter; } if ($search !== '') { $where[] = " ( p.name LIKE ? OR p.product_code LIKE ? OR p.slug LIKE ? OR pm.title LIKE ? OR pm.alt_text LIKE ? ) "; $searchValue = '%' . $search . '%'; $params[] = $searchValue; $params[] = $searchValue; $params[] = $searchValue; $params[] = $searchValue; $params[] = $searchValue; } $whereSql = $where ? 'WHERE ' . implode( ' AND ', $where ) : ''; /* ========================================================= COUNT ========================================================= */ $countSql = " SELECT COUNT(*) FROM product_media pm INNER JOIN products p ON p.id = pm.product_id {$whereSql} "; $countStmt = $pdo->prepare( $countSql ); $countStmt->execute( $params ); $totalRows = (int)$countStmt->fetchColumn(); $totalPages = max( 1, (int)ceil( $totalRows / $perPage ) ); if ($page > $totalPages) { $page = $totalPages; } $offset = ($page - 1) * $perPage; /* ========================================================= PRODUCT MEDIA RECORDS ========================================================= */ $listSql = " SELECT pm.id, pm.product_id, pm.media_id, pm.media_role, pm.external_url, pm.title, pm.caption, pm.alt_text, pm.sort_order, pm.created_at, p.name AS product_name, p.product_code, p.slug AS product_slug, p.status AS product_status, m.id AS actual_media_id " . ( $mediaUrlColumn ? ', m.' . $mediaUrlColumn . ' AS media_source' : ', NULL AS media_source' ) . " " . ( $mediaNameColumn ? ', m.' . $mediaNameColumn . ' AS media_name' : ', NULL AS media_name' ) . " FROM product_media pm INNER JOIN products p ON p.id = pm.product_id LEFT JOIN media m ON m.id = pm.media_id {$whereSql} ORDER BY pm.product_id ASC, pm.media_role ASC, pm.sort_order ASC, pm.id DESC LIMIT {$perPage} OFFSET {$offset} "; $listStmt = $pdo->prepare( $listSql ); $listStmt->execute( $params ); $images = $listStmt->fetchAll( PDO::FETCH_ASSOC ); /* ========================================================= STATS ========================================================= */ $totalImages = (int)$pdo->query( " SELECT COUNT(*) FROM product_media " )->fetchColumn(); $featuredImages = (int)$pdo->query( " SELECT COUNT(*) FROM product_media WHERE media_role = 'featured' " )->fetchColumn(); $galleryImages = (int)$pdo->query( " SELECT COUNT(*) FROM product_media WHERE media_role = 'gallery' " )->fetchColumn(); $productsWithImages = (int)$pdo->query( " SELECT COUNT( DISTINCT product_id ) FROM product_media " )->fetchColumn(); /* ========================================================= PAGE ========================================================= */ $page_title = 'Product Images'; $active_menu = 'product_images'; $csrfToken = productImageCsrfToken(); ?> <style> /* ========================================================= PRODUCT IMAGE PAGE ========================================================= */ :root { --pi-primary: #2563eb; --pi-primary-2: #4f46e5; --pi-bg: #f5f7fb; --pi-card: #ffffff; --pi-border: #e5e7eb; --pi-text: #111827; --pi-muted: #6b7280; --pi-green: #16a34a; --pi-red: #dc2626; --pi-radius: 18px; --pi-shadow: 0 12px 35px rgba(15, 23, 42, .07); } /* ========================================================= LAYOUT ========================================================= */ .pi-layout { min-height: 100vh; background: linear-gradient( 180deg, #f8fafc 0%, #f5f7fb 100% ); } /* * Existing sidebar.php * * Most premium admin sidebars use fixed width * around 260-280px. */ .pi-sidebar { position: fixed; left: 0; top: 0; bottom: 0; width: 270px; z-index: 1000; overflow-y: auto; background: #ffffff; border-right: 1px solid #e5e7eb; } /* * Main content stays on right. */ .pi-main { margin-left: 270px; min-height: 100vh; } /* ========================================================= TOPBAR ========================================================= */ .pi-topbar { height: 72px; background: rgba(255,255,255,.92); backdrop-filter: blur(16px); border-bottom: 1px solid var(--pi-border); display: flex; align-items: center; justify-content: space-between; padding: 0 28px; position: sticky; top: 0; z-index: 500; } .pi-breadcrumb { display: flex; align-items: center; gap: 9px; font-size: 13px; color: var(--pi-muted); } .pi-breadcrumb strong { color: var(--pi-text); } .pi-topbar-right { display: flex; align-items: center; gap: 10px; } .pi-admin-chip { display: flex; align-items: center; gap: 9px; padding: 7px 11px; border: 1px solid var(--pi-border); border-radius: 12px; background: #fff; } .pi-admin-avatar { width: 32px; height: 32px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 12px; font-weight: 800; background: linear-gradient( 135deg, var(--pi-primary), var(--pi-primary-2) ); } /* ========================================================= CONTENT ========================================================= */ .pi-content { padding: 28px; max-width: 1700px; margin: 0 auto; } /* ========================================================= PAGE HEADER ========================================================= */ .pi-page-header { display: flex; justify-content: space-between; align-items: center; gap: 20px; margin-bottom: 24px; } .pi-title-wrap { display: flex; align-items: center; gap: 15px; } .pi-title-icon { width: 54px; height: 54px; border-radius: 16px; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 21px; background: linear-gradient( 135deg, var(--pi-primary), var(--pi-primary-2) ); box-shadow: 0 12px 25px rgba(37,99,235,.22); } .pi-title h1 { margin: 0; font-size: 27px; font-weight: 850; letter-spacing: -.5px; color: var(--pi-text); } .pi-title p { margin: 5px 0 0; font-size: 13px; color: var(--pi-muted); } /* ========================================================= BUTTON ========================================================= */ .pi-btn { height: 44px; padding: 0 16px; border: 0; border-radius: 12px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; font-size: 13px; font-weight: 750; cursor: pointer; transition: .2s ease; text-decoration: none; } .pi-btn-primary { color: #fff; background: linear-gradient( 135deg, var(--pi-primary), var(--pi-primary-2) ); box-shadow: 0 10px 22px rgba(37,99,235,.20); } .pi-btn-primary:hover { transform: translateY(-1px); box-shadow: 0 14px 28px rgba(37,99,235,.28); } .pi-btn-light { color: #374151; background: #f3f4f6; } .pi-btn-danger { color: #fff; background: #dc2626; } /* ========================================================= STATS ========================================================= */ .pi-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 20px; } .pi-stat { background: #fff; border: 1px solid var(--pi-border); border-radius: var(--pi-radius); padding: 18px; display: flex; align-items: center; gap: 14px; box-shadow: var(--pi-shadow); } .pi-stat-icon { width: 48px; height: 48px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 18px; } .pi-blue { background: #eff6ff; color: #2563eb; } .pi-purple { background: #f5f3ff; color: #7c3aed; } .pi-green { background: #f0fdf4; color: #16a34a; } .pi-orange { background: #fff7ed; color: #ea580c; } .pi-stat-label { font-size: 11px; color: var(--pi-muted); font-weight: 700; } .pi-stat-value { margin-top: 3px; font-size: 22px; font-weight: 850; color: var(--pi-text); } /* ========================================================= FILTER ========================================================= */ .pi-card { background: #fff; border: 1px solid var(--pi-border); border-radius: var(--pi-radius); box-shadow: var(--pi-shadow); } .pi-filter { padding: 17px; margin-bottom: 20px; } .pi-filter-form { display: grid; grid-template-columns: 1.5fr 1fr 1fr auto; gap: 11px; align-items: end; } .pi-field { display: flex; flex-direction: column; gap: 7px; } .pi-field label { font-size: 11px; font-weight: 800; color: #4b5563; } .pi-input, .pi-select { width: 100%; height: 44px; border: 1px solid #dbe1ea; border-radius: 11px; padding: 0 12px; background: #fff; color: #111827; outline: none; font-size: 13px; } .pi-input:focus, .pi-select:focus { border-color: var(--pi-primary); box-shadow: 0 0 0 4px rgba(37,99,235,.08); } /* ========================================================= TABLE ========================================================= */ .pi-table-card { overflow: hidden; } .pi-table-head { padding: 18px 20px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--pi-border); } .pi-table-title { font-size: 16px; font-weight: 850; color: var(--pi-text); } .pi-table-sub { margin-top: 3px; font-size: 11px; color: var(--pi-muted); } .pi-table-wrap { overflow-x: auto; } .pi-table { width: 100%; min-width: 1000px; border-collapse: collapse; } .pi-table th { padding: 13px 18px; text-align: left; font-size: 10px; font-weight: 850; text-transform: uppercase; letter-spacing: .5px; color: #64748b; background: #f8fafc; border-bottom: 1px solid var(--pi-border); } .pi-table td { padding: 15px 18px; border-bottom: 1px solid #eef1f5; vertical-align: middle; } .pi-table tr:hover td { background: #f8fbff; } /* ========================================================= IMAGE ========================================================= */ .pi-image { width: 64px; height: 64px; border-radius: 13px; object-fit: cover; background: #f1f5f9; border: 1px solid #e5e7eb; } .pi-no-image { width: 64px; height: 64px; border-radius: 13px; background: #f1f5f9; display: flex; align-items: center; justify-content: center; color: #94a3b8; font-size: 20px; } .pi-product { display: flex; align-items: center; gap: 11px; } .pi-product-icon { width: 42px; height: 42px; border-radius: 12px; background: #eff6ff; color: #2563eb; display: flex; align-items: center; justify-content: center; } .pi-product-name { font-size: 13px; font-weight: 800; color: #111827; } .pi-product-code { margin-top: 3px; font-size: 10px; color: #9ca3af; } /* ========================================================= ROLE ========================================================= */ .pi-role { border: 0; height: 35px; padding: 0 10px; border-radius: 9px; background: #f8fafc; border: 1px solid #e5e7eb; font-size: 11px; font-weight: 750; outline: none; } .pi-role-featured { color: #b45309; background: #fffbeb; border-color: #fde68a; } .pi-role-gallery { color: #2563eb; background: #eff6ff; border-color: #bfdbfe; } .pi-role-image { color: #7c3aed; background: #f5f3ff; border-color: #ddd6fe; } /* ========================================================= REMOVE ========================================================= */ .pi-delete { width: 36px; height: 36px; border: 0; border-radius: 10px; color: #dc2626; background: #fef2f2; cursor: pointer; } .pi-delete:hover { background: #fee2e2; } /* ========================================================= PAGINATION ========================================================= */ .pi-pagination { padding: 15px 18px; display: flex; justify-content: space-between; align-items: center; border-top: 1px solid var(--pi-border); } .pi-pages { display: flex; gap: 6px; } .pi-page { min-width: 34px; height: 34px; padding: 0 9px; border: 1px solid #e5e7eb; border-radius: 9px; display: flex; align-items: center; justify-content: center; text-decoration: none; color: #374151; font-size: 11px; font-weight: 750; } .pi-page.active { color: #fff; background: #2563eb; border-color: #2563eb; } /* ========================================================= MODAL ========================================================= */ .pi-modal { position: fixed; inset: 0; z-index: 99999; display: none; align-items: center; justify-content: center; padding: 20px; overflow-y: auto; background: rgba(15,23,42,.58); backdrop-filter: blur(7px); } .pi-modal.show { display: flex; } .pi-modal-box { width: 100%; max-width: 600px; max-height: calc(100vh - 40px); display: flex; flex-direction: column; margin: auto; background: #fff; border-radius: 22px; overflow: hidden; box-shadow: 0 30px 80px rgba(15,23,42,.25); } .pi-modal-head { padding: 19px 21px; border-bottom: 1px solid var(--pi-border); display: flex; justify-content: space-between; align-items: center; } .pi-modal-head h3 { margin: 0; font-size: 17px; font-weight: 850; } .pi-close { width: 35px; height: 35px; border: 0; border-radius: 10px; background: #f3f4f6; cursor: pointer; } .pi-modal-body { padding: 22px; overflow-y: auto; min-height: 0; flex: 1 1 auto; } .pi-modal-footer { padding: 16px 21px; border-top: 1px solid var(--pi-border); display: flex; justify-content: flex-end; gap: 9px; } /* ========================================================= MEDIA SELECT ========================================================= */ .pi-media-select { display: grid; grid-template-columns: repeat(4, 1fr); gap: 9px; max-height: 270px; overflow-y: auto; margin-top: 9px; } .pi-media-option { position: relative; } .pi-media-option input { position: absolute; opacity: 0; } .pi-media-card { border: 2px solid transparent; border-radius: 12px; padding: 5px; background: #f8fafc; cursor: pointer; transition: .2s ease; } .pi-media-card:hover { border-color: #bfdbfe; } .pi-media-option input:checked + .pi-media-card { border-color: #2563eb; background: #eff6ff; } .pi-media-card img { width: 100%; aspect-ratio: 1 / 1; object-fit: cover; border-radius: 8px; } .pi-media-name { display: block; margin-top: 4px; font-size: 9px; color: #64748b; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } /* ========================================================= TOAST ========================================================= */ .pi-toast { position: fixed; right: 24px; bottom: 24px; z-index: 100000; min-width: 290px; max-width: 390px; padding: 14px 16px; border-radius: 13px; color: #fff; background: #111827; display: none; box-shadow: 0 18px 45px rgba(15,23,42,.22); } .pi-toast.show { display: block; } .pi-toast.success { background: #15803d; } .pi-toast.error { background: #b91c1c; } /* ========================================================= MOBILE ========================================================= */ @media (max-width: 1100px) { .pi-stats { grid-template-columns: repeat(2, 1fr); } .pi-filter-form { grid-template-columns: repeat(2, 1fr); } } @media (max-width: 800px) { .pi-sidebar { position: relative; width: 100%; height: auto; } .pi-main { margin-left: 0; } .pi-topbar { padding: 0 15px; } .pi-content { padding: 18px 14px; } .pi-page-header { align-items: flex-start; flex-direction: column; } .pi-filter-form { grid-template-columns: 1fr; } } @media (max-width: 550px) { .pi-stats { grid-template-columns: 1fr; } .pi-title h1 { font-size: 22px; } .pi-media-select { grid-template-columns: repeat(3, 1fr); } .pi-modal-footer { flex-direction: column; } .pi-modal-footer .pi-btn { width: 100%; } } /* MODAL FORM FIX: keep the action buttons visible while the form scrolls */ .pi-modal { align-items: center; justify-content: center; overflow-y: auto; padding: 16px; } .pi-modal-box { max-height: calc(100dvh - 32px); min-height: 0; flex: 0 1 600px; } .pi-modal-box > form#productImageForm { display: flex; flex: 1 1 auto; flex-direction: column; min-height: 0; overflow: hidden; } .pi-modal-head { flex: 0 0 auto; } .pi-modal-body { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; } .pi-modal-footer { flex: 0 0 auto; position: relative; z-index: 2; background: #fff; padding-bottom: max(16px, env(safe-area-inset-bottom)); } @media (max-height: 650px) { .pi-modal { align-items: flex-start; padding: 10px; } .pi-modal-box { max-height: calc(100dvh - 20px); margin: auto 0; border-radius: 16px; } .pi-modal-head { padding: 13px 16px; } .pi-modal-body { padding: 16px; } .pi-modal-footer { padding: 12px 16px; } } @media (max-width: 550px) { .pi-modal { padding: 8px; } .pi-modal-box { max-height: calc(100dvh - 16px); border-radius: 16px; } .pi-modal-footer { flex-direction: row; flex-wrap: wrap; } .pi-modal-footer .pi-btn { width: auto; flex: 1 1 120px; } } </style> <div class="pi-layout"> <!-- ===================================================== LEFT SIDEBAR ====================================================== --> <aside class="pi-sidebar"> <?php /* * YOUR EXISTING ADMIN SIDEBAR * * admin/sidebar.php * * No duplicate sidebar file is created. */ if ( file_exists( __DIR__ . '/sidebar.php' ) ) { require_once __DIR__ . '/sidebar.php'; } else { echo ' <div style=" padding:25px; color:#b91c1c; font-family:Arial; font-size:13px; "> sidebar.php not found. </div> '; } ?> </aside> <!-- ===================================================== MAIN ====================================================== --> <main class="pi-main"> <!-- TOPBAR --> <div class="pi-topbar"> <div class="pi-breadcrumb"> <span> Admin </span> <i class="fa-solid fa-chevron-right" style="font-size:9px;"> </i> <strong> Product Images </strong> </div> <div class="pi-topbar-right"> <div class="pi-admin-chip"> <div class="pi-admin-avatar"> <?php $adminName = $_SESSION['admin_name'] ?? $_SESSION['ADMIN_NAME'] ?? 'Admin'; echo pc_img_e( strtoupper( substr( trim($adminName), 0, 1 ) ) ); ?> </div> <span style=" font-size:12px; font-weight:750; color:#374151; "> <?= pc_img_e($adminName) ?> </span> </div> </div> </div> <!-- CONTENT --> <div class="pi-content"> <!-- PAGE HEADER --> <div class="pi-page-header"> <div class="pi-title-wrap"> <div class="pi-title-icon"> <i class="fa-solid fa-images"></i> </div> <div class="pi-title"> <h1> Product Images </h1> <p> Manage product featured images, galleries and media. </p> </div> </div> <button type="button" class="pi-btn pi-btn-primary" onclick="openProductImageModal()" > <i class="fa-solid fa-plus"></i> Add Product Image </button> </div> <!-- STATS --> <div class="pi-stats"> <div class="pi-stat"> <div class="pi-stat-icon pi-blue"> <i class="fa-solid fa-images"></i> </div> <div> <div class="pi-stat-label"> Total Product Images </div> <div class="pi-stat-value"> <?= number_format( $totalImages ) ?> </div> </div> </div> <div class="pi-stat"> <div class="pi-stat-icon pi-orange"> <i class="fa-solid fa-star"></i> </div> <div> <div class="pi-stat-label"> Featured Images </div> <div class="pi-stat-value"> <?= number_format( $featuredImages ) ?> </div> </div> </div> <div class="pi-stat"> <div class="pi-stat-icon pi-purple"> <i class="fa-solid fa-photo-film"></i> </div> <div> <div class="pi-stat-label"> Gallery Images </div> <div class="pi-stat-value"> <?= number_format( $galleryImages ) ?> </div> </div> </div> <div class="pi-stat"> <div class="pi-stat-icon pi-green"> <i class="fa-solid fa-box-open"></i> </div> <div> <div class="pi-stat-label"> Products With Images </div> <div class="pi-stat-value"> <?= number_format( $productsWithImages ) ?> </div> </div> </div> </div> <!-- FILTER --> <div class="pi-card pi-filter"> <form method="GET" action="product_image.php" class="pi-filter-form" > <div class="pi-field"> <label> Search </label> <input type="text" name="search" class="pi-input" placeholder="Product, code, title..." value="<?= pc_img_e( $search ) ?>" > </div> <div class="pi-field"> <label> Product </label> <select name="product_id" class="pi-select" > <option value="0"> All Products </option> <?php foreach ( $products as $product ): ?> <option value="<?= (int)$product['id'] ?>" <?= $productFilter == $product['id'] ? 'selected' : '' ?> > <?= pc_img_e( $product['name'] ) ?> <?php if ( !empty( $product['product_code'] ) ): ?> — <?= pc_img_e( $product['product_code'] ) ?> <?php endif; ?> </option> <?php endforeach; ?> </select> </div> <div class="pi-field"> <label> Image Type </label> <select name="role" class="pi-select" > <option value=""> All Types </option> <option value="featured" <?= $roleFilter === 'featured' ? 'selected' : '' ?> > Featured </option> <option value="gallery" <?= $roleFilter === 'gallery' ? 'selected' : '' ?> > Gallery </option> <option value="image" <?= $roleFilter === 'image' ? 'selected' : '' ?> > Image </option> </select> </div> <div style=" display:flex; gap:8px; "> <button type="submit" class="pi-btn pi-btn-primary" > <i class="fa-solid fa-filter"></i> Filter </button> <a href="product_image.php" class="pi-btn pi-btn-light" > <i class="fa-solid fa-rotate-left"></i> </a> </div> </form> </div> <!-- TABLE --> <div class="pi-card pi-table-card"> <div class="pi-table-head"> <div> <div class="pi-table-title"> Product Media </div> <div class="pi-table-sub"> <?= number_format( $totalRows ) ?> image relationship(s) </div> </div> </div> <?php if (!$images): ?> <div style=" padding:70px 20px; text-align:center; "> <div style=" width:64px; height:64px; margin:0 auto 15px; border-radius:18px; background:#f1f5f9; display:flex; align-items:center; justify-content:center; color:#94a3b8; font-size:25px; "> <i class="fa-solid fa-image"></i> </div> <h3 style=" margin:0; font-size:17px; "> No Product Images Found </h3> <p style=" margin:7px 0 0; color:#6b7280; font-size:13px; "> Assign an image from the Media Library to a product. </p> </div> <?php else: ?> <div class="pi-table-wrap"> <table class="pi-table"> <thead> <tr> <th> Preview </th> <th> Product </th> <th> Image Information </th> <th> Role </th> <th> Sort </th> <th> Added </th> <th> Action </th> </tr> </thead> <tbody> <?php foreach ( $images as $image ): ?> <tr id="product-image-<?= (int)$image['id'] ?>" > <!-- PREVIEW --> <td> <?php $imageSource = ''; if ( !empty( $image['media_source'] ) ) { $imageSource = productMediaUrl( $image[ 'media_source' ] ); } /* * External URL from * product_media has priority. */ if ( !empty( $image[ 'external_url' ] ) ) { $imageSource = $image[ 'external_url' ]; } ?> <?php if ( $imageSource !== '' ): ?> <img src="<?= pc_img_e( $imageSource ) ?>" class="pi-image" alt="<?= pc_img_e( $image['alt_text'] ?: $image['product_name'] ) ?>" loading="lazy" > <?php else: ?> <div class="pi-no-image"> <i class="fa-solid fa-image"></i> </div> <?php endif; ?> </td> <!-- PRODUCT --> <td> <div class="pi-product"> <div class="pi-product-icon"> <i class="fa-solid fa-flask"></i> </div> <div> <div class="pi-product-name"> <?= pc_img_e( $image[ 'product_name' ] ) ?> </div> <div class="pi-product-code"> <?php if ( !empty( $image[ 'product_code' ] ) ): ?> <?= pc_img_e( $image[ 'product_code' ] ) ?> <?php else: ?> <?= pc_img_e( $image[ 'product_slug' ] ) ?> <?php endif; ?> </div> </div> </div> </td> <!-- IMAGE INFO --> <td> <div style=" max-width:240px; "> <div style=" font-size:13px; font-weight:750; color:#111827; "> <?= pc_img_e( $image[ 'title' ] ?: $image[ 'media_name' ] ?: 'Media #' . $image[ 'media_id' ] ) ?> </div> <?php if ( !empty( $image[ 'alt_text' ] ) ): ?> <div style=" margin-top:4px; color:#9ca3af; font-size:10px; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; "> ALT: <?= pc_img_e( $image[ 'alt_text' ] ) ?> </div> <?php endif; ?> </div> </td> <!-- ROLE --> <td> <select class="pi-role pi-role-<?= pc_img_e( $image[ 'media_role' ] ) ?>" onchange="changeProductImageRole( <?= (int)$image['id'] ?>, this )" > <option value="featured" <?= $image[ 'media_role' ] === 'featured' ? 'selected' : '' ?> > Featured </option> <option value="gallery" <?= $image[ 'media_role' ] === 'gallery' ? 'selected' : '' ?> > Gallery </option> <option value="image" <?= $image[ 'media_role' ] === 'image' ? 'selected' : '' ?> > Image </option> </select> </td> <!-- SORT --> <td> <span style=" display:inline-flex; width:32px; height:32px; align-items:center; justify-content:center; border-radius:9px; background:#f8fafc; color:#64748b; font-size:11px; font-weight:800; "> <?= (int)$image[ 'sort_order' ] ?> </span> </td> <!-- DATE --> <td> <span style=" font-size:11px; color:#64748b; "> <?= !empty( $image[ 'created_at' ] ) ? date( 'd M Y', strtotime( $image[ 'created_at' ] ) ) : '—' ?> </span> </td> <!-- ACTION --> <td> <button type="button" class="pi-delete" title="Remove Image" onclick="removeProductImage( <?= (int)$image['id'] ?> )" > <i class="fa-solid fa-trash"></i> </button> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> <!-- PAGINATION --> <?php if ( $totalPages > 1 ): ?> <div class="pi-pagination"> <div style=" font-size:11px; color:#6b7280; "> Showing <?= number_format( $offset + 1 ) ?> - <?= number_format( min( $offset + $perPage, $totalRows ) ) ?> of <?= number_format( $totalRows ) ?> </div> <div class="pi-pages"> <?php if ( $page > 1 ): ?> <a class="pi-page" href="<?= pc_img_e( '?' . http_build_query( array_merge( $_GET, [ 'page' => $page - 1 ] ) ) ) ?>" > <i class="fa-solid fa-chevron-left"></i> </a> <?php endif; ?> <?php $startPage = max( 1, $page - 2 ); $endPage = min( $totalPages, $page + 2 ); ?> <?php for ( $p = $startPage; $p <= $endPage; $p++ ): ?> <a class="pi-page <?= $p == $page ? 'active' : '' ?>" href="<?= pc_img_e( '?' . http_build_query( array_merge( $_GET, [ 'page' => $p ] ) ) ) ?>" > <?= $p ?> </a> <?php endfor; ?> <?php if ( $page < $totalPages ): ?> <a class="pi-page" href="<?= pc_img_e( '?' . http_build_query( array_merge( $_GET, [ 'page' => $page + 1 ] ) ) ) ?>" > <i class="fa-solid fa-chevron-right"></i> </a> <?php endif; ?> </div> </div> <?php endif; ?> <?php endif; ?> </div> </div> </main> </div> <!-- ========================================================= ADD IMAGE MODAL ========================================================= --> <div class="pi-modal" id="productImageModal" > <div class="pi-modal-box"> <div class="pi-modal-head"> <h3> Add Product Image </h3> <button type="button" class="pi-close" onclick="closeProductImageModal()" > <i class="fa-solid fa-xmark"></i> </button> </div> <form id="productImageForm" > <input type="hidden" name="action" value="add_image" > <input type="hidden" name="csrf_token" value="<?= pc_img_e( $csrfToken ) ?>" > <div class="pi-modal-body"> <!-- PRODUCT --> <div class="pi-field"> <label> Product </label> <select name="product_id" class="pi-select" required > <option value=""> Select Product </option> <?php foreach ( $products as $product ): ?> <option value="<?= (int)$product['id'] ?>" > <?= pc_img_e( $product['name'] ) ?> <?php if ( !empty( $product[ 'product_code' ] ) ): ?> — <?= pc_img_e( $product[ 'product_code' ] ) ?> <?php endif; ?> </option> <?php endforeach; ?> </select> </div> <div style=" height:15px; "></div> <!-- IMAGE --> <div class="pi-field"> <label> Select Media Image </label> <div class="pi-media-select"> <?php foreach ( $mediaList as $media ): ?> <?php $source = ''; if ( !empty( $media[ 'media_source' ] ) ) { $source = productMediaUrl( $media[ 'media_source' ] ); } ?> <label class="pi-media-option"> <input type="radio" name="media_id" value="<?= (int)$media['id'] ?>" required > <span class="pi-media-card"> <?php if ( $source !== '' ): ?> <img src="<?= pc_img_e( $source ) ?>" alt="" loading="lazy" > <?php else: ?> <span style=" display:flex; aspect-ratio:1; align-items:center; justify-content:center; color:#94a3b8; font-size:22px; "> <i class="fa-solid fa-image"></i> </span> <?php endif; ?> <span class="pi-media-name"> <?= pc_img_e( $media[ 'media_name' ] ?: 'Media #' . $media[ 'id' ] ) ?> </span> </span> </label> <?php endforeach; ?> </div> <?php if ( !$mediaList ): ?> <div style=" margin-top:10px; padding:14px; border-radius:11px; background:#fff7ed; color:#9a3412; font-size:12px; "> No media found in Media Library. </div> <?php endif; ?> </div> <div style=" height:15px; "></div> <!-- ROLE --> <div class="pi-field"> <label> Image Role </label> <select name="media_role" class="pi-select" > <option value="gallery"> Gallery </option> <option value="featured"> Featured Image </option> <option value="image"> Image </option> </select> </div> <div style=" height:15px; "></div> <!-- TITLE --> <div class="pi-field"> <label> Title </label> <input type="text" name="title" class="pi-input" maxlength="255" placeholder="Image title" > </div> <div style=" height:15px; "></div> <!-- ALT --> <div class="pi-field"> <label> Alt Text </label> <input type="text" name="alt_text" class="pi-input" maxlength="255" placeholder="SEO friendly image alt text" > </div> <div style=" height:15px; "></div> <!-- CAPTION --> <div class="pi-field"> <label> Caption </label> <textarea name="caption" class="pi-input" rows="3" style=" height:auto; padding-top:10px; padding-bottom:10px; resize:vertical; " placeholder="Optional image caption" ></textarea> </div> <div style=" height:15px; "></div> <!-- SORT --> <div class="pi-field"> <label> Sort Order </label> <input type="number" name="sort_order" class="pi-input" value="0" min="0" > </div> </div> <div class="pi-modal-footer"> <button type="button" class="pi-btn pi-btn-light" onclick="closeProductImageModal()" > Cancel </button> <button type="submit" class="pi-btn pi-btn-primary" id="productImageSubmit" > <i class="fa-solid fa-link"></i> Assign Image </button> </div> </form> </div> </div> <!-- ========================================================= TOAST ========================================================= --> <div class="pi-toast" id="piToast" ></div> <script> /* ========================================================= CONFIG ========================================================= */ const PRODUCT_IMAGE_CSRF = <?= json_encode( $csrfToken ) ?>; /* ========================================================= TOAST ========================================================= */ function showProductImageToast( message, type = 'success' ) { const toast = document.getElementById( 'piToast' ); toast.textContent = message; toast.className = 'pi-toast show ' + type; setTimeout( function () { toast.className = 'pi-toast'; }, 3500 ); } /* ========================================================= MODAL ========================================================= */ function openProductImageModal() { const modal = document.getElementById( 'productImageModal' ); modal.classList.add( 'show' ); document.body.style.overflow = 'hidden'; } function closeProductImageModal() { const modal = document.getElementById( 'productImageModal' ); modal.classList.remove( 'show' ); document.body.style.overflow = ''; const form = document.getElementById( 'productImageForm' ); if (form) { form.reset(); } } /* ========================================================= MODAL OVERLAY ========================================================= */ document .getElementById( 'productImageModal' ) .addEventListener( 'click', function (event) { if ( event.target === this ) { closeProductImageModal(); } } ); /* ========================================================= ESCAPE ========================================================= */ document.addEventListener( 'keydown', function (event) { if ( event.key === 'Escape' ) { closeProductImageModal(); } } ); /* ========================================================= ADD IMAGE ========================================================= */ document .getElementById( 'productImageForm' ) .addEventListener( 'submit', async function (event) { event.preventDefault(); const form = this; const button = document.getElementById( 'productImageSubmit' ); const oldText = button.innerHTML; button.disabled = true; button.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Saving...'; try { const formData = new FormData( form ); const response = await fetch( 'product_image.php', { method: 'POST', body: formData } ); const data = await response.json(); if ( !data.success ) { showProductImageToast( data.message || 'Unable to assign image.', 'error' ); return; } showProductImageToast( data.message || 'Product image assigned successfully.', 'success' ); closeProductImageModal(); setTimeout( function () { window.location.reload(); }, 600 ); } catch (error) { showProductImageToast( 'Something went wrong. Please try again.', 'error' ); } finally { button.disabled = false; button.innerHTML = oldText; } } ); /* ========================================================= REMOVE IMAGE ========================================================= */ async function removeProductImage( relationId ) { if ( !confirm( 'Are you sure you want to remove this image from the product?' ) ) { return; } const formData = new FormData(); formData.append( 'action', 'remove_image' ); formData.append( 'relation_id', relationId ); formData.append( 'csrf_token', PRODUCT_IMAGE_CSRF ); try { const response = await fetch( 'product_image.php', { method: 'POST', body: formData } ); const data = await response.json(); if ( !data.success ) { showProductImageToast( data.message || 'Unable to remove image.', 'error' ); return; } const row = document.getElementById( 'product-image-' + relationId ); if (row) { row.style.opacity = '0'; row.style.transform = 'translateX(15px)'; row.style.transition = '.25s ease'; setTimeout( function () { row.remove(); }, 250 ); } showProductImageToast( data.message || 'Image removed successfully.', 'success' ); setTimeout( function () { window.location.reload(); }, 700 ); } catch (error) { showProductImageToast( 'Something went wrong. Please try again.', 'error' ); } } /* ========================================================= CHANGE ROLE ========================================================= */ async function changeProductImageRole( relationId, select ) { const newRole = select.value; const oldValue = select.getAttribute( 'data-old-value' ) || newRole; const formData = new FormData(); formData.append( 'action', 'change_role' ); formData.append( 'relation_id', relationId ); formData.append( 'media_role', newRole ); formData.append( 'csrf_token', PRODUCT_IMAGE_CSRF ); select.disabled = true; try { const response = await fetch( 'product_image.php', { method: 'POST', body: formData } ); const data = await response.json(); if ( !data.success ) { select.value = oldValue; showProductImageToast( data.message || 'Unable to update image role.', 'error' ); return; } select.setAttribute( 'data-old-value', newRole ); showProductImageToast( data.message || 'Image role updated successfully.', 'success' ); setTimeout( function () { window.location.reload(); }, 600 ); } catch (error) { select.value = oldValue; showProductImageToast( 'Something went wrong.', 'error' ); } finally { select.disabled = false; } } </script>
Save
Cancel