
<?php

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (!isset($pdo) || !($pdo instanceof PDO)) {
    exit('Database connection error: includes/db.php mein $pdo connection check karein.');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

error_reporting(E_ALL);
ini_set('display_errors', '1');

/* =========================================================
   PURE CHEMICAL - INDUSTRY MEDIA MANAGER
   Existing tables only: media, industry_media, industries
   ========================================================= */

function im_e(mixed $value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function im_columns(PDO $pdo, string $table): array
{
    $allowed = ['media', 'industry_media', 'industries'];

    if (!in_array($table, $allowed, true)) {
        throw new RuntimeException('Invalid table name.');
    }

    $columns = [];
    foreach ($pdo->query("SHOW COLUMNS FROM `$table`")->fetchAll() as $row) {
        $columns[$row['Field']] = $row;
    }

    return $columns;
}

function im_enum(array $column): array
{
    $type = (string)($column['Type'] ?? '');

    if (!preg_match('/^enum\((.*)\)$/i', $type, $match)) {
        return [];
    }

    preg_match_all("/'((?:[^'\\\\]|\\\\.)*)'/", $match[1], $matches);

    return array_map(
        static fn($v) => stripcslashes($v),
        $matches[1] ?? []
    );
}

function im_enum_choice(array $column, array $preferred): string
{
    $options = im_enum($column);

    foreach ($preferred as $value) {
        if (in_array($value, $options, true)) {
            return $value;
        }
    }

    if ($options) {
        return $options[0];
    }

    throw new RuntimeException('Database ENUM configuration check karein.');
}

function im_csrf(): string
{
    if (empty($_SESSION['im_csrf'])) {
        $_SESSION['im_csrf'] = bin2hex(random_bytes(32));
    }

    return (string)$_SESSION['im_csrf'];
}

function im_check_csrf(): void
{
    $posted = (string)($_POST['csrf_token'] ?? '');
    $saved  = (string)($_SESSION['im_csrf'] ?? '');

    if ($saved === '' || !hash_equals($saved, $posted)) {
        throw new RuntimeException('Security token expire ho gaya. Page refresh karein.');
    }
}

function im_flash(string $type, string $message): void
{
    $_SESSION['im_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}

function im_redirect(): never
{
    header('Location: industry_media.php');
    exit;
}

/* Read the actual existing schema */
try {
    $mediaColumns = im_columns($pdo, 'media');
    $mapColumns = im_columns($pdo, 'industry_media');
    $industryColumns = im_columns($pdo, 'industries');

    foreach (['id', 'original_name', 'file_name', 'file_path',
              'mime_type', 'file_type', 'file_size'] as $col) {
        if (!isset($mediaColumns[$col])) {
            throw new RuntimeException("media table mein `$col` column nahi mila.");
        }
    }

    foreach (['id', 'industry_id', 'media_id', 'media_role',
              'external_url', 'sort_order'] as $col) {
        if (!isset($mapColumns[$col])) {
            throw new RuntimeException("industry_media table mein `$col` column nahi mila.");
        }
    }

    if (!isset($industryColumns['id'])) {
        throw new RuntimeException('industries table mein id column nahi mila.');
    }

    $industryNameCol = null;
    foreach (['name', 'industry_name', 'title', 'label'] as $candidate) {
        if (isset($industryColumns[$candidate])) {
            $industryNameCol = $candidate;
            break;
        }
    }

    if ($industryNameCol === null) {
        throw new RuntimeException(
            'industries table mein name, industry_name, title ya label column chahiye.'
        );
    }
} catch (Throwable $e) {
    http_response_code(500);
    exit(im_e($e->getMessage()));
}

/* Upload into the project's root uploads folder */
function im_save_upload(PDO $pdo, array $columns, array $file): int
{
    if (
        !isset($file['error']) ||
        is_array($file['error']) ||
        (int)$file['error'] !== UPLOAD_ERR_OK
    ) {
        throw new RuntimeException('File select karein aur upload dobara try karein.');
    }

    if ((int)$file['size'] < 1 || (int)$file['size'] > 50 * 1024 * 1024) {
        throw new RuntimeException('File size 1 byte se 50 MB ke beech honi chahiye.');
    }

    $original = basename((string)$file['name']);
    $ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));

    $allowedExtensions = [
        'jpg', 'jpeg', 'png', 'gif', 'webp', 'avif',
        'mp4', 'webm', 'mov', 'pdf',
        'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'csv'
    ];

    if (!in_array($ext, $allowedExtensions, true)) {
        throw new RuntimeException('Ye file extension allowed nahi hai.');
    }

    $tmp = (string)$file['tmp_name'];

    if (!is_uploaded_file($tmp)) {
        throw new RuntimeException('Uploaded file valid nahi hai.');
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = (string)$finfo->file($tmp);

    $mimeMap = [
        'jpg' => ['image/jpeg'],
        'jpeg' => ['image/jpeg'],
        'png' => ['image/png'],
        'gif' => ['image/gif'],
        'webp' => ['image/webp'],
        'avif' => ['image/avif'],
        'mp4' => ['video/mp4', 'application/octet-stream'],
        'webm' => ['video/webm', 'application/octet-stream'],
        'mov' => ['video/quicktime', 'video/mp4', 'application/octet-stream'],
        'pdf' => ['application/pdf'],
        'doc' => ['application/msword', 'application/octet-stream'],
        'docx' => ['application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                   'application/zip', 'application/octet-stream'],
        'xls' => ['application/vnd.ms-excel', 'application/octet-stream'],
        'xlsx' => ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                   'application/zip', 'application/octet-stream'],
        'ppt' => ['application/vnd.ms-powerpoint', 'application/octet-stream'],
        'pptx' => ['application/vnd.openxmlformats-officedocument.presentationml.presentation',
                   'application/zip', 'application/octet-stream'],
        'txt' => ['text/plain', 'application/octet-stream'],
        'csv' => ['text/plain', 'text/csv', 'application/csv', 'application/octet-stream']
    ];

    if (!in_array($mime, $mimeMap[$ext] ?? [], true)) {
        throw new RuntimeException('File ka actual type aur extension match nahi karte.');
    }

    if (str_starts_with($mime, 'image/')) {
        $typePreference = ['image'];
    } elseif (str_starts_with($mime, 'video/')) {
        $typePreference = ['video'];
    } elseif ($ext === 'pdf') {
        $typePreference = ['pdf', 'document'];
    } else {
        $typePreference = ['document'];
    }

    $fileType = im_enum_choice($columns['file_type'], $typePreference);

    $relativeDir = 'uploads/industry-media';
    $rootDir = dirname(__DIR__);
    $absoluteDir = $rootDir . DIRECTORY_SEPARATOR . 'uploads'
        . DIRECTORY_SEPARATOR . 'industry-media';

    if (!is_dir($absoluteDir) &&
        !mkdir($absoluteDir, 0755, true) &&
        !is_dir($absoluteDir)) {
        throw new RuntimeException('Upload folder create nahi ho saka.');
    }

    $newName = bin2hex(random_bytes(16)) . '.' . $ext;
    $destination = $absoluteDir . DIRECTORY_SEPARATOR . $newName;

    if (!move_uploaded_file($tmp, $destination)) {
        throw new RuntimeException('File server par save nahi ho saki.');
    }

    $width = null;
    $height = null;

    if ($fileType === 'image') {
        $dimensions = @getimagesize($destination);
        if ($dimensions !== false) {
            $width = (int)$dimensions[0];
            $height = (int)$dimensions[1];
        }
    }

    $values = [
        'original_name' => mb_substr($original, 0, 255),
        'file_name' => $newName,
        'file_path' => $relativeDir . '/' . $newName,
        'mime_type' => mb_substr($mime, 0, 150),
        'file_type' => $fileType,
        'extension' => $ext,
        'file_size' => (int)filesize($destination),
        'width' => $width,
        'height' => $height,
        'alt_text' => null,
        'title' => mb_substr(pathinfo($original, PATHINFO_FILENAME), 0, 255),
        'caption' => null,
        'thumbnail_path' => null,
        'uploaded_by' => null,
        'status' => 1
    ];

    $insertValues = [];
    foreach ($values as $name => $value) {
        if (isset($columns[$name])) {
            $insertValues[$name] = $value;
        }
    }

    try {
        $names = array_keys($insertValues);
        $quoted = array_map(static fn($n) => "`$n`", $names);
        $marks = array_fill(0, count($names), '?');

        $sql = 'INSERT INTO `media` (' . implode(',', $quoted) .
               ') VALUES (' . implode(',', $marks) . ')';

        $stmt = $pdo->prepare($sql);
        $stmt->execute(array_values($insertValues));

        return (int)$pdo->lastInsertId();
    } catch (Throwable $e) {
        if (is_file($destination)) {
            @unlink($destination);
        }
        throw $e;
    }
}

/* Handle form submissions */
$errorMessage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        im_check_csrf();
        $action = (string)($_POST['action'] ?? '');

        if ($action === 'save') {
            $industryId = filter_var(
                $_POST['industry_id'] ?? null,
                FILTER_VALIDATE_INT
            );
            $sortOrder = filter_var(
                $_POST['sort_order'] ?? 0,
                FILTER_VALIDATE_INT
            );
            $roleRequested = (string)($_POST['media_role'] ?? 'image');
            $externalUrl = trim((string)($_POST['external_url'] ?? ''));

            if (!$industryId || $industryId < 1) {
                throw new RuntimeException('Industry select karein.');
            }

            if ($sortOrder === false || $sortOrder < 0) {
                throw new RuntimeException('Sort order 0 ya usse bada number hona chahiye.');
            }

            $check = $pdo->prepare('SELECT id FROM industries WHERE id = ? LIMIT 1');
            $check->execute([$industryId]);

            if (!$check->fetch()) {
                throw new RuntimeException('Selected industry database mein nahi mili.');
            }

            if ($externalUrl !== '') {
                if (
                    !filter_var($externalUrl, FILTER_VALIDATE_URL) ||
                    !in_array(
                        strtolower((string)parse_url($externalUrl, PHP_URL_SCHEME)),
                        ['http', 'https'],
                        true
                    ) ||
                    mb_strlen($externalUrl) > 1000
                ) {
                    throw new RuntimeException('Valid HTTP/HTTPS URL enter karein (maximum 1000 characters).');
                }
            }

            if (
                !isset($_FILES['media_file']) ||
                (int)($_FILES['media_file']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE
            ) {
                throw new RuntimeException(
                    'File upload karein. Is database mein industry_media.media_id required hai.'
                );
            }

            $roleOptions = im_enum($mapColumns['media_role']);
            if (!in_array($roleRequested, $roleOptions, true)) {
                throw new RuntimeException('Selected media role database ENUM mein allowed nahi hai.');
            }

            $pdo->beginTransaction();

            try {
                $mediaId = im_save_upload($pdo, $mediaColumns, $_FILES['media_file']);

                $stmt = $pdo->prepare(
                    'INSERT INTO `industry_media`
                    (`industry_id`, `media_id`, `media_role`, `external_url`, `sort_order`)
                    VALUES (?, ?, ?, ?, ?)'
                );

                $stmt->execute([
                    (int)$industryId,
                    $mediaId,
                    $roleRequested,
                    $externalUrl !== '' ? $externalUrl : null,
                    (int)$sortOrder
                ]);

                $pdo->commit();
            } catch (Throwable $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                throw $e;
            }

            im_flash('success', 'Media successfully upload aur save ho gaya.');
            im_redirect();
        }

        if ($action === 'delete') {
            $mappingId = filter_var(
                $_POST['mapping_id'] ?? null,
                FILTER_VALIDATE_INT
            );

            if (!$mappingId || $mappingId < 1) {
                throw new RuntimeException('Invalid media mapping ID.');
            }

            $stmt = $pdo->prepare('DELETE FROM industry_media WHERE id = ?');
            $stmt->execute([$mappingId]);

            im_flash('success', 'Industry se media link remove ho gaya. Original file delete nahi hui.');
            im_redirect();
        }

        throw new RuntimeException('Invalid request action.');
    } catch (Throwable $e) {
        $errorMessage = $e->getMessage();
    }
}

/* Page data */
$industries = $pdo->query(
    'SELECT id, `' . $industryNameCol . '` AS industry_name
     FROM industries ORDER BY `' . $industryNameCol . '` ASC'
)->fetchAll();

$search = trim((string)($_GET['q'] ?? ''));
$industryFilter = filter_var($_GET['industry_id'] ?? '', FILTER_VALIDATE_INT);
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 12;

$where = [];
$params = [];

if ($search !== '') {
    $where[] = '(m.original_name LIKE ? OR m.file_name LIKE ? OR m.title LIKE ?)';
    $like = '%' . $search . '%';
    array_push($params, $like, $like, $like);
}

if ($industryFilter && $industryFilter > 0) {
    $where[] = 'im.industry_id = ?';
    $params[] = $industryFilter;
}

$whereSql = $where ? ' WHERE ' . implode(' AND ', $where) : '';

$countStmt = $pdo->prepare(
    'SELECT COUNT(*)
     FROM industry_media im
     INNER JOIN media m ON m.id = im.media_id
     INNER JOIN industries i ON i.id = im.industry_id' . $whereSql
);
$countStmt->execute($params);
$totalRows = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($totalRows / $perPage));
$page = min($page, $totalPages);
$offset = ($page - 1) * $perPage;

$listSql = 'SELECT
        im.id AS mapping_id, im.industry_id, im.media_id,
        im.media_role, im.external_url, im.sort_order,
        m.original_name, m.file_name, m.file_path, m.mime_type,
        m.file_type, m.file_size, m.title,
        i.`' . $industryNameCol . '` AS industry_name
    FROM industry_media im
    INNER JOIN media m ON m.id = im.media_id
    INNER JOIN industries i ON i.id = im.industry_id'
    . $whereSql .
    ' ORDER BY im.sort_order ASC, im.id DESC
      LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset;

$listStmt = $pdo->prepare($listSql);
$listStmt->execute($params);
$items = $listStmt->fetchAll();

$flash = $_SESSION['im_flash'] ?? null;
unset($_SESSION['im_flash']);

$token = im_csrf();
$roleOptions = im_enum($mapColumns['media_role']);
if (!$roleOptions) {
    $roleOptions = ['image', 'gallery', 'video', 'pdf', 'document'];
}

?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Industry Media | Pure Chemical</title>

<style>
:root {
    --im-sidebar-width: 280px;
    --im-bg: #f3f6fb;
    --im-card: #fff;
    --im-text: #172033;
    --im-muted: #738097;
    --im-border: #e3e9f2;
    --im-primary: #315efb;
    --im-primary-dark: #2449d8;
    --im-radius: 17px;
    --im-shadow: 0 8px 28px rgba(24,39,75,.055);
}

* { box-sizing: border-box; }

html { min-width: 320px; }

body {
    margin: 0;
    color: var(--im-text);
    background: var(--im-bg);
    font-family: Inter, "Segoe UI", Arial, sans-serif;
}

/*
  Sidebar is already included by sidebar.php.
  Reserve space for its fixed desktop layout so content does not sit underneath it.
*/
.im-page {
    margin-left: var(--im-sidebar-width);
    width: calc(100% - var(--im-sidebar-width));
    min-width: 0;
    min-height: 100vh;
    padding: 28px;
}

.im-container {
    width: 100%;
    max-width: 1500px;
    min-width: 0;
    margin: 0 auto;
}

.im-heading {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 16px;
    margin-bottom: 23px;
}

.im-heading h1 {
    margin: 0;
    font-size: clamp(24px, 2vw, 32px);
    letter-spacing: -.7px;
    line-height: 1.2;
}

.im-subtitle {
    margin: 8px 0 0;
    color: var(--im-muted);
    font-size: 14px;
    line-height: 1.6;
}

.im-chip {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 9px 13px;
    border-radius: 999px;
    background: #eaf0ff;
    color: #3154c9;
    font-size: 12px;
    font-weight: 750;
}

.im-stats {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 17px;
    margin-bottom: 21px;
}

.im-stat, .im-card {
    min-width: 0;
    background: var(--im-card);
    border: 1px solid var(--im-border);
    border-radius: var(--im-radius);
    box-shadow: var(--im-shadow);
}

.im-stat { padding: 20px 22px; }

.im-stat span {
    display: block;
    color: var(--im-muted);
    font-size: 13px;
}

.im-stat strong {
    display: block;
    margin-top: 9px;
    font-size: 29px;
    line-height: 1.15;
}

.im-card {
    margin-bottom: 22px;
    overflow: hidden;
}

.im-card-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
    padding: 21px 23px;
    border-bottom: 1px solid var(--im-border);
}

