
<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (function_exists('requireAdmin')) {
    requireAdmin();
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    die('Database connection error: includes/db.php mein PDO variable $pdo check karein.');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

/* =========================================================
   HELPERS
========================================================= */

function pd_e($value)
{
    return htmlspecialchars((string)($value ?? ''), ENT_QUOTES, 'UTF-8');
}

function pd_csrf_token()
{
    if (empty($_SESSION['pd_csrf_token'])) {
        $_SESSION['pd_csrf_token'] = bin2hex(random_bytes(32));
    }

    return $_SESSION['pd_csrf_token'];
}

function pd_verify_csrf()
{
    $token = $_POST['csrf_token'] ?? '';

    if (
        !is_string($token) ||
        empty($_SESSION['pd_csrf_token']) ||
        !hash_equals($_SESSION['pd_csrf_token'], $token)
    ) {
        throw new RuntimeException('Security token expire ho gaya. Page refresh karke dobara try karein.');
    }
}

function pd_redirect($query = '')
{
    $url = 'product_documents.php';

    if ($query !== '') {
        $url .= '?' . $query;
    }

    header('Location: ' . $url);
    exit;
}

function pd_media_url($path)
{
    $path = trim((string)$path);

    if ($path === '') {
        return '';
    }

    if (preg_match('~^https?://~i', $path)) {
        return $path;
    }

    return '../' . ltrim(str_replace('\\', '/', $path), '/');
}

function pd_flash($type, $message)
{
    $_SESSION['pd_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}

function pd_table_exists(PDO $pdo, $table)
{
    $stmt = $pdo->prepare(
        'SELECT COUNT(*)
         FROM information_schema.tables
         WHERE table_schema = DATABASE()
           AND table_name = ?'
    );

    $stmt->execute([$table]);

    return (int)$stmt->fetchColumn() > 0;
}

function pd_column_exists(PDO $pdo, $table, $column)
{
    $stmt = $pdo->prepare(
        'SELECT COUNT(*)
         FROM information_schema.columns
         WHERE table_schema = DATABASE()
           AND table_name = ?
           AND column_name = ?'
    );

    $stmt->execute([$table, $column]);

    return (int)$stmt->fetchColumn() > 0;
}

function pd_get_enum_values(PDO $pdo, $table, $column)
{
    $stmt = $pdo->prepare(
        'SELECT COLUMN_TYPE
         FROM information_schema.columns
         WHERE table_schema = DATABASE()
           AND table_name = ?
           AND column_name = ?
         LIMIT 1'
    );

    $stmt->execute([$table, $column]);
    $columnType = $stmt->fetchColumn();

    if (!$columnType || stripos($columnType, 'enum(') !== 0) {
        return [];
    }

    preg_match_all("/'((?:[^'\\\\\\\\]|\\\\\\\\.)*)'/", $columnType, $matches);

    $values = [];

    foreach ($matches[1] ?? [] as $value) {
        $values[] = stripcslashes($value);
    }

    return $values;
}

/* =========================================================
   DATABASE CHECK
========================================================= */

$requiredTables = ['product_documents', 'products', 'media'];
$missingTables = [];

foreach ($requiredTables as $table) {
    if (!pd_table_exists($pdo, $table)) {
        $missingTables[] = $table;
    }
}

if (!empty($missingTables)) {
    die(
        '<div style="font-family:Arial;padding:30px;color:#991b1b">' .
        '<h2>Required database table missing</h2>' .
        '<p>Ye table database mein nahi mili: ' .
        pd_e(implode(', ', $missingTables)) .
        '</p><p>phpMyAdmin mein database aur table names check karein.</p></div>'
    );
}

$requiredColumns = [
    'product_documents' => [
        'id', 'product_id', 'media_id', 'document_type',
        'title', 'document_number', 'version',
        'sort_order', 'status', 'created_at'
    ],
    'products' => ['id', 'name'],
    'media' => ['id', 'file_path']
];

foreach ($requiredColumns as $table => $columns) {
    foreach ($columns as $column) {
        if (!pd_column_exists($pdo, $table, $column)) {
            die(
                '<div style="font-family:Arial;padding:30px;color:#991b1b">' .
                '<h2>Database column missing</h2><p>Table: ' .
                pd_e($table) . ' | Column: ' . pd_e($column) .
                '</p><p>Apne actual database columns check karein.</p></div>'
            );
        }
    }
}

/* Actual ENUM values database se automatically milenge */
$documentTypes = pd_get_enum_values($pdo, 'product_documents', 'document_type');

if (empty($documentTypes)) {
    $documentTypes = ['msds', 'tds', 'specification', 'catalogue'];
}

$defaultType = $documentTypes[0] ?? 'msds';

$errorMessage = '';

/* =========================================================
   POST ACTIONS: CREATE / UPDATE / DELETE / STATUS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        pd_verify_csrf();

        $action = $_POST['action'] ?? '';

        if ($action === 'save') {
            $id = (int)($_POST['id'] ?? 0);
            $productId = (int)($_POST['product_id'] ?? 0);
            $mediaId = (int)($_POST['media_id'] ?? 0);

            $documentType = trim((string)($_POST['document_type'] ?? ''));
            $title = trim((string)($_POST['title'] ?? ''));
            $documentNumber = trim((string)($_POST['document_number'] ?? ''));
            $version = trim((string)($_POST['version'] ?? ''));
            $sortOrder = (int)($_POST['sort_order'] ?? 0);
            $status = isset($_POST['status']) ? 1 : 0;

            if ($productId < 1) {
                throw new RuntimeException('Product select karein.');
            }

            if ($mediaId < 1) {
                throw new RuntimeException('Media/File select karein.');
            }

            if (!in_array($documentType, $documentTypes, true)) {
                throw new RuntimeException('Valid document type select karein.');
            }

            if ($title === '') {
                throw new RuntimeException('Document title required hai.');
            }

            if (mb_strlen($title) > 255) {
                throw new RuntimeException('Title 255 characters se chhota hona chahiye.');
            }

            if (mb_strlen($documentNumber) > 150) {
                throw new RuntimeException('Document number maximum 150 characters ka ho sakta hai.');
            }

            if (mb_strlen($version) > 50) {
                throw new RuntimeException('Version maximum 50 characters ka ho sakta hai.');
            }

            $checkProduct = $pdo->prepare(
                'SELECT id FROM products WHERE id = ? LIMIT 1'
            );
            $checkProduct->execute([$productId]);

            if (!$checkProduct->fetchColumn()) {
                throw new RuntimeException('Selected product products table mein nahi mila.');
            }

            $checkMedia = $pdo->prepare(
                'SELECT id FROM media WHERE id = ? LIMIT 1'
            );
            $checkMedia->execute([$mediaId]);

            if (!$checkMedia->fetchColumn()) {
                throw new RuntimeException('Selected file media table mein nahi mili. Media library check karein.');
            }

            if ($id > 0) {
                $checkDocument = $pdo->prepare(
                    'SELECT id FROM product_documents WHERE id = ? LIMIT 1'
                );
                $checkDocument->execute([$id]);

                if (!$checkDocument->fetchColumn()) {
                    throw new RuntimeException('Edit karne wala document record nahi mila.');
                }

                $stmt = $pdo->prepare(
                    'UPDATE product_documents
                     SET product_id = ?,
                         media_id = ?,
                         document_type = ?,
                         title = ?,
                         document_number = ?,
                         version = ?,
                         sort_order = ?,
                         status = ?
                     WHERE id = ?'
                );

                $stmt->execute([
                    $productId,
                    $mediaId,
                    $documentType,
                    $title,
                    $documentNumber !== '' ? $documentNumber : null,
                    $version !== '' ? $version : null,
                    $sortOrder,
                    $status,
                    $id
                ]);

                pd_flash('success', 'Document successfully update ho gaya.');
            } else {
                $stmt = $pdo->prepare(
                    'INSERT INTO product_documents
                     (product_id, media_id, document_type, title,
                      document_number, version, sort_order, status)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
                );

                $stmt->execute([
                    $productId,
                    $mediaId,
                    $documentType,
                    $title,
                    $documentNumber !== '' ? $documentNumber : null,
                    $version !== '' ? $version : null,
                    $sortOrder,
                    $status
                ]);

                pd_flash('success', 'New product document successfully add ho gaya.');
            }

            pd_redirect();
        }

        if ($action === 'delete') {
            $id = (int)($_POST['id'] ?? 0);

            if ($id < 1) {
                throw new RuntimeException('Invalid document ID.');
            }

            $stmt = $pdo->prepare(
                'DELETE FROM product_documents WHERE id = ?'
            );
            $stmt->execute([$id]);

            pd_flash('success', 'Document record delete ho gaya.');
            pd_redirect();
        }

        if ($action === 'toggle_status') {
            $id = (int)($_POST['id'] ?? 0);

            $stmt = $pdo->prepare(
                'UPDATE product_documents
                 SET status = CASE WHEN status = 1 THEN 0 ELSE 1 END
                 WHERE id = ?'
            );
            $stmt->execute([$id]);

            pd_flash('success', 'Document status update ho gaya.');
            pd_redirect();
        }

        throw new RuntimeException('Unknown action.');
    } catch (Throwable $e) {
        $errorMessage = $e->getMessage();
    }
}

/* =========================================================
   FLASH MESSAGE
========================================================= */

$flash = $_SESSION['pd_flash'] ?? null;
unset($_SESSION['pd_flash']);

/* =========================================================
   DROPDOWN DATA
========================================================= */

$productCodeExists = pd_column_exists($pdo, 'products', 'product_code');

$productSql = 'SELECT id, name';

if ($productCodeExists) {
    $productSql .= ', product_code';
}

$productSql .= ' FROM products ORDER BY name ASC';

$products = $pdo->query($productSql)->fetchAll(PDO::FETCH_ASSOC);

$mediaHasOriginalName = pd_column_exists($pdo, 'media', 'original_name');
$mediaHasFileName = pd_column_exists($pdo, 'media', 'file_name');
$mediaHasFileType = pd_column_exists($pdo, 'media', 'file_type');
$mediaHasMimeType = pd_column_exists($pdo, 'media', 'mime_type');

$mediaSql = 'SELECT id, file_path';

$mediaSql .= $mediaHasOriginalName ? ', original_name' : '';
$mediaSql .= $mediaHasFileName ? ', file_name' : '';
$mediaSql .= $mediaHasFileType ? ', file_type' : '';
$mediaSql .= $mediaHasMimeType ? ', mime_type' : '';

$mediaSql .= ' FROM media ORDER BY id DESC';

$mediaFiles = $pdo->query($mediaSql)->fetchAll(PDO::FETCH_ASSOC);

/* =========================================================
   SEARCH / FILTERS / PAGINATION
========================================================= */

$search = trim((string)($_GET['q'] ?? ''));
$filterType = trim((string)($_GET['type'] ?? ''));
$filterStatus = (string)($_GET['status'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));

$perPage = 10;
$where = [];
$params = [];

if ($search !== '') {
    $searchParts = [
        'pd.title LIKE ?',
        'pd.document_number LIKE ?',
        'pd.version LIKE ?',
        'p.name LIKE ?'
    ];

    $searchTerm = '%' . $search . '%';

    for ($i = 0; $i < count($searchParts); $i++) {
        $params[] = $searchTerm;
    }

    $where[] = '(' . implode(' OR ', $searchParts) . ')';
}

if ($filterType !== '' && in_array($filterType, $documentTypes, true)) {
    $where[] = 'pd.document_type = ?';
    $params[] = $filterType;
}

if ($filterStatus === '1' || $filterStatus === '0') {
    $where[] = 'pd.status = ?';
    $params[] = (int)$filterStatus;
}

$whereSql = !empty($where) ? ' WHERE ' . implode(' AND ', $where) : '';

$countSql = '
    SELECT COUNT(*)
    FROM product_documents pd
    LEFT JOIN products p ON p.id = pd.product_id
' . $whereSql;

$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);

$totalRows = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($totalRows / $perPage));

if ($page > $totalPages) {
    $page = $totalPages;
}

$offset = ($page - 1) * $perPage;

$listSql = '
    SELECT
        pd.id,
        pd.product_id,
        pd.media_id,
        pd.document_type,
        pd.title,
        pd.document_number,
        pd.version,
        pd.sort_order,
        pd.status,
        pd.created_at,
        p.name AS product_name,
        ' . ($productCodeExists ? 'p.product_code AS product_code,' : "'' AS product_code,") . '
        m.file_path,
        ' . ($mediaHasOriginalName ? 'm.original_name AS original_name,' : "'' AS original_name,") . '
        ' . ($mediaHasFileName ? 'm.file_name AS file_name' : "'' AS file_name") . '
    FROM product_documents pd
    LEFT JOIN products p ON p.id = pd.product_id
    LEFT JOIN media m ON m.id = pd.media_id
' . $whereSql . '
    ORDER BY pd.sort_order ASC, pd.id DESC
    LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset;

$listStmt = $pdo->prepare($listSql);
$listStmt->execute($params);
$documents = $listStmt->fetchAll(PDO::FETCH_ASSOC);

/* Dashboard stats */
$totalDocuments = (int)$pdo->query(
    'SELECT COUNT(*) FROM product_documents'
)->fetchColumn();

$activeDocuments = (int)$pdo->query(
    'SELECT COUNT(*) FROM product_documents WHERE status = 1'
)->fetchColumn();

$inactiveDocuments = max(0, $totalDocuments - $activeDocuments);

$uniqueProducts = (int)$pdo->query(
    'SELECT COUNT(DISTINCT product_id) FROM product_documents'
)->fetchColumn();

$csrfToken = pd_csrf_token();

$currentQuery = $_GET;
unset($currentQuery['page']);

function pd_page_url($page, $query)
{
    $query['page'] = $page;

    return 'product_documents.php?' . http_build_query($query);
}

function pd_type_label($type)
{
    return ucwords(str_replace(['_', '-'], ' ', (string)$type));
}

include __DIR__ . '/sidebar.php';
?>

<style>
:root {
    --pd-bg: #f5f7fb;
    --pd-card: #ffffff;
    --pd-text: #172033;
    --pd-muted: #738096;
    --pd-border: #e6eaf1;
    --pd-primary: #4f46e5;
    --pd-primary-dark: #4338ca;
    --pd-green: #15803d;
    --pd-red: #dc2626;
    --pd-radius: 18px;
    --pd-shadow: 0 10px 30px rgba(20, 31, 56, .055);
}

.pd-page, .pd-page * { box-sizing: border-box; }

.pd-page {
    padding: 28px;
    min-width: 0;
    background: var(--pd-bg);
    color: var(--pd-text);
    font-family: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
    min-height: 100vh;
}

.pd-container { max-width: 1600px; margin: 0 auto; }

.pd-topbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 18px;
    flex-wrap: wrap;
    margin-bottom: 25px;
}

