<?php
/*
|--------------------------------------------------------------------------
| Pure Chemical Admin - Service Media Manager
|--------------------------------------------------------------------------
| File: admin/service_media.php
| Table: service_media
|
| Existing tables used:
|   - services
|   - media
|   - service_media
|
| No new table required.
|--------------------------------------------------------------------------
*/

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

/*
|--------------------------------------------------------------------------
| Optional Auth
|--------------------------------------------------------------------------
*/
$authFile = __DIR__ . '/includes/auth.php';

if (file_exists($authFile)) {
    require_once $authFile;

    if (function_exists('requireAdmin')) {
        requireAdmin();
    }
}

/*
|--------------------------------------------------------------------------
| Helpers
|--------------------------------------------------------------------------
*/
if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

/*
|--------------------------------------------------------------------------
| CSRF
|--------------------------------------------------------------------------
*/
$csrfFile = __DIR__ . '/includes/csrf.php';

if (file_exists($csrfFile)) {
    require_once $csrfFile;
}

if (!function_exists('csrf_token')) {
    function csrf_token()
    {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }

        return $_SESSION['csrf_token'];
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field()
    {
        return '<input type="hidden" name="csrf_token" value="' .
            e(csrf_token()) .
            '">';
    }
}

if (!function_exists('verify_csrf')) {
    function verify_csrf()
    {
        $token = $_POST['csrf_token'] ?? '';

        if (
            empty($_SESSION['csrf_token']) ||
            !hash_equals($_SESSION['csrf_token'], $token)
        ) {
            throw new Exception(
                'Invalid security token. Please refresh the page and try again.'
            );
        }
    }
}

/*
|--------------------------------------------------------------------------
| Flash
|--------------------------------------------------------------------------
*/
$success = $_SESSION['service_media_success'] ?? '';
$error   = $_SESSION['service_media_error'] ?? '';

unset(
    $_SESSION['service_media_success'],
    $_SESSION['service_media_error']
);

/*
|--------------------------------------------------------------------------
| ENUM Values
|--------------------------------------------------------------------------
*/
$mediaRoles = [];

try {

    $enumStmt = $pdo->query(
        "SHOW COLUMNS FROM service_media LIKE 'media_role'"
    );

    $enumColumn = $enumStmt->fetch();

    if ($enumColumn && !empty($enumColumn['Type'])) {

        $type = $enumColumn['Type'];

        if (preg_match('/^enum\((.*)\)$/i', $type, $matches)) {

            preg_match_all(
                "/'((?:[^'\\\\]|\\\\.)*)'/",
                $matches[1],
                $enumMatches
            );

            if (!empty($enumMatches[1])) {
                foreach ($enumMatches[1] as $role) {
                    $mediaRoles[] = stripslashes($role);
                }
            }
        }
    }

} catch (Throwable $e) {
    $mediaRoles = [];
}

/*
|--------------------------------------------------------------------------
| Fallback only if ENUM couldn't be read
|--------------------------------------------------------------------------
*/
if (empty($mediaRoles)) {
    $mediaRoles = [
        'image',
        'gallery',
        'video',
        'pdf',
        'document'
    ];
}

/*
|--------------------------------------------------------------------------
| Services
|--------------------------------------------------------------------------
*/
$services = [];

try {

    $stmt = $pdo->query("
        SELECT
            id,
            parent_id,
            name,
            slug,
            status
        FROM services
        ORDER BY sort_order ASC, name ASC
    ");

    $services = $stmt->fetchAll();

} catch (Throwable $e) {
    $services = [];
}

/*
|--------------------------------------------------------------------------
| Service Tree
|--------------------------------------------------------------------------
*/
$serviceTree = [];

foreach ($services as $service) {

    $parentId = !empty($service['parent_id'])
        ? (int)$service['parent_id']
        : 0;

    if (!isset($serviceTree[$parentId])) {
        $serviceTree[$parentId] = [];
    }

    $serviceTree[$parentId][] = $service;
}

/*
|--------------------------------------------------------------------------
| Service Options
|--------------------------------------------------------------------------
*/
function renderServiceOptions(
    $parentId,
    $tree,
    $selectedId = '',
    $level = 0,
    $visited = []
) {

    if (empty($tree[$parentId])) {
        return;
    }

    foreach ($tree[$parentId] as $service) {

        $serviceId = (int)$service['id'];

        if (isset($visited[$serviceId])) {
            continue;
        }

        $visited[$serviceId] = true;

        $prefix = str_repeat('— ', $level);

        $selected =
            ((string)$selectedId === (string)$serviceId)
                ? ' selected'
                : '';

        $statusText =
            ((int)$service['status'] === 1)
                ? ''
                : ' (Inactive)';

        echo '<option value="' . e($serviceId) . '"' . $selected . '>';
        echo e($prefix . $service['name'] . $statusText);
        echo '</option>';

        renderServiceOptions(
            $serviceId,
            $tree,
            $selectedId,
            $level + 1,
            $visited
        );
    }
}

/*
|--------------------------------------------------------------------------
| Selected Service Filter
|--------------------------------------------------------------------------
*/
$selectedService = isset($_GET['service_id'])
    ? (int)$_GET['service_id']
    : 0;

$selectedRole = trim($_GET['role'] ?? '');

$search = trim($_GET['search'] ?? '');

$page = max(
    1,
    (int)($_GET['page'] ?? 1)
);

$perPage = 12;

$offset = ($page - 1) * $perPage;


/*
|--------------------------------------------------------------------------
| Existing media records and secure upload helper
|--------------------------------------------------------------------------
*/
$availableMedia = [];
try {
    $mediaStmt = $pdo->query("
        SELECT id, original_name, file_path, file_type, mime_type
        FROM media
        WHERE status = 1
        ORDER BY id DESC
        LIMIT 500
    ");
    $availableMedia = $mediaStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $availableMedia = [];
}

function saveUploadedMedia(PDO $pdo, array $file): int
{
    if (!isset($file['error']) || $file['error'] === UPLOAD_ERR_NO_FILE) {
        return 0;
    }
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('File upload failed. Please choose the file again.');
    }
    if (($file['size'] ?? 0) <= 0 || $file['size'] > 20 * 1024 * 1024) {
        throw new Exception('File must be smaller than 20 MB.');
    }
    $tmp = $file['tmp_name'] ?? '';
    if (!$tmp || !is_uploaded_file($tmp)) {
        throw new Exception('Invalid uploaded file.');
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($tmp) ?: 'application/octet-stream';
    $allowed = [
        'image/jpeg' => ['jpg', 'image'],
        'image/png' => ['png', 'image'],
        'image/gif' => ['gif', 'image'],
        'image/webp' => ['webp', 'image'],
        'image/avif' => ['avif', 'image'],
        'video/mp4' => ['mp4', 'video'],
        'video/webm' => ['webm', 'video'],
        'video/quicktime' => ['mov', 'video'],
        'audio/mpeg' => ['mp3', 'audio'],
        'audio/wav' => ['wav', 'audio'],
        'audio/ogg' => ['ogg', 'audio'],
        'application/pdf' => ['pdf', 'pdf'],
        'application/msword' => ['doc', 'document'],
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => ['docx', 'document'],
        'application/vnd.ms-excel' => ['xls', 'document'],
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => ['xlsx', 'document'],
        'text/plain' => ['txt', 'document']
    ];
    if (!isset($allowed[$mime])) {
        throw new Exception('Unsupported file type. Upload an image, video, audio, PDF or document.');
    }

    [$extension, $fileType] = $allowed[$mime];
    $original = basename((string)($file['name'] ?? ('upload.' . $extension)));
    $original = mb_substr($original, 0, 255, 'UTF-8');
    $storedName = bin2hex(random_bytes(16)) . '.' . $extension;
    $uploadDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'media';
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) {
        throw new Exception('Could not create uploads/media folder. Check folder permissions.');
    }
    $destination = $uploadDir . DIRECTORY_SEPARATOR . $storedName;
    if (!move_uploaded_file($tmp, $destination)) {
        throw new Exception('Could not save the uploaded file. Check folder permissions.');
    }

    try {
        $insert = $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)
        ");
        $insert->execute([
            ':original_name' => $original,
            ':file_name' => $storedName,
            ':file_path' => 'uploads/media/' . $storedName,
            ':mime_type' => $mime,
            ':file_type' => $fileType,
            ':extension' => $extension,
            ':file_size' => (int)$file['size']
        ]);
        return (int)$pdo->lastInsertId();
    } catch (Throwable $e) {
        if (is_file($destination)) {
            @unlink($destination);
        }
        throw $e;
    }
}