.im-card-head h2 {
    margin: 0;
    font-size: 17px;
}

.im-card-body { padding: 23px; }

.im-form-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 21px 24px;
}

.im-field { min-width: 0; }
.im-field-full { grid-column: 1 / -1; }

.im-field label {
    display: block;
    margin-bottom: 9px;
    font-size: 13px;
    font-weight: 700;
}

.im-field input,
.im-field select {
    display: block;
    width: 100%;
    max-width: 100%;
    min-width: 0;
    height: 48px;
    padding: 11px 13px;
    border: 1px solid #dbe3ee;
    border-radius: 11px;
    outline: none;
    color: var(--im-text);
    background: #fff;
    font: inherit;
    font-size: 14px;
    transition: border-color .15s, box-shadow .15s;
}

.im-field input[type="file"] {
    height: auto;
    min-height: 48px;
    padding: 10px;
    background: #fbfcff;
}

.im-field input:focus,
.im-field select:focus {
    border-color: var(--im-primary);
    box-shadow: 0 0 0 3px rgba(49,94,251,.12);
}

.im-help {
    margin-top: 7px;
    color: var(--im-muted);
    font-size: 12px;
    line-height: 1.55;
    overflow-wrap: anywhere;
}

.im-actions {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 22px;
}

.im-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    min-height: 41px;
    padding: 10px 15px;
    border: 1px solid transparent;
    border-radius: 10px;
    cursor: pointer;
    text-decoration: none;
    font: inherit;
    font-size: 13px;
    font-weight: 750;
    line-height: 1.2;
    white-space: normal;
    overflow-wrap: anywhere;
    transition: background .15s, border-color .15s, transform .15s;
}