.pd-heading { display: flex; gap: 14px; align-items: center; }

.pd-heading-icon {
    width: 54px;
    height: 54px;
    display: grid;
    place-items: center;
    flex-shrink: 0;
    border-radius: 17px;
    background: linear-gradient(135deg, #4f46e5, #7c3aed);
    color: #fff;
    font-size: 25px;
    box-shadow: 0 8px 20px rgba(79, 70, 229, .23);
}

.pd-heading h1 { margin: 0 0 5px; font-size: 25px; letter-spacing: -.7px; }
.pd-heading p { margin: 0; color: var(--pd-muted); font-size: 13px; }

.pd-btn {
    border: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 11px 16px;
    border-radius: 11px;
    font-weight: 700;
    font-size: 13px;
    cursor: pointer;
    text-decoration: none;
    transition: .2s ease;
    font-family: inherit;
}

.pd-btn-primary {
    background: var(--pd-primary);
    color: white;
    box-shadow: 0 5px 14px rgba(79, 70, 229, .18);
}
.pd-btn-primary:hover { background: var(--pd-primary-dark); transform: translateY(-1px); }
.pd-btn-light { background: #f2f4f9; color: #344054; }
.pd-btn-light:hover { background: #e7eaf2; }
.pd-btn-danger { background: #fff1f2; color: #be123c; }
.pd-btn-danger:hover { background: #ffe4e6; }

.pd-stats {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 16px;
    margin-bottom: 22px;
}

.pd-stat {
    background: var(--pd-card);
    border: 1px solid var(--pd-border);
    border-radius: var(--pd-radius);
    padding: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    box-shadow: var(--pd-shadow);
}

.pd-stat-label { color: var(--pd-muted); font-size: 12px; font-weight: 700; margin-bottom: 10px; }
.pd-stat-value { font-size: 27px; line-height: 1; font-weight: 800; letter-spacing: -.8px; }
.pd-stat-icon {
    width: 45px;
    height: 45px;
    display: grid;
    place-items: center;
    border-radius: 14px;
    font-size: 20px;
    flex-shrink: 0;
}
.pd-purple { background: #eeecff; color: #5b4ce2; }
.pd-green { background: #e5f8ed; color: #15803d; }
.pd-orange { background: #fff1df; color: #c46a0b; }
.pd-blue { background: #e5f2ff; color: #1767c0; }

.pd-alert {
    padding: 14px 17px;
    border-radius: 12px;
    margin-bottom: 18px;
    font-size: 13px;
    line-height: 1.55;
    overflow-wrap: anywhere;
}
.pd-alert-success { color: #166534; background: #dcfce7; border: 1px solid #bbf7d0; }
.pd-alert-error { color: #991b1b; background: #fee2e2; border: 1px solid #fecaca; }

.pd-panel {
    background: var(--pd-card);
    border: 1px solid var(--pd-border);
    border-radius: var(--pd-radius);
    box-shadow: var(--pd-shadow);
    overflow: hidden;
}

.pd-panel-head {
    padding: 20px 22px;
    border-bottom: 1px solid var(--pd-border);
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}

.pd-panel-title { margin: 0; font-size: 16px; font-weight: 800; }
.pd-panel-subtitle { margin: 5px 0 0; color: var(--pd-muted); font-size: 12px; }

.pd-filter {
    padding: 16px 22px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    border-bottom: 1px solid var(--pd-border);
    background: #fcfcfe;
}

.pd-input, .pd-select, .pd-textarea {
    width: 100%;
    border: 1px solid #dfe4ed;
    border-radius: 10px;
    background: white;
    padding: 11px 12px;
    color: var(--pd-text);
    outline: none;
    font-size: 13px;
    font-family: inherit;
    transition: border-color .2s, box-shadow .2s;
}

.pd-input:focus, .pd-select:focus, .pd-textarea:focus {
    border-color: #818cf8;
    box-shadow: 0 0 0 3px rgba(99, 102, 241, .11);
}

.pd-search { flex: 1 1 220px; position: relative; }
.pd-search .pd-input { padding-left: 36px; }
.pd-search-icon { position: absolute; left: 13px; top: 10px; color: #8993a5; font-size: 16px; }

.pd-filter .pd-select { width: auto; min-width: 150px; }
.pd-table-wrap { width: 100%; overflow-x: auto; }

.pd-table { width: 100%; border-collapse: collapse; text-align: left; min-width: 950px; }
.pd-table th {
    padding: 13px 18px;
    background: #f8f9fc;
    color: #778196;
    font-size: 10px;
    text-transform: uppercase;
    letter-spacing: .7px;
    white-space: nowrap;
}
.pd-table td {
    padding: 15px 18px;
    border-top: 1px solid #eef0f5;
    vertical-align: middle;
    font-size: 12px;
}
.pd-table tbody tr:hover { background: #fafbff; }

.pd-doc-title { font-size: 13px; font-weight: 800; color: #202a3e; margin-bottom: 5px; }
.pd-doc-meta { color: var(--pd-muted); font-size: 11px; overflow-wrap: anywhere; }
.pd-product { font-weight: 700; font-size: 12px; margin-bottom: 4px; }
.pd-product-code { color: var(--pd-muted); font-size: 10px; }

.pd-type {
    display: inline-flex;
    align-items: center;
    padding: 6px 9px;
    border-radius: 7px;
    font-size: 10px;
    font-weight: 800;
    color: #5145cd;
    background: #efedff;
    white-space: nowrap;
}

.pd-status {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 11px;
    font-weight: 800;
}
.pd-status:before {
    content: "";
    width: 7px;
    height: 7px;
    border-radius: 50%;
    background: currentColor;
}
.pd-status-active { color: #15803d; }
.pd-status-inactive { color: #b45309; }

.pd-actions { display: flex; align-items: center; gap: 6px; }
.pd-icon-btn {
    border: 1px solid #e5e8ef;
    background: white;
    color: #536078;
    width: 33px;
    height: 33px;
    border-radius: 9px;
    display: inline-grid;
    place-items: center;
    cursor: pointer;
    font-size: 14px;
}
.pd-icon-btn:hover { background: #f2f3ff; color: #4f46e5; border-color: #d9d5ff; }
.pd-icon-btn.pd-delete:hover { background: #fff1f2; color: #be123c; border-color: #fecdd3; }
.pd-inline-form { display: inline-flex; margin: 0; }

.pd-empty { padding: 55px 20px; text-align: center; }
.pd-empty-icon { font-size: 38px; margin-bottom: 12px; }
.pd-empty h3 { margin: 0 0 7px; font-size: 16px; }
.pd-empty p { color: var(--pd-muted); font-size: 12px; margin: 0 0 18px; }

.pd-pagination {
    padding: 17px 22px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    flex-wrap: wrap;
    border-top: 1px solid var(--pd-border);
}
.pd-page-info { color: var(--pd-muted); font-size: 12px; }
.pd-page-links { display: flex; gap: 6px; flex-wrap: wrap; }
.pd-page-link {
    min-width: 34px;
    height: 34px;
    padding: 0 10px;
    display: inline-grid;
    place-items: center;
    border: 1px solid #e1e5ed;
    border-radius: 9px;
    color: #596579;
    text-decoration: none;
    font-size: 12px;
    font-weight: 700;
    background: white;
}
.pd-page-link.active { color: white; background: var(--pd-primary); border-color: var(--pd-primary); }
.pd-page-link.disabled { opacity: .4; pointer-events: none; }

.pd-modal-backdrop {
    position: fixed;
    inset: 0;
    z-index: 9999;
    padding: 22px;
    display: none;
    align-items: center;
    justify-content: center;
    background: rgba(15, 23, 42, .58);
    backdrop-filter: blur(5px);
}
.pd-modal-backdrop.open { display: flex; }

.pd-modal {
    background: #fff;
    border-radius: 20px;
    width: min(650px, 100%);
    max-height: calc(100vh - 44px);
    overflow-y: auto;
    box-shadow: 0 24px 90px rgba(0, 0, 0, .22);
    animation: pdModalIn .2s ease;
}
@keyframes pdModalIn {
    from { opacity: 0; transform: translateY(8px) scale(.99); }
    to { opacity: 1; transform: translateY(0) scale(1); }
}
.pd-modal-head {
    padding: 21px 23px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 15px;
    border-bottom: 1px solid var(--pd-border);
}
.pd-modal-head h2 { margin: 0 0 5px; font-size: 18px; }
.pd-modal-head p { margin: 0; font-size: 12px; color: var(--pd-muted); }
.pd-close {
    border: 0;
    width: 34px;
    height: 34px;
    border-radius: 10px;
    background: #f1f3f8;
    cursor: pointer;
    font-size: 20px;
    color: #5a6475;
}
.pd-modal-body { padding: 22px 23px; }
.pd-form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
.pd-field { min-width: 0; }
.pd-field.full { grid-column: 1 / -1; }
.pd-label { display: block; font-size: 12px; font-weight: 800; margin-bottom: 7px; color: #344054; }
.pd-required { color: #dc2626; }
.pd-help { margin-top: 6px; font-size: 11px; line-height: 1.5; color: var(--pd-muted); }
.pd-checkbox-row {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 13px;
    border-radius: 11px;
    border: 1px solid var(--pd-border);
    background: #fafbfe;
    font-size: 12px;
    font-weight: 700;
}
.pd-checkbox-row input { width: 16px; height: 16px; accent-color: var(--pd-primary); }
.pd-modal-foot {
    padding: 16px 23px 22px;
    display: flex;
    justify-content: flex-end;
    gap: 9px;
    border-top: 1px solid var(--pd-border);
}

@media (max-width: 1100px) {
    .pd-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 650px) {
    .pd-page { padding: 16px 12px; }
    .pd-heading h1 { font-size: 21px; }
    .pd-stats { gap: 10px; }
    .pd-stat { padding: 14px; }
    .pd-stat-value { font-size: 23px; }
    .pd-stat-icon { width: 37px; height: 37px; }
    .pd-filter { padding: 13px; }
    .pd-filter .pd-select { width: 100%; }
    .pd-form-grid { grid-template-columns: 1fr; }
    .pd-field.full { grid-column: auto; }
    .pd-modal-backdrop { padding: 10px; }
    .pd-modal { max-height: calc(100vh - 20px); }
    .pd-modal-head, .pd-modal-body { padding: 17px; }
    .pd-modal-foot { padding: 14px 17px 17px; }
}

/* Sidebar overlap fix: keep the existing page design, only offset the content area. */
@media (min-width: 1101px) {
    .pd-page {
        margin-left: 376px;
        width: calc(100% - 376px);
        min-width: 0;
    }
}
@media (max-width: 1100px) {
    .pd-page {
        margin-left: 0;
        width: 100%;
    }
}
</style>

<div class="pd-page">
<div class="pd-container">

    <div class="pd-topbar">
        <div class="pd-heading">
            <div class="pd-heading-icon">▤</div>
            <div>
                <h1>Product Documents</h1>
                <p>Manage product certificates, technical sheets and files.</p>
            </div>
        </div>

        <button type="button" class="pd-btn pd-btn-primary" id="pdAddBtn">
            <span style="font-size:18px;line-height:12px">＋</span>
            Add Document
        </button>
    </div>

    <?php if ($flash): ?>
        <div class="pd-alert pd-alert-<?= pd_e($flash['type'] === 'success' ? 'success' : 'error') ?>">
            <?= pd_e($flash['message']) ?>
        </div>
    <?php endif; ?>

    <?php if ($errorMessage !== ''): ?>
        <div class="pd-alert pd-alert-error"><?= pd_e($errorMessage) ?></div>
    <?php endif; ?>

    <div class="pd-stats">
        <div class="pd-stat">
            <div>
                <div class="pd-stat-label">TOTAL DOCUMENTS</div>
                <div class="pd-stat-value"><?= number_format($totalDocuments) ?></div>
            </div>
            <div class="pd-stat-icon pd-purple">▤</div>
        </div>

        <div class="pd-stat">
            <div>
                <div class="pd-stat-label">ACTIVE DOCUMENTS</div>
                <div class="pd-stat-value"><?= number_format($activeDocuments) ?></div>
            </div>
            <div class="pd-stat-icon pd-green">✓</div>
        </div>

        <div class="pd-stat">
            <div>
                <div class="pd-stat-label">INACTIVE DOCUMENTS</div>
                <div class="pd-stat-value"><?= number_format($inactiveDocuments) ?></div>
            </div>
            <div class="pd-stat-icon pd-orange">◷</div>
        </div>

        <div class="pd-stat">
            <div>
                <div class="pd-stat-label">LINKED PRODUCTS</div>
                <div class="pd-stat-value"><?= number_format($uniqueProducts) ?></div>
            </div>
            <div class="pd-stat-icon pd-blue">▦</div>
        </div>
    </div>

    <section class="pd-panel">
        <div class="pd-panel-head">
            <div>
                <h2 class="pd-panel-title">All Product Documents</h2>
                <p class="pd-panel-subtitle">Search, filter and manage your document records.</p>
            </div>
            <div style="font-size:12px;color:#778196;font-weight:700">
                <?= number_format($totalRows) ?> record<?= $totalRows === 1 ? '' : 's' ?>
            </div>
        </div>

        <form method="get" class="pd-filter">
            <div class="pd-search">
                <span class="pd-search-icon">⌕</span>
                <input
                    class="pd-input"
                    type="search"
                    name="q"
                    value="<?= pd_e($search) ?>"
                    placeholder="Search title, product, document no..."
                >
            </div>

            <select class="pd-select" name="type" aria-label="Filter by document type">
                <option value="">All document types</option>
                <?php foreach ($documentTypes as $type): ?>
                    <option value="<?= pd_e($type) ?>" <?= $filterType === $type ? 'selected' : '' ?>>
                        <?= pd_e(pd_type_label($type)) ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <select class="pd-select" name="status" aria-label="Filter by status">
                <option value="">All statuses</option>
                <option value="1" <?= $filterStatus === '1' ? 'selected' : '' ?>>Active</option>
                <option value="0" <?= $filterStatus === '0' ? 'selected' : '' ?>>Inactive</option>
            </select>

            <button type="submit" class="pd-btn pd-btn-primary">Apply Filters</button>
            <a href="product_documents.php" class="pd-btn pd-btn-light">Reset</a>
        </form>

        <?php if (empty($documents)): ?>
            <div class="pd-empty">
                <div class="pd-empty-icon">📄</div>
                <h3>No documents found</h3>
                <p>Abhi koi matching record nahi hai. Naya document add karein.</p>
                <button type="button" class="pd-btn pd-btn-primary" id="pdEmptyAddBtn">＋ Add First Document</button>
            </div>
        <?php else: ?>
            <div class="pd-table-wrap">
                <table class="pd-table">
                    <thead>
                        <tr>
                            <th>Document</th>
                            <th>Product</th>
                            <th>Document Type</th>
                            <th>Version</th>
                            <th>Status</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($documents as $doc): ?>
                        <?php
                            $mediaName = $doc['original_name'] ?: ($doc['file_name'] ?: basename((string)$doc['file_path']));
                            $fileUrl = pd_media_url($doc['file_path']);
                        ?>
                        <tr>
                            <td>
                                <div class="pd-doc-title"><?= pd_e($doc['title']) ?></div>
                                <div class="pd-doc-meta">
                                    ID #<?= (int)$doc['id'] ?>
                                    <?php if (!empty($doc['document_number'])): ?>
                                        · <?= pd_e($doc['document_number']) ?>
                                    <?php endif; ?>
                                </div>
                                <?php if ($fileUrl !== ''): ?>
                                    <div style="margin-top:7px">
                                        <a
                                            href="<?= pd_e($fileUrl) ?>"
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            style="font-size:11px;font-weight:700;color:#4f46e5;text-decoration:none"
                                        >↗ View attached file</a>
                                    </div>
                                <?php endif; ?>
                                <div class="pd-doc-meta" style="margin-top:4px"><?= pd_e($mediaName) ?></div>
                            </td>

                            <td>
                                <div class="pd-product"><?= pd_e($doc['product_name'] ?: 'Product not found') ?></div>
                                <?php if (!empty($doc['product_code'])): ?>
                                    <div class="pd-product-code"><?= pd_e($doc['product_code']) ?></div>
                                <?php endif; ?>
                            </td>

                            <td>
                                <span class="pd-type"><?= pd_e(pd_type_label($doc['document_type'])) ?></span>
                            </td>

                            <td><?= pd_e($doc['version'] ?: '—') ?></td>

                            <td>
                                <span class="pd-status <?= (int)$doc['status'] === 1 ? 'pd-status-active' : 'pd-status-inactive' ?>">
                                    <?= (int)$doc['status'] === 1 ? 'Active' : 'Inactive' ?>
                                </span>
                            </td>

                            <td>
                                <div style="font-weight:700;font-size:11px">
                                    <?= !empty($doc['created_at']) ? pd_e(date('d M Y', strtotime($doc['created_at']))) : '—' ?>
                                </div>
                                <div class="pd-doc-meta">
                                    <?= !empty($doc['created_at']) ? pd_e(date('h:i A', strtotime($doc['created_at']))) : '' ?>
                                </div>
                            </td>

                            <td>
                                <div class="pd-actions">
                                    <button
                                        type="button"
                                        class="pd-icon-btn pd-edit-btn"
                                        title="Edit document"
                                        aria-label="Edit document"
                                        data-id="<?= (int)$doc['id'] ?>"
                                        data-product-id="<?= (int)$doc['product_id'] ?>"
                                        data-media-id="<?= (int)$doc['media_id'] ?>"
                                        data-type="<?= pd_e($doc['document_type']) ?>"
                                        data-title="<?= pd_e($doc['title']) ?>"
                                        data-number="<?= pd_e($doc['document_number']) ?>"
                                        data-version="<?= pd_e($doc['version']) ?>"
                                        data-sort="<?= (int)$doc['sort_order'] ?>"
                                        data-status="<?= (int)$doc['status'] ?>"
                                    >✎</button>

                                    <form method="post" class="pd-inline-form" onsubmit="return confirm('Is document ka status change karna hai?')">
                                        <input type="hidden" name="csrf_token" value="<?= pd_e($csrfToken) ?>">
                                        <input type="hidden" name="action" value="toggle_status">
                                        <input type="hidden" name="id" value="<?= (int)$doc['id'] ?>">
                                        <button type="submit" class="pd-icon-btn" title="Toggle status" aria-label="Toggle status">◷</button>
                                    </form>

                                    <form method="post" class="pd-inline-form" onsubmit="return confirm('Kya aap is document record ko permanently delete karna chahte hain?')">
                                        <input type="hidden" name="csrf_token" value="<?= pd_e($csrfToken) ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= (int)$doc['id'] ?>">
                                        <button type="submit" class="pd-icon-btn pd-delete" title="Delete record" aria-label="Delete record">⌫</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div class="pd-pagination">
                <div class="pd-page-info">
                    Showing <?= $totalRows > 0 ? $offset + 1 : 0 ?>–<?= min($offset + $perPage, $totalRows) ?>
                    of <?= number_format($totalRows) ?> records
                </div>

                <div class="pd-page-links">
                    <a
                        class="pd-page-link <?= $page <= 1 ? 'disabled' : '' ?>"
                        href="<?= pd_e(pd_page_url(max(1, $page - 1), $currentQuery)) ?>"
                        aria-label="Previous page"
                    >‹</a>

                    <?php
                    $startPage = max(1, $page - 2);
                    $endPage = min($totalPages, $page + 2);
                    ?>

                    <?php for ($p = $startPage; $p <= $endPage; $p++): ?>
                        <a
                            class="pd-page-link <?= $p === $page ? 'active' : '' ?>"
                            href="<?= pd_e(pd_page_url($p, $currentQuery)) ?>"
                        ><?= $p ?></a>
                    <?php endfor; ?>

                    <a
                        class="pd-page-link <?= $page >= $totalPages ? 'disabled' : '' ?>"
                        href="<?= pd_e(pd_page_url(min($totalPages, $page + 1), $currentQuery)) ?>"
                        aria-label="Next page"
                    >›</a>
                </div>
            </div>
        <?php endif; ?>
    </section>
</div>
</div>

<!-- ADD / EDIT MODAL -->
<div class="pd-modal-backdrop" id="pdModalBackdrop" aria-hidden="true">
    <section class="pd-modal" role="dialog" aria-modal="true" aria-labelledby="pdModalTitle">
        <div class="pd-modal-head">
            <div>
                <h2 id="pdModalTitle">Add Product Document</h2>
                <p>Fill in the document details below.</p>
            </div>
            <button type="button" class="pd-close" id="pdCloseBtn" aria-label="Close modal">×</button>
        </div>

        <form method="post" id="pdDocumentForm">
            <input type="hidden" name="csrf_token" value="<?= pd_e($csrfToken) ?>">
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="id" id="pd_id" value="">

            <div class="pd-modal-body">
                <div class="pd-form-grid">
                    <div class="pd-field full">
                        <label class="pd-label" for="pd_product_id">
                            Product <span class="pd-required">*</span>
                        </label>
                        <select class="pd-select" name="product_id" id="pd_product_id" required>
                            <option value="">Select product</option>
                            <?php foreach ($products as $product): ?>
                                <option value="<?= (int)$product['id'] ?>">
                                    <?= pd_e($product['name']) ?>
                                    <?php if (!empty($product['product_code'])): ?>
                                        — <?= pd_e($product['product_code']) ?>
                                    <?php endif; ?>
                                    (ID: <?= (int)$product['id'] ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (empty($products)): ?>
                            <div class="pd-help">Products table mein abhi koi product nahi mila. Pehle product add karein.</div>
                        <?php endif; ?>
                    </div>

                    <div class="pd-field full">
                        <label class="pd-label" for="pd_media_id">
                            Media / File <span class="pd-required">*</span>
                        </label>
                        <select class="pd-select" name="media_id" id="pd_media_id" required>
                            <option value="">Select file from media library</option>
                            <?php foreach ($mediaFiles as $media): ?>
                                <?php
                                    $mediaLabel = $media['original_name']
                                        ?? ($media['file_name'] ?? basename((string)$media['file_path']));

                                    if (trim((string)$mediaLabel) === '') {
                                        $mediaLabel = basename((string)$media['file_path']);
                                    }

                                    $mediaExtra = $media['file_type']
                                        ?? ($media['mime_type'] ?? '');
                                ?>
                                <option value="<?= (int)$media['id'] ?>">
                                    <?= pd_e($mediaLabel) ?>
                                    <?= $mediaExtra !== '' ? ' — ' . pd_e($mediaExtra) : '' ?>
                                    (ID: <?= (int)$media['id'] ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="pd-help">
                            File yahan upload nahi hoti; yahan media table mein pehle se uploaded file select hoti hai.
                        </div>
                        <?php if (empty($mediaFiles)): ?>
                            <div class="pd-help" style="color:#b45309">
                                Media library empty hai. Pehle admin ke media section mein file upload karein.
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="pd-field">
                        <label class="pd-label" for="pd_document_type">
                            Document Type <span class="pd-required">*</span>
                        </label>
                        <select class="pd-select" name="document_type" id="pd_document_type" required>
                            <?php foreach ($documentTypes as $type): ?>
                                <option value="<?= pd_e($type) ?>" <?= $type === $defaultType ? 'selected' : '' ?>>
                                    <?= pd_e(pd_type_label($type)) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="pd-help">Options database ke ENUM se load hote hain.</div>
                    </div>

                    <div class="pd-field">
                        <label class="pd-label" for="pd_title">
                            Document Title <span class="pd-required">*</span>
                        </label>
                        <input
                            class="pd-input"
                            type="text"
                            name="title"
                            id="pd_title"
                            maxlength="255"
                            placeholder="e.g. Product Safety Data Sheet"
                            required
                        >
                    </div>

                    <div class="pd-field">
                        <label class="pd-label" for="pd_document_number">Document Number</label>
                        <input
                            class="pd-input"
                            type="text"
                            name="document_number"
                            id="pd_document_number"
                            maxlength="150"
                            placeholder="e.g. MSDS-001"
                        >
                    </div>

                    <div class="pd-field">
                        <label class="pd-label" for="pd_version">Version</label>
                        <input
                            class="pd-input"
                            type="text"
                            name="version"
                            id="pd_version"
                            maxlength="50"
                            placeholder="e.g. 1.0 / Rev 02"
                        >
                    </div>

                    <div class="pd-field">
                        <label class="pd-label" for="pd_sort_order">Sort Order</label>
                        <input
                            class="pd-input"
                            type="number"
                            name="sort_order"
                            id="pd_sort_order"
                            value="0"
                            step="1"
                        >
                        <div class="pd-help">Chhota number list mein pehle show hoga.</div>
                    </div>

                    <div class="pd-field full">
                        <label class="pd-checkbox-row">
                            <input type="checkbox" name="status" id="pd_status" value="1" checked>
                            <span>Document Active rakhein</span>
                        </label>
                    </div>
                </div>
            </div>

            <div class="pd-modal-foot">
                <button type="button" class="pd-btn pd-btn-light" id="pdCancelBtn">Cancel</button>
                <button type="submit" class="pd-btn pd-btn-primary" id="pdSaveBtn">Save Document</button>
            </div>
        </form>
    </section>
</div>

<script>
(function () {
    const backdrop = document.getElementById('pdModalBackdrop');
    const form = document.getElementById('pdDocumentForm');
    const title = document.getElementById('pdModalTitle');
    const saveBtn = document.getElementById('pdSaveBtn');

    const fields = {
        id: document.getElementById('pd_id'),
        product_id: document.getElementById('pd_product_id'),
        media_id: document.getElementById('pd_media_id'),
        document_type: document.getElementById('pd_document_type'),
        title: document.getElementById('pd_title'),
        document_number: document.getElementById('pd_document_number'),
        version: document.getElementById('pd_version'),
        sort_order: document.getElementById('pd_sort_order'),
        status: document.getElementById('pd_status')
    };

    function openModal() {
        backdrop.classList.add('open');
        backdrop.setAttribute('aria-hidden', 'false');
        document.body.style.overflow = 'hidden';

        window.setTimeout(function () {
            fields.product_id.focus();
        }, 60);
    }

    function closeModal() {
        backdrop.classList.remove('open');
        backdrop.setAttribute('aria-hidden', 'true');
        document.body.style.overflow = '';
    }

    function resetForm() {
        form.reset();

        fields.id.value = '';
        fields.sort_order.value = '0';
        fields.status.checked = true;

        title.textContent = 'Add Product Document';
        saveBtn.textContent = 'Save Document';
    }

    function openAddModal() {
        resetForm();
        openModal();
    }

    document.getElementById('pdAddBtn')?.addEventListener('click', openAddModal);
    document.getElementById('pdEmptyAddBtn')?.addEventListener('click', openAddModal);
    document.getElementById('pdCloseBtn').addEventListener('click', closeModal);
    document.getElementById('pdCancelBtn').addEventListener('click', closeModal);

    backdrop.addEventListener('click', function (event) {
        if (event.target === backdrop) {
            closeModal();
        }
    });

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape' && backdrop.classList.contains('open')) {
            closeModal();
        }
    });

    document.querySelectorAll('.pd-edit-btn').forEach(function (button) {
        button.addEventListener('click', function () {
            resetForm();

            fields.id.value = button.dataset.id || '';
            fields.product_id.value = button.dataset.productId || '';
            fields.media_id.value = button.dataset.mediaId || '';
            fields.document_type.value = button.dataset.type || '';
            fields.title.value = button.dataset.title || '';
            fields.document_number.value = button.dataset.number || '';
            fields.version.value = button.dataset.version || '';
            fields.sort_order.value = button.dataset.sort || '0';
            fields.status.checked = button.dataset.status === '1';

            title.textContent = 'Edit Product Document';
            saveBtn.textContent = 'Update Document';

            openModal();
        });
    });

    form.addEventListener('submit', function (event) {
        if (!fields.product_id.value) {
            event.preventDefault();
            alert('Please select a product.');
            fields.product_id.focus();
            return;
        }

        if (!fields.media_id.value) {
            event.preventDefault();
            alert('Please select a media file.');
            fields.media_id.focus();
            return;
        }

        if (!fields.title.value.trim()) {
            event.preventDefault();
            alert('Please enter document title.');
            fields.title.focus();
        }
    });
})();
</script>