/*
|--------------------------------------------------------------------------
| POST ACTIONS
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    try {

        verify_csrf();

        $action = $_POST['action'] ?? '';

        /*
        |--------------------------------------------------------------------------
        | ADD MEDIA
        |--------------------------------------------------------------------------
        */
        if ($action === 'add') {

            $serviceId = (int)($_POST['service_id'] ?? 0);
            $mediaId   = (int)($_POST['media_id'] ?? 0);
            $uploadedMediaId = saveUploadedMedia($pdo, $_FILES['media_file'] ?? []);
            if ($uploadedMediaId > 0) { $mediaId = $uploadedMediaId; }

            $mediaRole = trim(
                $_POST['media_role'] ?? 'image'
            );

            $externalUrl = trim(
                $_POST['external_url'] ?? ''
            );

            $sortOrder = (int)(
                $_POST['sort_order'] ?? 0
            );

            /*
            |--------------------------------------------------------------------------
            | Validation
            |--------------------------------------------------------------------------
            */

            if ($serviceId <= 0) {
                throw new Exception(
                    'Please select a service.'
                );
            }

            if ($mediaId <= 0) {
                throw new Exception(
                    'Please enter a valid Media ID.'
                );
            }

            if (!in_array($mediaRole, $mediaRoles, true)) {
                throw new Exception(
                    'Invalid media role selected.'
                );
            }

            if ($externalUrl !== '') {

                if (mb_strlen($externalUrl) > 1000) {
                    throw new Exception(
                        'External URL cannot exceed 1000 characters.'
                    );
                }

                if (
                    !filter_var(
                        $externalUrl,
                        FILTER_VALIDATE_URL
                    )
                ) {
                    throw new Exception(
                        'Please enter a valid external URL.'
                    );
                }
            }

            if ($sortOrder < 0) {
                $sortOrder = 0;
            }

            /*
            |--------------------------------------------------------------------------
            | Service Exists
            |--------------------------------------------------------------------------
            */

            $serviceStmt = $pdo->prepare("
                SELECT id
                FROM services
                WHERE id = ?
                LIMIT 1
            ");

            $serviceStmt->execute([
                $serviceId
            ]);

            if (!$serviceStmt->fetch()) {
                throw new Exception(
                    'Selected service does not exist.'
                );
            }

            $mediaCheck = $pdo->prepare("SELECT id FROM media WHERE id = ? AND status = 1 LIMIT 1");
            $mediaCheck->execute([$mediaId]);
            if (!$mediaCheck->fetch()) {
                throw new Exception('Selected media was not found. Choose an existing media item or upload a file.');
            }

            /*
            |--------------------------------------------------------------------------
            | Duplicate Relation
            |--------------------------------------------------------------------------
            */

            $duplicateStmt = $pdo->prepare("
                SELECT id
                FROM service_media
                WHERE service_id = ?
                  AND media_id = ?
                LIMIT 1
            ");

            $duplicateStmt->execute([
                $serviceId,
                $mediaId
            ]);

            if ($duplicateStmt->fetch()) {
                throw new Exception(
                    'This media is already attached to the selected service.'
                );
            }

            /*
            |--------------------------------------------------------------------------
            | Insert
            |--------------------------------------------------------------------------
            */

            $insert = $pdo->prepare("
                INSERT INTO service_media (
                    service_id,
                    media_id,
                    media_role,
                    external_url,
                    sort_order
                ) VALUES (
                    :service_id,
                    :media_id,
                    :media_role,
                    :external_url,
                    :sort_order
                )
            ");

            $insert->execute([
                ':service_id'   => $serviceId,
                ':media_id'     => $mediaId,
                ':media_role'   => $mediaRole,
                ':external_url' =>
                    $externalUrl !== ''
                        ? $externalUrl
                        : null,
                ':sort_order'   => $sortOrder
            ]);

            $_SESSION['service_media_success'] =
                'Service media added successfully.';

            header(
                'Location: service_media.php?service_id=' .
                $serviceId
            );

            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | UPDATE MEDIA
        |--------------------------------------------------------------------------
        */
        if ($action === 'update') {

            $id = (int)($_POST['id'] ?? 0);

            $serviceId = (int)(
                $_POST['service_id'] ?? 0
            );

            $mediaId = (int)(
                $_POST['media_id'] ?? 0
            );
            if ($mediaId <= 0) {
                $currentMediaStmt = $pdo->prepare('SELECT media_id FROM service_media WHERE id = ? LIMIT 1');
                $currentMediaStmt->execute([(int)($_POST['id'] ?? 0)]);
                $mediaId = (int)$currentMediaStmt->fetchColumn();
            }
            $uploadedMediaId = saveUploadedMedia($pdo, $_FILES['media_file'] ?? []);
            if ($uploadedMediaId > 0) { $mediaId = $uploadedMediaId; }

            $mediaRole = trim(
                $_POST['media_role'] ?? 'image'
            );

            $externalUrl = trim(
                $_POST['external_url'] ?? ''
            );

            $sortOrder = (int)(
                $_POST['sort_order'] ?? 0
            );

            if ($id <= 0) {
                throw new Exception(
                    'Invalid media record.'
                );
            }

            if ($serviceId <= 0) {
                throw new Exception(
                    'Please select a service.'
                );
            }

            if ($mediaId <= 0) {
                throw new Exception(
                    'Please enter a valid Media ID.'
                );
            }

            if (!in_array($mediaRole, $mediaRoles, true)) {
                throw new Exception(
                    'Invalid media role selected.'
                );
            }

            if ($externalUrl !== '') {

                if (mb_strlen($externalUrl) > 1000) {
                    throw new Exception(
                        'External URL cannot exceed 1000 characters.'
                    );
                }

                if (
                    !filter_var(
                        $externalUrl,
                        FILTER_VALIDATE_URL
                    )
                ) {
                    throw new Exception(
                        'Please enter a valid external URL.'
                    );
                }
            }

            if ($sortOrder < 0) {
                $sortOrder = 0;
            }

            /*
            |--------------------------------------------------------------------------
            | Record Exists
            |--------------------------------------------------------------------------
            */

            $recordStmt = $pdo->prepare("
                SELECT id
                FROM service_media
                WHERE id = ?
                LIMIT 1
            ");

            $recordStmt->execute([
                $id
            ]);

            if (!$recordStmt->fetch()) {
                throw new Exception(
                    'Media record not found.'
                );
            }

            /*
            |--------------------------------------------------------------------------
            | Service Exists
            |--------------------------------------------------------------------------
            */

            $serviceStmt = $pdo->prepare("
                SELECT id
                FROM services
                WHERE id = ?
                LIMIT 1
            ");

            $serviceStmt->execute([
                $serviceId
            ]);

            if (!$serviceStmt->fetch()) {
                throw new Exception(
                    'Selected service does not exist.'
                );
            }

            $mediaCheck = $pdo->prepare("SELECT id FROM media WHERE id = ? AND status = 1 LIMIT 1");
            $mediaCheck->execute([$mediaId]);
            if (!$mediaCheck->fetch()) {
                throw new Exception('Selected media was not found. Choose an existing media item or upload a file.');
            }

            /*
            |--------------------------------------------------------------------------
            | Duplicate Relation Except Current
            |--------------------------------------------------------------------------
            */

            $duplicateStmt = $pdo->prepare("
                SELECT id
                FROM service_media
                WHERE service_id = ?
                  AND media_id = ?
                  AND id != ?
                LIMIT 1
            ");

            $duplicateStmt->execute([
                $serviceId,
                $mediaId,
                $id
            ]);

            if ($duplicateStmt->fetch()) {
                throw new Exception(
                    'This media is already attached to this service.'
                );
            }

            /*
            |--------------------------------------------------------------------------
            | Update
            |--------------------------------------------------------------------------
            */

            $update = $pdo->prepare("
                UPDATE service_media
                SET
                    service_id = :service_id,
                    media_id = :media_id,
                    media_role = :media_role,
                    external_url = :external_url,
                    sort_order = :sort_order
                WHERE id = :id
                LIMIT 1
            ");

            $update->execute([
                ':service_id'   => $serviceId,
                ':media_id'     => $mediaId,
                ':media_role'   => $mediaRole,
                ':external_url' =>
                    $externalUrl !== ''
                        ? $externalUrl
                        : null,
                ':sort_order'   => $sortOrder,
                ':id'           => $id
            ]);

            $_SESSION['service_media_success'] =
                'Service media updated successfully.';

            header(
                'Location: service_media.php?service_id=' .
                $serviceId
            );

            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | DELETE
        |--------------------------------------------------------------------------
        */
        if ($action === 'delete') {

            $id = (int)(
                $_POST['id'] ?? 0
            );

            if ($id <= 0) {
                throw new Exception(
                    'Invalid media record.'
                );
            }

            $delete = $pdo->prepare("
                DELETE FROM service_media
                WHERE id = ?
                LIMIT 1
            ");

            $delete->execute([
                $id
            ]);

            $_SESSION['service_media_success'] =
                'Service media removed successfully.';

            header(
                'Location: service_media.php'
            );

            exit;
        }

    } catch (Throwable $e) {

        $error = $e->getMessage();
    }
}

/*
|--------------------------------------------------------------------------
| Edit Record
|--------------------------------------------------------------------------
*/
$editId = isset($_GET['edit'])
    ? (int)$_GET['edit']
    : 0;

$editRecord = null;

if ($editId > 0) {

    try {

        $stmt = $pdo->prepare("
            SELECT
                sm.id,
                sm.service_id,
                sm.media_id,
                sm.media_role,
                sm.external_url,
                sm.sort_order,
                s.name AS service_name,
                m.original_name,
                m.file_path,
                m.file_type
            FROM service_media sm
            LEFT JOIN services s
                ON s.id = sm.service_id
            LEFT JOIN media m
                ON m.id = sm.media_id
            WHERE sm.id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $editId
        ]);

        $editRecord = $stmt->fetch();

        if (!$editRecord) {

            $error =
                'The selected media record could not be found.';

            $editId = 0;
        }

    } catch (Throwable $e) {

        $error = $e->getMessage();
        $editId = 0;
    }
}

/*
|--------------------------------------------------------------------------
| Statistics
|--------------------------------------------------------------------------
*/
$totalMedia = 0;
$imageCount = 0;
$galleryCount = 0;
$videoCount = 0;
$documentCount = 0;

try {

    $totalMedia = (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM service_media
        ")
        ->fetchColumn();

    $imageCount = (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM service_media
            WHERE media_role = 'image'
        ")
        ->fetchColumn();

    $galleryCount = (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM service_media
            WHERE media_role = 'gallery'
        ")
        ->fetchColumn();

    $videoCount = (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM service_media
            WHERE media_role = 'video'
        ")
        ->fetchColumn();

    $documentCount = (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM service_media
            WHERE media_role IN ('pdf', 'document')
        ")
        ->fetchColumn();

} catch (Throwable $e) {
    // Keep statistics at zero if unavailable.
}

/*
|--------------------------------------------------------------------------
| WHERE Conditions
|--------------------------------------------------------------------------
*/
$where = [];
$params = [];

if ($selectedService > 0) {

    $where[] = 'sm.service_id = ?';
    $params[] = $selectedService;
}

if ($selectedRole !== '') {

    $where[] = 'sm.media_role = ?';
    $params[] = $selectedRole;
}

if ($search !== '') {

    $where[] = "
        (
            s.name LIKE ?
            OR sm.media_id LIKE ?
            OR sm.external_url LIKE ?
        )
    ";

    $searchLike = '%' . $search . '%';

    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

/*
|--------------------------------------------------------------------------
| Total Filtered
|--------------------------------------------------------------------------
*/
$filteredTotal = 0;

try {

    $countSql = "
        SELECT COUNT(*)
        FROM service_media sm
        LEFT JOIN services s
            ON s.id = sm.service_id
        {$whereSql}
    ";

    $countStmt = $pdo->prepare($countSql);

    $countStmt->execute($params);

    $filteredTotal = (int)$countStmt->fetchColumn();

} catch (Throwable $e) {

    $filteredTotal = 0;
}

/*
|--------------------------------------------------------------------------
| Pagination
|--------------------------------------------------------------------------
*/
$totalPages = max(
    1,
    (int)ceil($filteredTotal / $perPage)
);

if ($page > $totalPages) {
    $page = $totalPages;
    $offset = ($page - 1) * $perPage;
}

/*
|--------------------------------------------------------------------------
| Media List
|--------------------------------------------------------------------------
*/
$mediaRows = [];

try {

    $sql = "
        SELECT
            sm.id,
            sm.service_id,
            sm.media_id,
            sm.media_role,
            sm.external_url,
            sm.sort_order,
            s.name AS service_name,
            s.slug AS service_slug,
            m.original_name,
            m.file_path,
            m.file_type
        FROM service_media sm
        LEFT JOIN services s
            ON s.id = sm.service_id
        LEFT JOIN media m
            ON m.id = sm.media_id
        {$whereSql}
        ORDER BY
            sm.sort_order ASC,
            sm.id DESC
        LIMIT {$perPage}
        OFFSET {$offset}
    ";

    $stmt = $pdo->prepare($sql);

    $stmt->execute($params);

    $mediaRows = $stmt->fetchAll();

} catch (Throwable $e) {

    $error = $error ?: $e->getMessage();
}

/*
|--------------------------------------------------------------------------
| URL Helper
|--------------------------------------------------------------------------
*/
function buildMediaUrl($overrides = [])
{
    $query = [
        'search'    => $_GET['search'] ?? '',
        'service_id'=> $_GET['service_id'] ?? '',
        'role'      => $_GET['role'] ?? '',
        'page'      => $_GET['page'] ?? 1,
        'edit'      => $_GET['edit'] ?? ''
    ];

    foreach ($overrides as $key => $value) {

        if ($value === null || $value === '') {
            unset($query[$key]);
        } else {
            $query[$key] = $value;
        }
    }

    return 'service_media.php?' . http_build_query($query);
}

/*
|--------------------------------------------------------------------------
| Admin
|--------------------------------------------------------------------------
*/
$adminName =
    $_SESSION['ADMIN_NAME']
    ?? $_SESSION['admin_name']
    ?? $_SESSION['name']
    ?? 'Administrator';

$adminInitial = strtoupper(
    mb_substr(trim($adminName), 0, 1, 'UTF-8')
);

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>Service Media | Pure Chemical Admin</title>

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>

        :root {

            --primary: #2563eb;
            --primary-dark: #1d4ed8;
            --primary-soft: #eff6ff;

            --success: #16a34a;
            --danger: #dc2626;
            --warning: #d97706;
            --purple: #7c3aed;

            --text: #172033;
            --muted: #667085;

            --border: #e7eaf0;
            --bg: #f5f7fb;
            --white: #fff;

            --sidebar-width: 280px;

            --radius: 18px;

            --shadow-sm:
                0 2px 10px rgba(16, 24, 40, .045);

            --shadow:
                0 14px 40px rgba(16, 24, 40, .075);
        }

        * {
            box-sizing: border-box;
        }

        body {

            margin: 0;

            background: var(--bg);

            color: var(--text);

            font-family:
                Inter,
                -apple-system,
                BlinkMacSystemFont,
                "Segoe UI",
                Roboto,
                Arial,
                sans-serif;
        }

        a {
            text-decoration: none;
            color: inherit;
        }

        button,
        input,
        select {
            font: inherit;
        }

        /* =========================================================
           WRAPPER
        ========================================================= */

        .page-wrapper {

            margin-left: var(--sidebar-width);

            min-height: 100vh;
        }

        /* =========================================================
           TOPBAR
        ========================================================= */

        .topbar {

            height: 78px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            padding: 0 32px;

            background:
                rgba(255, 255, 255, .94);

            border-bottom:
                1px solid var(--border);

            position: sticky;

            top: 0;

            z-index: 50;

            backdrop-filter:
                blur(16px);
        }

        .topbar-left {

            display: flex;

            align-items: center;

            gap: 15px;
        }

        .page-icon {

            width: 46px;
            height: 46px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 14px;

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #2563eb,
                    #4f46e5
                );

            box-shadow:
                0 9px 22px
                rgba(37, 99, 235, .22);
        }

        .topbar-title {

            margin: 0;

            font-size: 18px;

            font-weight: 800;

            letter-spacing: -.3px;
        }

        .breadcrumb {

            display: flex;

            align-items: center;

            gap: 8px;

            margin-top: 3px;

            font-size: 11px;

            color: var(--muted);
        }

        .breadcrumb i {
            font-size: 8px;
        }

        .topbar-right {

            display: flex;

            align-items: center;

            gap: 12px;
        }

        .admin-profile {

            display: flex;

            align-items: center;

            gap: 10px;

            padding:
                6px 12px 6px 6px;

            border:
                1px solid var(--border);

            background: #fff;

            border-radius: 50px;
        }

        .admin-avatar {

            width: 37px;
            height: 37px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 50%;

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #111827,
                    #374151
                );

            font-size: 13px;

            font-weight: 800;
        }

        .admin-name {

            font-size: 12px;

            font-weight: 750;
        }

        .admin-role {

            color: var(--muted);

            font-size: 10px;

            margin-top: 2px;
        }

        /* =========================================================
           MAIN
        ========================================================= */

        .main-content {

            padding: 30px;

            max-width: 1550px;

            margin: auto;
        }

        .page-heading {

            display: flex;

            align-items: flex-end;

            justify-content: space-between;

            gap: 20px;

            margin-bottom: 24px;
        }

        .page-heading h1 {

            margin: 0;

            font-size: 28px;

            font-weight: 850;

            letter-spacing: -.8px;
        }

        .page-heading p {

            margin: 7px 0 0;

            color: var(--muted);

            font-size: 13px;
        }

        .add-btn {

            display: inline-flex;

            align-items: center;

            gap: 8px;

            padding: 12px 17px;

            color: #fff;

            border-radius: 11px;

            background:
                linear-gradient(
                    135deg,
                    #2563eb,
                    #4f46e5
                );

            box-shadow:
                0 8px 20px
                rgba(37, 99, 235, .2);

            font-size: 12px;

            font-weight: 750;
        }

        .add-btn:hover {
            transform: translateY(-1px);
        }

        /* =========================================================
           ALERT
        ========================================================= */

        .alert {

            display: flex;

            align-items: flex-start;

            gap: 11px;

            padding: 14px 16px;

            border-radius: 13px;

            margin-bottom: 20px;

            font-size: 12px;

            line-height: 1.6;
        }

        .alert-success {

            background: #ecfdf3;

            border:
                1px solid #bbf7d0;

            color: #166534;
        }

        .alert-danger {

            background: #fef2f2;

            border:
                1px solid #fecaca;

            color: #991b1b;
        }

        /* =========================================================
           STAT CARDS
        ========================================================= */

        .stats-grid {

            display: grid;

            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 15px;

            margin-bottom: 20px;
        }

        .stat-card {

            padding: 18px;

            background: #fff;

            border:
                1px solid var(--border);

            border-radius: 16px;

            box-shadow: var(--shadow-sm);

            display: flex;

            align-items: center;

            justify-content: space-between;
        }

        .stat-label {

            color: var(--muted);

            font-size: 11px;

            font-weight: 650;
        }

        .stat-value {

            margin-top: 5px;

            font-size: 24px;

            font-weight: 850;

            letter-spacing: -.6px;
        }

        .stat-icon {

            width: 42px;
            height: 42px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 12px;

            font-size: 15px;
        }

        .stat-blue {

            background: #eff6ff;

            color: #2563eb;
        }

        .stat-green {

            background: #ecfdf3;

            color: #16a34a;
        }

        .stat-purple {

            background: #f5f3ff;

            color: #7c3aed;
        }

        .stat-orange {

            background: #fff7ed;

            color: #ea580c;
        }

        /* =========================================================
           CARD
        ========================================================= */

        .card {

            background: #fff;

            border:
                1px solid var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow-sm);

            overflow: hidden;
        }

        /* =========================================================
           FILTER BAR
        ========================================================= */

        .filter-bar {

            padding: 18px;

            display: grid;

            grid-template-columns:
                minmax(200px, 1.3fr)
                minmax(180px, .8fr)
                minmax(150px, .6fr)
                auto;

            gap: 10px;

            border-bottom:
                1px solid var(--border);

            background: #fcfdff;
        }

        .input-wrap {
            position: relative;
        }

        .input-icon {

            position: absolute;

            left: 13px;

            top: 50%;

            transform:
                translateY(-50%);

            color: #98a2b3;

            font-size: 12px;

            pointer-events: none;
        }

        .form-control {

            width: 100%;

            min-height: 43px;

            padding: 10px 12px;

            border:
                1px solid #dfe3ea;

            border-radius: 10px;

            background: #fff;

            color: var(--text);

            outline: none;

            font-size: 12px;

            transition: .2s ease;
        }

        .input-wrap .form-control {
            padding-left: 37px;
        }

        .form-control:focus {

            border-color:
                var(--primary);

            box-shadow:
                0 0 0 4px
                rgba(37, 99, 235, .08);
        }

        .filter-btn {

            min-height: 43px;

            padding: 0 16px;

            border: 0;

            border-radius: 10px;

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #2563eb,
                    #4f46e5
                );

            cursor: pointer;

            font-size: 12px;

            font-weight: 750;
        }

        .reset-btn {

            display: inline-flex;

            align-items: center;

            justify-content: center;

            gap: 7px;

            min-height: 43px;

            padding: 0 15px;

            border:
                1px solid #dfe3ea;

            border-radius: 10px;

            background: #fff;

            color: #475467;

            font-size: 12px;

            font-weight: 700;
        }

        /* =========================================================
           TABLE HEADER
        ========================================================= */

        .table-header {

            padding: 19px 21px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;

            border-bottom:
                1px solid var(--border);
        }

        .table-title {

            display: flex;

            align-items: center;

            gap: 10px;
        }

        .table-title-icon {

            width: 35px;
            height: 35px;

            display: flex;

            align-items: center;

            justify-content: center;

            background:
                var(--primary-soft);

            color: var(--primary);

            border-radius: 9px;

            font-size: 13px;
        }

        .table-title h2 {

            margin: 0;

            font-size: 14px;

            font-weight: 800;
        }

        .table-title p {

            margin: 3px 0 0;

            color: var(--muted);

            font-size: 10px;
        }

        .record-count {

            padding: 7px 10px;

            border-radius: 8px;

            background: #f8fafc;

            color: #667085;

            font-size: 10px;

            font-weight: 700;
        }

        /* =========================================================
           TABLE
        ========================================================= */

        .table-scroll {
            overflow-x: auto;
        }

        table {

            width: 100%;

            border-collapse: collapse;

            min-width: 920px;
        }

        thead th {

            padding:
                12px 16px;

            background: #f8fafc;

            border-bottom:
                1px solid var(--border);

            text-align: left;

            color: #667085;

            font-size: 10px;

            text-transform: uppercase;

            letter-spacing: .45px;

            font-weight: 800;
        }

        tbody td {

            padding:
                15px 16px;

            border-bottom:
                1px solid #f0f2f5;

            vertical-align: middle;

            font-size: 12px;
        }

        tbody tr {

            transition: .18s ease;
        }

        tbody tr:hover {

            background:
                #fbfdff;
        }

        tbody tr:last-child td {
            border-bottom: 0;
        }

        .id-badge {

            display: inline-flex;

            align-items: center;

            justify-content: center;

            min-width: 35px;

            padding: 6px 8px;

            border-radius: 7px;

            background: #f8fafc;

            border:
                1px solid #edf0f4;

            color: #667085;

            font-size: 10px;

            font-weight: 800;
        }

        .service-cell {

            display: flex;

            align-items: center;

            gap: 10px;
        }

        .service-icon {

            width: 36px;
            height: 36px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 10px;

            background:
                linear-gradient(
                    135deg,
                    #eff6ff,
                    #eef2ff
                );

            color: #2563eb;

            font-size: 13px;
        }

        .service-name {

            font-weight: 750;

            color: #1f2937;
        }

        .service-slug {

            margin-top: 3px;

            color: #98a2b3;

            font-size: 10px;
        }

        .media-id {

            display: inline-flex;

            align-items: center;

            gap: 5px;

            color: #344054;

            font-weight: 750;
        }

        .media-id i {
            color: #98a2b3;
            font-size: 10px;
        }

        .role-badge {

            display: inline-flex;

            align-items: center;

            gap: 6px;

            padding: 6px 9px;

            border-radius: 7px;

            font-size: 10px;

            font-weight: 750;

            background: #f8fafc;

            color: #475467;

            border:
                1px solid #edf0f4;

            text-transform: capitalize;
        }

        .role-image {
            background: #eff6ff;
            color: #2563eb;
        }

        .role-gallery {
            background: #f5f3ff;
            color: #7c3aed;
        }

        .role-video {
            background: #fef2f2;
            color: #dc2626;
        }

        .role-pdf,
        .role-document {
            background: #fff7ed;
            color: #c2410c;
        }

        .url-cell {

            max-width: 240px;

            color: #667085;

            font-size: 10px;

            white-space: nowrap;

            overflow: hidden;

            text-overflow: ellipsis;
        }

        .sort-badge {

            display: inline-flex;

            width: 28px;
            height: 28px;

            align-items: center;

            justify-content: center;

            border-radius: 8px;

            background: #f8fafc;

            color: #667085;

            font-size: 10px;

            font-weight: 800;
        }

        /* =========================================================
           ACTIONS
        ========================================================= */

        .actions {

            display: flex;

            align-items: center;

            gap: 6px;
        }

        .action-btn {

            width: 34px;
            height: 34px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            border-radius: 9px;

            border:
                1px solid #e7eaf0;

            background: #fff;

            cursor: pointer;

            font-size: 11px;

            transition: .2s ease;
        }

        .edit-btn {
            color: #2563eb;
        }

        .edit-btn:hover {

            background: #eff6ff;

            border-color: #bfdbfe;
        }

        .delete-btn {
            color: #dc2626;
        }

        .delete-btn:hover {

            background: #fef2f2;

            border-color: #fecaca;
        }

        /* =========================================================
           EMPTY
        ========================================================= */

        .empty-state {

            padding: 70px 20px;

            text-align: center;
        }

        .empty-icon {

            width: 66px;
            height: 66px;

            margin:
                0 auto 15px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 18px;

            background: #eff6ff;

            color: #2563eb;

            font-size: 23px;
        }

        .empty-state h3 {

            margin: 0;

            font-size: 15px;

            font-weight: 800;
        }

        .empty-state p {

            margin: 7px auto 0;

            max-width: 430px;

            color: var(--muted);

            font-size: 11px;

            line-height: 1.6;
        }

        /* =========================================================
           PAGINATION
        ========================================================= */

        .pagination {

            padding: 17px 20px;

            border-top:
                1px solid var(--border);

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;
        }

        .pagination-info {

            color: var(--muted);

            font-size: 10px;
        }

        .pagination-links {

            display: flex;

            align-items: center;

            gap: 5px;
        }

        .page-link {

            min-width: 34px;
            height: 34px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            border:
                1px solid var(--border);

            border-radius: 8px;

            background: #fff;

            color: #475467;

            font-size: 10px;

            font-weight: 700;
        }

        .page-link.active {

            color: #fff;

            border-color:
                var(--primary);

            background:
                var(--primary);
        }

        .page-link:hover:not(.active) {

            border-color:
                #cbd5e1;

            background:
                #f8fafc;
        }

        /* =========================================================
           MODAL
        ========================================================= */

        .modal-overlay {

            position: fixed;

            inset: 0;

            z-index: 100;

            display: none;

            align-items: center;

            justify-content: center;

            padding: 20px;

            background:
                rgba(15, 23, 42, .52);

            backdrop-filter:
                blur(7px);
        }

        .modal-overlay.show {
            display: flex;
        }

        .modal {

            width: 100%;

            max-width: 650px;

            max-height:
                calc(100vh - 40px);

            overflow-y: auto;

            background: #fff;

            border-radius: 20px;

            box-shadow:
                0 30px 80px
                rgba(15, 23, 42, .25);

            animation:
                modalIn .2s ease;
        }

        @keyframes modalIn {

            from {
                opacity: 0;
                transform: translateY(10px) scale(.98);
            }

            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .modal-header {

            padding: 20px 22px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            border-bottom:
                1px solid var(--border);
        }

        .modal-heading {

            display: flex;

            align-items: center;

            gap: 11px;
        }

        .modal-heading-icon {

            width: 38px;
            height: 38px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 10px;

            background: var(--primary-soft);

            color: var(--primary);
        }

        .modal-header h2 {

            margin: 0;

            font-size: 16px;

            font-weight: 800;
        }

        .modal-header p {

            margin: 3px 0 0;

            color: var(--muted);

            font-size: 10px;
        }

        .modal-close {

            width: 35px;
            height: 35px;

            border:
                1px solid var(--border);

            background: #fff;

            border-radius: 9px;

            cursor: pointer;

            color: #667085;
        }

        .modal-body {
            padding: 22px;
        }

        .modal-grid {

            display: grid;

            grid-template-columns:
                repeat(2, minmax(0, 1fr));

            gap: 17px;
        }

        .modal-group.full {
            grid-column: 1 / -1;
        }

        .field-help {
            display: block;
            margin-top: 6px;
            color: #667085;
            font-size: 10px;
            line-height: 1.5;
        }

        .media-file-input {
            min-height: 46px;
            padding: 9px;
            background: #f8fafc;
        }

        .modal-label {

            display: block;

            margin-bottom: 7px;

            color: #344054;

            font-size: 11px;

            font-weight: 750;
        }

        .modal-footer {

            padding: 17px 22px;

            display: flex;

            align-items: center;

            justify-content: flex-end;

            gap: 9px;

            background: #fbfcfe;

            border-top:
                1px solid var(--border);
        }

        .btn {

            min-height: 42px;

            padding: 10px 16px;

            border-radius: 10px;

            border:
                1px solid transparent;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            gap: 8px;

            cursor: pointer;

            font-size: 11px;

            font-weight: 750;
        }

        .btn-secondary {

            color: #475467;

            background: #fff;

            border-color:
                #dfe3ea;
        }

        .btn-primary {

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #2563eb,
                    #4f46e5
                );
        }

        /* =========================================================
           FOOTER
        ========================================================= */

        .page-footer {

            padding:
                23px 30px 30px;

            color: #98a2b3;

            text-align: center;

            font-size: 10px;
        }

        /* =========================================================
           RESPONSIVE
        ========================================================= */

        @media (max-width: 1150px) {

            .stats-grid {

                grid-template-columns:
                    repeat(2, 1fr);
            }

            .filter-bar {

                grid-template-columns:
                    1fr 1fr;
            }

        }

        @media (max-width: 1000px) {

            .page-wrapper {
                margin-left: 0;
            }

            .main-content {
                padding: 22px;
            }

            .topbar {
                padding: 0 20px;
            }

        }

        @media (max-width: 700px) {

            .topbar {
                height: 68px;
            }

            .page-icon {

                width: 40px;
                height: 40px;
            }

            .breadcrumb {
                display: none;
            }

            .admin-info {
                display: none;
            }

            .page-heading {

                align-items: flex-start;

                flex-direction: column;
            }

            .page-heading h1 {
                font-size: 23px;
            }

            .add-btn {
                width: 100%;
            }

            .stats-grid {

                grid-template-columns:
                    1fr 1fr;
            }

            .filter-bar {

                grid-template-columns: 1fr;
            }

            .pagination {

                align-items: flex-start;

                flex-direction: column;
            }

            .pagination-links {
                flex-wrap: wrap;
            }

            .modal-grid {
                grid-template-columns: 1fr;
            }

            .modal-group.full {
                grid-column: auto;
            }

        }

        @media (max-width: 450px) {

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .main-content {
                padding: 16px;
            }

        }

    </style>

</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| EXISTING SIDEBAR
|--------------------------------------------------------------------------
*/
require_once __DIR__ . '/sidebar.php';
?>

<div class="page-wrapper">

    <!-- =========================================================
         TOPBAR
    ========================================================== -->

    <header class="topbar">

        <div class="topbar-left">

            <div class="page-icon">
                <i class="fa-solid fa-photo-film"></i>
            </div>

            <div>

                <h1 class="topbar-title">
                    Service Media
                </h1>

                <div class="breadcrumb">

                    <span>Admin</span>

                    <i class="fa-solid fa-chevron-right"></i>

                    <span>Services</span>

                    <i class="fa-solid fa-chevron-right"></i>

                    <strong>Media</strong>

                </div>

            </div>

        </div>


        <div class="topbar-right">

            <div class="admin-profile">

                <div class="admin-avatar">
                    <?= e($adminInitial) ?>
                </div>

                <div>

                    <div class="admin-name">
                        <?= e($adminName) ?>
                    </div>

                    <div class="admin-role">
                        Administrator
                    </div>

                </div>

            </div>

        </div>

    </header>


    <!-- =========================================================
         MAIN
    ========================================================== -->

    <main class="main-content">

        <div class="page-heading">

            <div>

                <h1>
                    Service Media
                </h1>

                <p>
                    Manage images, galleries, videos and documents connected to services.
                </p>

            </div>


            <button
                type="button"
                class="add-btn"
                onclick="openAddModal()"
            >
                <i class="fa-solid fa-plus"></i>
                Add Service Media
            </button>

        </div>


        <!-- =====================================================
             ALERTS
        ====================================================== -->

        <?php if ($success): ?>

            <div class="alert alert-success">

                <i class="fa-solid fa-circle-check"></i>

                <div>
                    <?= e($success) ?>
                </div>

            </div>

        <?php endif; ?>


        <?php if ($error): ?>

            <div class="alert alert-danger">

                <i class="fa-solid fa-circle-exclamation"></i>

                <div>
                    <?= e($error) ?>
                </div>

            </div>

        <?php endif; ?>


        <!-- =====================================================
             STATS
        ====================================================== -->

        <div class="stats-grid">

            <div class="stat-card">

                <div>

                    <div class="stat-label">
                        Total Media
                    </div>

                    <div class="stat-value">
                        <?= number_format($totalMedia) ?>
                    </div>

                </div>

                <div class="stat-icon stat-blue">
                    <i class="fa-solid fa-photo-film"></i>
                </div>

            </div>


            <div class="stat-card">

                <div>

                    <div class="stat-label">
                        Images
                    </div>

                    <div class="stat-value">
                        <?= number_format($imageCount) ?>
                    </div>

                </div>

                <div class="stat-icon stat-green">
                    <i class="fa-regular fa-image"></i>
                </div>

            </div>


            <div class="stat-card">

                <div>

                    <div class="stat-label">
                        Galleries
                    </div>

                    <div class="stat-value">
                        <?= number_format($galleryCount) ?>
                    </div>

                </div>

                <div class="stat-icon stat-purple">
                    <i class="fa-solid fa-images"></i>
                </div>

            </div>


            <div class="stat-card">

                <div>

                    <div class="stat-label">
                        Video / Documents
                    </div>

                    <div class="stat-value">
                        <?= number_format($videoCount + $documentCount) ?>
                    </div>

                </div>

                <div class="stat-icon stat-orange">
                    <i class="fa-solid fa-file-lines"></i>
                </div>

            </div>

        </div>


        <!-- =====================================================
             MAIN CARD
        ====================================================== -->

        <div class="card">

            <!-- =================================================
                 FILTER
            ================================================== -->

            <form
                method="GET"
                class="filter-bar"
            >

                <div class="input-wrap">

                    <i class="fa-solid fa-magnifying-glass input-icon"></i>

                    <input
                        type="text"
                        name="search"
                        class="form-control"
                        value="<?= e($search) ?>"
                        placeholder="Search service, media ID or URL..."
                    >

                </div>


                <select
                    name="service_id"
                    class="form-control"
                >

                    <option value="">
                        All Services
                    </option>

                    <?php
                    renderServiceOptions(
                        0,
                        $serviceTree,
                        $selectedService
                    );
                    ?>

                </select>


                <select
                    name="role"
                    class="form-control"
                >

                    <option value="">
                        All Media Roles
                    </option>

                    <?php foreach ($mediaRoles as $role): ?>

                        <option
                            value="<?= e($role) ?>"
                            <?= $selectedRole === $role ? 'selected' : '' ?>
                        >
                            <?= e(ucfirst($role)) ?>
                        </option>

                    <?php endforeach; ?>

                </select>


                <div style="display:flex;gap:8px;">

                    <button
                        type="submit"
                        class="filter-btn"
                    >
                        <i class="fa-solid fa-filter"></i>
                        Filter
                    </button>

                    <a
                        href="service_media.php"
                        class="reset-btn"
                    >
                        <i class="fa-solid fa-rotate-left"></i>
                        Reset
                    </a>

                </div>

            </form>


            <!-- =================================================
                 TABLE HEADER
            ================================================== -->

            <div class="table-header">

                <div class="table-title">

                    <div class="table-title-icon">
                        <i class="fa-solid fa-list"></i>
                    </div>

                    <div>

                        <h2>
                            Attached Media
                        </h2>

                        <p>
                            Service media records
                        </p>

                    </div>

                </div>

                <div class="record-count">

                    <?= number_format($filteredTotal) ?>
                    record<?= $filteredTotal == 1 ? '' : 's' ?>

                </div>

            </div>


            <!-- =================================================
                 TABLE
            ================================================== -->

            <?php if (!empty($mediaRows)): ?>

                <div class="table-scroll">

                    <table>

                        <thead>

                            <tr>

                                <th>
                                    ID
                                </th>

                                <th>
                                    Service
                                </th>

                                <th>
                                    Media ID
                                </th>

                                <th>
                                    Role
                                </th>

                                <th>
                                    Media File / URL
                                </th>

                                <th>
                                    Order
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>


                        <tbody>

                            <?php foreach ($mediaRows as $row): ?>

                                <?php

                                $roleClass =
                                    'role-' .
                                    preg_replace(
                                        '/[^a-z0-9_-]/i',
                                        '',
                                        strtolower($row['media_role'])
                                    );

                                $roleIcon = 'fa-file';

                                if ($row['media_role'] === 'image') {
                                    $roleIcon = 'fa-image';
                                } elseif ($row['media_role'] === 'gallery') {
                                    $roleIcon = 'fa-images';
                                } elseif ($row['media_role'] === 'video') {
                                    $roleIcon = 'fa-video';
                                } elseif (
                                    $row['media_role'] === 'pdf' ||
                                    $row['media_role'] === 'document'
                                ) {
                                    $roleIcon = 'fa-file-lines';
                                }

                                ?>

                                <tr>

                                    <!-- ID -->

                                    <td>

                                        <span class="id-badge">
                                            #<?= e($row['id']) ?>
                                        </span>

                                    </td>


                                    <!-- SERVICE -->

                                    <td>

                                        <div class="service-cell">

                                            <div class="service-icon">

                                                <i class="fa-solid fa-layer-group"></i>

                                            </div>

                                            <div>

                                                <div class="service-name">
                                                    <?= e($row['service_name'] ?? 'Unknown Service') ?>
                                                </div>

                                                <?php if (!empty($row['service_slug'])): ?>

                                                    <div class="service-slug">
                                                        /<?= e($row['service_slug']) ?>
                                                    </div>

                                                <?php endif; ?>

                                            </div>

                                        </div>

                                    </td>


                                    <!-- MEDIA ID -->

                                    <td>

                                        <div class="media-id">

                                            <i class="fa-solid fa-photo-film"></i>

                                            #<?= e($row['media_id']) ?>

                                        </div>

                                    </td>


                                    <!-- ROLE -->

                                    <td>

                                        <span
                                            class="role-badge <?= e($roleClass) ?>"
                                        >

                                            <i class="fa-solid <?= e($roleIcon) ?>"></i>

                                            <?= e($row['media_role']) ?>

                                        </span>

                                    </td>


                                    <!-- MEDIA FILE / URL -->

                                    <td>
                                        <?php if (!empty($row['file_path'])): ?>
                                            <a
                                                href="<?= e('../' . ltrim($row['file_path'], '/')) ?>"
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                class="url-cell"
                                                title="<?= e($row['original_name'] ?? $row['file_path']) ?>"
                                                style="display:block;max-width:240px;"
                                            >
                                                <i class="fa-solid fa-file-arrow-up"></i>
                                                <?= e($row['original_name'] ?: basename($row['file_path'])) ?>
                                            </a>
                                            <?php if (!empty($row['external_url'])): ?>
                                                <a href="<?= e($row['external_url']) ?>" target="_blank" rel="noopener noreferrer" class="url-cell" style="display:block;max-width:240px;margin-top:5px;">
                                                    <i class="fa-solid fa-link"></i> External URL
                                                </a>
                                            <?php endif; ?>
                                        <?php elseif (!empty($row['external_url'])): ?>
                                            <a
                                                href="<?= e($row['external_url']) ?>"
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                class="url-cell"
                                                title="<?= e($row['external_url']) ?>"
                                            >
                                                <i class="fa-solid fa-link"></i>
                                                <?= e($row['external_url']) ?>
                                            </a>
                                        <?php else: ?>
                                            <span style="color:#98a2b3;font-size:10px;">Media record #<?= (int)$row['media_id'] ?></span>
                                        <?php endif; ?>
                                    </td>


                                    <!-- ORDER -->

                                    <td>

                                        <span class="sort-badge">
                                            <?= e($row['sort_order']) ?>
                                        </span>

                                    </td>


                                    <!-- ACTIONS -->

                                    <td>

                                        <div class="actions">

                                            <a
                                                href="<?= e(
                                                    buildMediaUrl([
                                                        'edit' => $row['id']
                                                    ])
                                                ) ?>"
                                                class="action-btn edit-btn"
                                                title="Edit"
                                            >
                                                <i class="fa-solid fa-pen"></i>
                                            </a>


                                            <button
                                                type="button"
                                                class="action-btn delete-btn"
                                                title="Delete"
                                                onclick="confirmDelete(<?= (int)$row['id'] ?>)"
                                            >
                                                <i class="fa-solid fa-trash"></i>
                                            </button>

                                        </div>

                                    </td>

                                </tr>

                            <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            <?php else: ?>

                <div class="empty-state">

                    <div class="empty-icon">
                        <i class="fa-solid fa-photo-film"></i>
                    </div>

                    <h3>
                        No service media found
                    </h3>

                    <p>
                        No media records match your current filters.
                        Add a service media record to get started.
                    </p>

                </div>

            <?php endif; ?>


            <!-- =================================================
                 PAGINATION
            ================================================== -->

            <?php if ($filteredTotal > 0): ?>

                <div class="pagination">

                    <div class="pagination-info">

                        Showing

                        <strong>
                            <?= number_format($offset + 1) ?>
                        </strong>

                        to

                        <strong>
                            <?= number_format(
                                min(
                                    $offset + $perPage,
                                    $filteredTotal
                                )
                            ) ?>
                        </strong>

                        of

                        <strong>
                            <?= number_format($filteredTotal) ?>
                        </strong>

                    </div>


                    <div class="pagination-links">

                        <?php if ($page > 1): ?>

                            <a
                                class="page-link"
                                href="<?= e(
                                    buildMediaUrl([
                                        '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
                        );

                        for (
                            $p = $startPage;
                            $p <= $endPage;
                            $p++
                        ):
                        ?>

                            <a
                                class="page-link <?= $p === $page ? 'active' : '' ?>"
                                href="<?= e(
                                    buildMediaUrl([
                                        'page' => $p
                                    ])
                                ) ?>"
                            >
                                <?= $p ?>
                            </a>

                        <?php endfor; ?>


                        <?php if ($page < $totalPages): ?>

                            <a
                                class="page-link"
                                href="<?= e(
                                    buildMediaUrl([
                                        'page' => $page + 1
                                    ])
                                ) ?>"
                            >
                                <i class="fa-solid fa-chevron-right"></i>
                            </a>

                        <?php endif; ?>

                    </div>

                </div>

            <?php endif; ?>

        </div>

    </main>


    <footer class="page-footer">

        © <?= date('Y') ?> Pure Chemical.
        All rights reserved.

    </footer>

</div>


<!-- =============================================================
     ADD MODAL
============================================================== -->

<div
    class="modal-overlay"
    id="addModal"
>

    <div class="modal">

        <div class="modal-header">

            <div class="modal-heading">

                <div class="modal-heading-icon">
                    <i class="fa-solid fa-plus"></i>
                </div>

                <div>

                    <h2>
                        Add Service Media
                    </h2>

                    <p>
                        Upload a file or choose one from the Media Library.
                    </p>

                </div>

            </div>

            <button
                type="button"
                class="modal-close"
                onclick="closeModal('addModal')"
            >
                <i class="fa-solid fa-xmark"></i>
            </button>

        </div>


        <form method="POST" enctype="multipart/form-data">

            <?= csrf_field() ?>

            <input
                type="hidden"
                name="action"
                value="add"
            >

            <div class="modal-body">

                <div class="modal-grid">

                    <!-- SERVICE -->

                    <div class="modal-group full">

                        <label class="modal-label">
                            Service
                        </label>

                        <select
                            name="service_id"
                            class="form-control"
                            required
                        >

                            <option value="">
                                Select Service
                            </option>

                            <?php
                            renderServiceOptions(
                                0,
                                $serviceTree,
                                $selectedService
                            );
                            ?>

                        </select>

                    </div>


                    <!-- MEDIA ID -->

                    <div class="modal-group">

                        <label class="modal-label">
                            Media ID
                        </label>

                        <select name="media_id" class="form-control" id="addMediaSelect">
                            <option value="">Choose existing media (optional if uploading)</option>
                            <?php foreach ($availableMedia as $mediaItem): ?>
                                <option value="<?= (int)$mediaItem['id'] ?>">
                                    #<?= (int)$mediaItem['id'] ?> — <?= e($mediaItem['original_name']) ?> (<?= e($mediaItem['file_type']) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <small class="field-help">Select an item from Media Library, or upload a new file below.</small>
                        <input type="file" name="media_file" class="form-control media-file-input" accept="image/*,video/mp4,video/webm,audio/*,.pdf,.doc,.docx,.xls,.xlsx,.txt" style="margin-top:10px">
                        <small class="field-help">Supported images, videos, audio, PDF and documents. Maximum 20 MB.</small>

                    </div>


                    <!-- ROLE -->

                    <div class="modal-group">

                        <label class="modal-label">
                            Media Role
                        </label>

                        <select
                            name="media_role"
                            class="form-control"
                            required
                        >

                            <?php foreach ($mediaRoles as $role): ?>

                                <option
                                    value="<?= e($role) ?>"
                                    <?= $role === 'image'
                                        ? 'selected'
                                        : '' ?>
                                >
                                    <?= e(ucfirst($role)) ?>
                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <!-- URL -->

                    <div class="modal-group full">

                        <label class="modal-label">
                            External URL
                        </label>

                        <input
                            type="url"
                            name="external_url"
                            class="form-control"
                            maxlength="1000"
                            placeholder="https://example.com/media.jpg"
                        >

                    </div>


                    <!-- SORT -->

                    <div class="modal-group">

                        <label class="modal-label">
                            Sort Order
                        </label>

                        <input
                            type="number"
                            name="sort_order"
                            class="form-control"
                            value="0"
                            min="0"
                            step="1"
                        >

                    </div>

                </div>

            </div>


            <div class="modal-footer">

                <button
                    type="button"
                    class="btn btn-secondary"
                    onclick="closeModal('addModal')"
                >
                    Cancel
                </button>

                <button
                    type="submit"
                    class="btn btn-primary"
                >
                    <i class="fa-solid fa-plus"></i>
                    Add Media
                </button>

            </div>

        </form>

    </div>

</div>


<!-- =============================================================
     EDIT MODAL
============================================================== -->

<?php if ($editRecord): ?>

<div
    class="modal-overlay show"
    id="editModal"
>

    <div class="modal">

        <div class="modal-header">

            <div class="modal-heading">

                <div class="modal-heading-icon">
                    <i class="fa-solid fa-pen"></i>
                </div>

                <div>

                    <h2>
                        Edit Service Media
                    </h2>

                    <p>
                        Update this service media relationship.
                    </p>

                </div>

            </div>

            <a
                href="<?= e(
                    buildMediaUrl([
                        'edit' => null
                    ])
                ) ?>"
                class="modal-close"
                style="
                    display:flex;
                    align-items:center;
                    justify-content:center;
                "
            >
                <i class="fa-solid fa-xmark"></i>
            </a>

        </div>


        <form method="POST" enctype="multipart/form-data">

            <?= csrf_field() ?>

            <input
                type="hidden"
                name="action"
                value="update"
            >

            <input
                type="hidden"
                name="id"
                value="<?= e($editRecord['id']) ?>"
            >

            <div class="modal-body">

                <div class="modal-grid">

                    <!-- SERVICE -->

                    <div class="modal-group full">

                        <label class="modal-label">
                            Service
                        </label>

                        <select
                            name="service_id"
                            class="form-control"
                            required
                        >

                            <option value="">
                                Select Service
                            </option>

                            <?php
                            renderServiceOptions(
                                0,
                                $serviceTree,
                                $editRecord['service_id']
                            );
                            ?>

                        </select>

                    </div>


                    <!-- MEDIA ID -->

                    <div class="modal-group">

                        <label class="modal-label">
                            Media ID
                        </label>

                        <select name="media_id" class="form-control" id="editMediaSelect">
                            <option value="">Keep current media unless uploading a replacement</option>
                            <?php foreach ($availableMedia as $mediaItem): ?>
                                <option value="<?= (int)$mediaItem['id'] ?>" <?= (int)$editRecord['media_id'] === (int)$mediaItem['id'] ? 'selected' : '' ?>>
                                    #<?= (int)$mediaItem['id'] ?> — <?= e($mediaItem['original_name']) ?> (<?= e($mediaItem['file_type']) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <small class="field-help">Choose another library item or upload a replacement file.</small>
                        <input type="file" name="media_file" class="form-control media-file-input" accept="image/*,video/mp4,video/webm,audio/*,.pdf,.doc,.docx,.xls,.xlsx,.txt" style="margin-top:10px">
                        <small class="field-help">If you upload a file, it will replace the selected Media ID for this service.</small>

                    </div>


                    <!-- ROLE -->

                    <div class="modal-group">

                        <label class="modal-label">
                            Media Role
                        </label>

                        <select
                            name="media_role"
                            class="form-control"
                            required
                        >

                            <?php foreach ($mediaRoles as $role): ?>

                                <option
                                    value="<?= e($role) ?>"
                                    <?= $editRecord['media_role'] === $role
                                        ? 'selected'
                                        : '' ?>
                                >
                                    <?= e(ucfirst($role)) ?>
                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <!-- URL -->

                    <div class="modal-group full">

                        <label class="modal-label">
                            External URL
                        </label>

                        <input
                            type="url"
                            name="external_url"
                            class="form-control"
                            maxlength="1000"
                            value="<?= e(
                                $editRecord['external_url']
                            ) ?>"
                            placeholder="https://example.com/media.jpg"
                        >

                    </div>


                    <!-- SORT -->

                    <div class="modal-group">

                        <label class="modal-label">
                            Sort Order
                        </label>

                        <input
                            type="number"
                            name="sort_order"
                            class="form-control"
                            min="0"
                            step="1"
                            value="<?= e(
                                $editRecord['sort_order']
                            ) ?>"
                        >

                    </div>

                </div>

            </div>


            <div class="modal-footer">

                <a
                    href="<?= e(
                        buildMediaUrl([
                            'edit' => null
                        ])
                    ) ?>"
                    class="btn btn-secondary"
                >
                    Cancel
                </a>

                <button
                    type="submit"
                    class="btn btn-primary"
                >
                    <i class="fa-solid fa-check"></i>
                    Save Changes
                </button>

            </div>

        </form>

    </div>

</div>

<?php endif; ?>


<!-- =============================================================
     DELETE FORM
============================================================== -->

<form
    method="POST"
    id="deleteForm"
    style="display:none;"
>

    <?= csrf_field() ?>

    <input
        type="hidden"
        name="action"
        value="delete"
    >

    <input
        type="hidden"
        name="id"
        id="deleteId"
        value=""
    >

</form>


<script>

/*
|--------------------------------------------------------------------------
| Add Modal
|--------------------------------------------------------------------------
*/

function openAddModal() {

    const modal =
        document.getElementById('addModal');

    if (!modal) {
        return;
    }

    modal.classList.add('show');

    document.body.style.overflow = 'hidden';
}


/*
|--------------------------------------------------------------------------
| Close Modal
|--------------------------------------------------------------------------
*/

function closeModal(id) {

    const modal =
        document.getElementById(id);

    if (!modal) {
        return;
    }

    modal.classList.remove('show');

    document.body.style.overflow = '';
}


/*
|--------------------------------------------------------------------------
| Delete Confirmation
|--------------------------------------------------------------------------
*/

function confirmDelete(id) {

    const confirmed = confirm(
        'Are you sure you want to remove this media from the service?\n\n' +
        'This will delete only the service_media relationship. ' +
        'The original media record will not be deleted.'
    );

    if (!confirmed) {
        return;
    }

    document.getElementById('deleteId').value = id;

    document.getElementById('deleteForm').submit();
}


/*
|--------------------------------------------------------------------------
| Close Modal With Overlay
|--------------------------------------------------------------------------
*/

document.addEventListener(
    'click',
    function (event) {

        if (
            event.target.classList.contains(
                'modal-overlay'
            )
        ) {

            const modal =
                event.target;

            modal.classList.remove('show');

            document.body.style.overflow = '';

        }

    }
);


/*
|--------------------------------------------------------------------------
| Escape Key
|--------------------------------------------------------------------------
*/

document.addEventListener(
    'keydown',
    function (event) {

        if (event.key !== 'Escape') {
            return;
        }

        document
            .querySelectorAll('.modal-overlay.show')
            .forEach(function (modal) {

                modal.classList.remove('show');

            });

        document.body.style.overflow = '';

    }
);

</script>

</body>

</html>