.im-btn:focus-visible {
    outline: 3px solid rgba(49,94,251,.25);
    outline-offset: 2px;
}

.im-btn-primary { background: var(--im-primary); color: #fff; }
.im-btn-primary:hover { background: var(--im-primary-dark); }
.im-btn-light { background: #fff; color: #344054; border-color: var(--im-border); }
.im-btn-light:hover { background: #f7f9fc; }
.im-btn-danger { background: #fff1f2; color: #b42332; border-color: #ffd5d9; }
.im-btn-danger:hover { background: #ffe5e8; }

.im-alert {
    padding: 14px 16px;
    margin-bottom: 19px;
    border-radius: 12px;
    font-size: 14px;
    line-height: 1.55;
    overflow-wrap: anywhere;
}
.im-alert-success { color: #08744e; background: #e8f8f1; border: 1px solid #c3eedb; }
.im-alert-error { color: #a5222b; background: #fff0f0; border: 1px solid #ffd2d5; }

.im-toolbar {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    padding: 17px 22px;
    border-bottom: 1px solid var(--im-border);
}

.im-toolbar input, .im-toolbar select {
    height: 43px;
    min-width: 0;
    padding: 9px 12px;
    border: 1px solid var(--im-border);
    border-radius: 10px;
    background: #fff;
    font: inherit;
    font-size: 13px;
}

.im-toolbar input { flex: 1 1 220px; }
.im-toolbar select { flex: 0 1 240px; }

.im-table-wrap {
    width: 100%;
    max-width: 100%;
    overflow-x: auto;
}

.im-table {
    width: 100%;
    min-width: 790px;
    border-collapse: collapse;
}

.im-table th {
    padding: 14px 16px;
    background: #f8faff;
    color: #69778e;
    text-align: left;
    text-transform: uppercase;
    letter-spacing: .45px;
    font-size: 11px;
    white-space: nowrap;
}

.im-table td {
    padding: 15px 16px;
    border-top: 1px solid #edf1f6;
    vertical-align: middle;
    font-size: 13px;
}

.im-media-cell {
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 230px;
}

.im-thumb {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 58px;
    height: 52px;
    flex: 0 0 58px;
    overflow: hidden;
    border: 1px solid var(--im-border);
    border-radius: 10px;
    background: #f0f3f8;
    color: #52617a;
    font-size: 10px;
    font-weight: 800;
}

.im-thumb img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.im-file-name {
    max-width: 270px;
    font-weight: 750;
    overflow-wrap: anywhere;
}

.im-muted {
    margin-top: 4px;
    color: var(--im-muted);
    font-size: 12px;
    overflow-wrap: anywhere;
}

.im-tag {
    display: inline-block;
    padding: 5px 8px;
    border-radius: 7px;
    background: #edf2ff;
    color: #3154c9;
    font-size: 11px;
    font-weight: 750;
}

.im-empty {
    padding: 45px 18px;
    color: var(--im-muted);
    text-align: center;
}

.im-pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
    padding: 17px 22px;
    border-top: 1px solid var(--im-border);
    font-size: 13px;
}

.im-pager { display: flex; flex-wrap: wrap; gap: 7px; }

.im-pager a, .im-pager span {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 36px;
    min-height: 35px;
    padding: 7px 10px;
    border: 1px solid var(--im-border);
    border-radius: 8px;
    color: var(--im-text);
    background: #fff;
    text-decoration: none;
}

.im-pager .current {
    color: #fff;
    background: var(--im-primary);
    border-color: var(--im-primary);
}

@media (max-width: 1100px) {
    :root { --im-sidebar-width: 250px; }
    .im-page { padding: 20px; }
    .im-stats { gap: 12px; }
}

@media (max-width: 760px) {
    /*
      Most admin sidebars become a drawer on mobile.
      Content uses full width rather than reserving desktop sidebar space.
    */
    .im-page {
        margin-left: 0;
        width: 100%;
        padding: 16px;
    }

    .im-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }
    .im-form-grid { grid-template-columns: minmax(0, 1fr); }
    .im-field-full { grid-column: auto; }
    .im-card-head, .im-card-body { padding: 17px; }
    .im-toolbar { padding: 14px 16px; }
    .im-toolbar input, .im-toolbar select { flex: 1 1 100%; width: 100%; }
}

@media (max-width: 480px) {
    .im-page { padding: 11px; }
    .im-stats { grid-template-columns: minmax(0, 1fr); }
    .im-heading { align-items: flex-start; }
    .im-card-head { padding: 15px; }
    .im-card-body { padding: 15px; }
    .im-actions .im-btn { flex: 1 1 auto; }
}
</style>
</head>
<body>

<?php
/*
 * Existing sidebar ko hi use karein.
 * Sidebar ki width agar CSS mein alag hai, to neeche diye gaye note ko dekhein.
 */
$sidebarFile = __DIR__ . '/sidebar.php';

if (is_file($sidebarFile)) {
    require $sidebarFile;
}
?>

<main class="im-page">
<div class="im-container">

    <header class="im-heading">
        <div>
            <h1>Industry Media</h1>
            <p class="im-subtitle">Manage industry images, videos, PDFs and documents.</p>
        </div>
        <span class="im-chip">● Prime UI · Media Manager</span>
    </header>

    <section class="im-stats">
        <div class="im-stat">
            <span>Total media links</span>
            <strong><?= number_format($totalRows) ?></strong>
        </div>
        <div class="im-stat">
            <span>Industries available</span>
            <strong><?= number_format(count($industries)) ?></strong>
        </div>
        <div class="im-stat">
            <span>Current page</span>
            <strong><?= $page ?> / <?= $totalPages ?></strong>
        </div>
    </section>

    <?php if (is_array($flash)): ?>
        <div class="im-alert im-alert-<?= ($flash['type'] ?? '') === 'error' ? 'error' : 'success' ?>">
            <?= im_e($flash['message'] ?? '') ?>
        </div>
    <?php endif; ?>

    <?php if ($errorMessage !== ''): ?>
        <div class="im-alert im-alert-error">
            <strong>Save nahi ho saka:</strong> <?= im_e($errorMessage) ?>
        </div>
    <?php endif; ?>

    <section class="im-card">
        <div class="im-card-head">
            <h2>Upload new media</h2>
            <span class="im-muted">Maximum file size: 50 MB</span>
        </div>

        <div class="im-card-body">
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?= im_e($token) ?>">
                <input type="hidden" name="action" value="save">

                <div class="im-form-grid">
                    <div class="im-field">
                        <label for="industry_id">Select industry *</label>
                        <select id="industry_id" name="industry_id" required>
                            <option value="">Choose industry</option>
                            <?php foreach ($industries as $industry): ?>
                                <option value="<?= (int)$industry['id'] ?>">
                                    <?= im_e($industry['industry_name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="im-field">
                        <label for="media_role">Media role *</label>
                        <select id="media_role" name="media_role" required>
                            <?php foreach ($roleOptions as $role): ?>
                                <option value="<?= im_e($role) ?>">
                                    <?= im_e(ucfirst($role)) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="im-help">Options existing database ENUM se liye gaye hain.</div>
                    </div>

                    <div class="im-field im-field-full">
                        <label for="media_file">Choose image, video, PDF or document *</label>
                        <input
                            type="file"
                            id="media_file"
                            name="media_file"
                            required
                            accept=".jpg,.jpeg,.png,.gif,.webp,.avif,.mp4,.webm,.mov,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.csv"
                        >
                        <div class="im-help">
                            JPG, PNG, WEBP, AVIF, MP4, WEBM, MOV, PDF, DOC, DOCX,
                            XLS, XLSX, PPT, PPTX, TXT and CSV.
                        </div>
                    </div>

                    <div class="im-field im-field-full">
                        <label for="external_url">External URL (optional)</label>
                        <input
                            type="url"
                            id="external_url"
                            name="external_url"
                            maxlength="1000"
                            placeholder="https://example.com/resource"
                        >
                        <div class="im-help">
                            Tumhari table mein media_id required hai, isliye file upload karna zaroori hai.
                            External URL optional hai.
                        </div>
                    </div>

                    <div class="im-field">
                        <label for="sort_order">Sort order</label>
                        <input type="number" id="sort_order" name="sort_order" min="0" value="0">
                    </div>
                </div>

                <div class="im-actions">
                    <button type="submit" class="im-btn im-btn-primary">↑ Upload and Save</button>
                    <button type="reset" class="im-btn im-btn-light">Reset form</button>
                </div>
            </form>
        </div>
    </section>

    <section class="im-card">
        <div class="im-card-head">
            <h2>Uploaded industry media</h2>
            <span class="im-chip"><?= number_format($totalRows) ?> records</span>
        </div>

        <form class="im-toolbar" method="get">
            <input
                type="search"
                name="q"
                value="<?= im_e($search) ?>"
                placeholder="Search file name..."
                aria-label="Search media"
            >

            <select name="industry_id" aria-label="Filter by industry">
                <option value="">All industries</option>
                <?php foreach ($industries as $industry): ?>
                    <option
                        value="<?= (int)$industry['id'] ?>"
                        <?= (string)$industryFilter === (string)$industry['id'] ? 'selected' : '' ?>
                    >
                        <?= im_e($industry['industry_name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <button type="submit" class="im-btn im-btn-primary">Search</button>
            <a href="industry_media.php" class="im-btn im-btn-light">Clear</a>
        </form>

        <?php if (!$items): ?>
            <div class="im-empty">
                <strong>No media records found</strong>
                <p>Upload karne ke baad records yahan dikhai denge.</p>
            </div>
        <?php else: ?>
            <div class="im-table-wrap">
                <table class="im-table">
                    <thead>
                    <tr>
                        <th>Media</th>
                        <th>Industry</th>
                        <th>Type / Role</th>
                        <th>Size</th>
                        <th>Order</th>
                        <th>Action</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($items as $item): ?>
                        <?php
                        $relativePath = str_replace('\\', '/', (string)$item['file_path']);
                        $relativePath = ltrim($relativePath, '/');
                        $fileUrl = '../' . implode(
                            '/',
                            array_map('rawurlencode', explode('/', $relativePath))
                        );
                        $isImage = ($item['file_type'] ?? '') === 'image';
                        $sizeBytes = (int)($item['file_size'] ?? 0);
                        $sizeLabel = $sizeBytes >= 1024 * 1024
                            ? number_format($sizeBytes / (1024 * 1024), 2) . ' MB'
                            : number_format($sizeBytes / 1024, 1) . ' KB';
                        ?>
                        <tr>
                            <td>
                                <div class="im-media-cell">
                                    <div class="im-thumb">
                                        <?php if ($isImage): ?>
                                            <a href="<?= im_e($fileUrl) ?>" target="_blank" rel="noopener">
                                                <img
                                                    src="<?= im_e($fileUrl) ?>"
                                                    alt="<?= im_e($item['title'] ?: $item['original_name']) ?>"
                                                    loading="lazy"
                                                >
                                            </a>
                                        <?php else: ?>
                                            <?= im_e(strtoupper((string)($item['file_type'] ?? 'FILE'))) ?>
                                        <?php endif; ?>
                                    </div>
                                    <div>
                                        <div class="im-file-name">
                                            <?= im_e($item['title'] ?: $item['original_name']) ?>
                                        </div>
                                        <div class="im-muted"><?= im_e($item['original_name']) ?></div>
                                    </div>
                                </div>
                            </td>
                            <td><?= im_e($item['industry_name']) ?></td>
                            <td>
                                <span class="im-tag"><?= im_e($item['file_type'] ?? 'other') ?></span>
                                <div class="im-muted"><?= im_e($item['media_role']) ?></div>
                            </td>
                            <td><?= im_e($sizeLabel) ?></td>
                            <td><?= (int)$item['sort_order'] ?></td>
                            <td>
                                <div class="im-actions" style="margin:0">
                                    <a
                                        class="im-btn im-btn-light"
                                        href="<?= im_e($fileUrl) ?>"
                                        target="_blank"
                                        rel="noopener"
                                    >Open</a>

                                    <form
                                        method="post"
                                        onsubmit="return confirm('Industry se media link remove karein? Original file delete nahi hogi.');"
                                    >
                                        <input type="hidden" name="csrf_token" value="<?= im_e($token) ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="mapping_id" value="<?= (int)$item['mapping_id'] ?>">
                                        <button type="submit" class="im-btn im-btn-danger">Remove link</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div class="im-pagination">
                <span>
                    Showing <?= number_format($offset + 1) ?>–<?= number_format(min($offset + $perPage, $totalRows)) ?>
                    of <?= number_format($totalRows) ?>
                </span>

                <div class="im-pager">
                    <?php
                    $queryBase = ['q' => $search];
                    if ($industryFilter && $industryFilter > 0) {
                        $queryBase['industry_id'] = $industryFilter;
                    }
                    ?>

                    <?php if ($page > 1): ?>
                        <a href="?<?= im_e(http_build_query($queryBase + ['page' => $page - 1])) ?>">Previous</a>
                    <?php endif; ?>

                    <span class="current"><?= $page ?></span>

                    <?php if ($page < $totalPages): ?>
                        <a href="?<?= im_e(http_build_query($queryBase + ['page' => $page + 1])) ?>">Next</a>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </section>

</div>
</main>
</body>
</html>
<?php
