
<?php
/*
|--------------------------------------------------------------------------
| Pure Chemical - Add Product
| File: admin/add_product.php
|--------------------------------------------------------------------------
*/

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/csrf.php';

if (function_exists('requireAdmin')) {
    requireAdmin();
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    exit('Database connection not available. Check admin/includes/db.php');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

/* -------------------- HELPERS -------------------- */

function apEscape($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function apSlug(string $value): string
{
    $value = trim($value);

    if (function_exists('iconv')) {
        $converted = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value);
        if ($converted !== false) {
            $value = $converted;
        }
    }

    $value = strtolower($value);
    $value = preg_replace('/[^a-z0-9]+/', '-', $value);
    $value = trim((string)$value, '-');

    return $value !== '' ? substr($value, 0, 240) : 'product';
}

function apUniqueSlug(PDO $pdo, string $slug): string
{
    $base = $slug;
    $number = 1;

    while (true) {
        $stmt = $pdo->prepare(
            'SELECT id FROM products WHERE slug = ? LIMIT 1'
        );
        $stmt->execute([$slug]);

        if (!$stmt->fetchColumn()) {
            return $slug;
        }

        $number++;
        $suffix = '-' . $number;
        $slug = substr($base, 0, 255 - strlen($suffix)) . $suffix;
    }
}

function apCsrfField(): string
{
    if (!function_exists('csrf_field')) {
        return '';
    }

    // Supports CSRF helpers that either echo or return the field.
    ob_start();
    $returned = csrf_field();
    $printed = (string)ob_get_clean();

    return $printed . (is_string($returned) ? $returned : '');
}

function apVerifyCsrf(): void
{
    if (function_exists('requireCsrf')) {
        requireCsrf();
    }
}

function apStoreMedia(
    PDO $pdo,
    string $tmpPath,
    string $originalName,
    string $mime,
    string $extension,
    string $type,
    int $size,
    ?string $altText = null
): array {
    $directory = dirname(__DIR__) . '/uploads/products/';

    if (!is_dir($directory)) {
        if (!mkdir($directory, 0775, true) && !is_dir($directory)) {
            throw new RuntimeException('Upload folder create nahi ho saka.');
        }
    }

    if (!is_writable($directory)) {
        throw new RuntimeException('uploads/products folder writable nahi hai.');
    }

    $filename = bin2hex(random_bytes(16)) . '.' . $extension;
    $destination = $directory . $filename;

    if (!move_uploaded_file($tmpPath, $destination)) {
        throw new RuntimeException('File move nahi ho saki: ' . $originalName);
    }

    $GLOBALS['ap_uploaded_files'][] = $destination;

    try {
        $stmt = $pdo->prepare("
            INSERT INTO media (
                original_name,
                file_name,
                file_path,
                mime_type,
                file_type,
                extension,
                file_size,
                alt_text,
                title,
                status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
        ");

        $stmt->execute([
            $originalName,
            $filename,
            'uploads/products/' . $filename,
            $mime,
            $type,
            $extension,
            $size,
            $altText,
            pathinfo($originalName, PATHINFO_FILENAME)
        ]);

        return [
            'id' => (int)$pdo->lastInsertId(),
            'path' => $destination
        ];
    } catch (Throwable $exception) {
        if (is_file($destination)) {
            @unlink($destination);
        }

        throw $exception;
    }
}

function apAttachMedia(
    PDO $pdo,
    int $productId,
    int $mediaId,
    string $role,
    int $sortOrder,
    string $title
): void {
    $stmt = $pdo->prepare("
        INSERT INTO product_media (
            product_id,
            media_id,
            media_role,
            title,
            sort_order
        ) VALUES (?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $productId,
        $mediaId,
        $role,
        $title,
        $sortOrder
    ]);
}

/* -------------------- LOAD CATEGORIES / MENUS -------------------- */

$categories = [];
$menus = [];
$pageError = '';
$errors = [];

try {
    $stmt = $pdo->query("
        SELECT id, name, parent_id
        FROM categories
        WHERE category_type = 'product'
          AND status = 1
        ORDER BY sort_order ASC, name ASC
    ");
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->query("
        SELECT id, name
        FROM menus
        WHERE status = 1
        ORDER BY name ASC
    ");
    $menus = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $exception) {
    $pageError = 'Categories ya menus load nahi ho paaye. Database error log check karein.';
    error_log('Add product dropdown error: ' . $exception->getMessage());
}

/* -------------------- FORM DEFAULTS -------------------- */

$form = [
    'name' => '',
    'slug' => '',
    'product_code' => '',
    'cas_number' => '',
    'grade' => '',
    'molecular_formula' => '',
    'molecular_weight' => '',
    'sku' => '',
    'short_description' => '',
    'description' => '',
    'application' => '',
    'packaging' => '',
    'category_id' => '',
    'menu_id' => '',
    'status' => 'draft',
    'featured' => '0',
    'sort_order' => '0'
];

$saved = isset($_GET['saved']) && $_GET['saved'] === '1';

/* -------------------- SUBMIT -------------------- */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    apVerifyCsrf();

    foreach ($form as $key => $default) {
        if ($key === 'featured') {
            $form[$key] = isset($_POST['featured']) ? '1' : '0';
        } elseif (isset($_POST[$key]) && !is_array($_POST[$key])) {
            $form[$key] = trim((string)$_POST[$key]);
        }
    }

    if ($form['name'] === '') {
        $errors[] = 'Product name bharna zaroori hai.';
    } elseif (strlen($form['name']) > 255) {
        $errors[] = 'Product name 255 characters se chhota rakhein.';
    }

    $slugInput = $form['slug'] !== '' ? $form['slug'] : $form['name'];
    $form['slug'] = apSlug($slugInput);

    if (!in_array($form['status'], ['draft', 'published', 'inactive'], true)) {
        $form['status'] = 'draft';
    }

    $sortOrder = filter_var($form['sort_order'], FILTER_VALIDATE_INT);

    if ($sortOrder === false || $sortOrder < 0) {
        $sortOrder = 0;
        $form['sort_order'] = '0';
    }

    if ($form['category_id'] !== '') {
        $check = $pdo->prepare("
            SELECT id FROM categories
            WHERE id = ? AND category_type = 'product' AND status = 1
            LIMIT 1
        ");
        $check->execute([(int)$form['category_id']]);

        if (!$check->fetchColumn()) {
            $errors[] = 'Selected product category valid nahi hai.';
        }
    }

    if ($form['menu_id'] !== '') {
        $check = $pdo->prepare("
            SELECT id FROM menus WHERE id = ? AND status = 1 LIMIT 1
        ");
        $check->execute([(int)$form['menu_id']]);

        if (!$check->fetchColumn()) {
            $errors[] = 'Selected menu valid nahi hai.';
        }
    }

    /* Upload validation */

    $allowedImages = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
        'image/gif' => 'gif'
    ];

    $allowedVideos = [
        'video/mp4' => 'mp4',
        'video/webm' => 'webm',
        'video/ogg' => 'ogv',
        'video/quicktime' => 'mov'
    ];

    $validImages = [];
    $validVideo = null;
    $finfo = new finfo(FILEINFO_MIME_TYPE);

    for ($i = 1; $i <= 4; $i++) {
        $field = 'image_' . $i;

        if (
            !isset($_FILES[$field]) ||
            $_FILES[$field]['error'] === UPLOAD_ERR_NO_FILE
        ) {
            continue;
        }

        $file = $_FILES[$field];

        if ($file['error'] !== UPLOAD_ERR_OK) {
            $errors[] = "Image {$i}: upload error.";
            continue;
        }

        if (!is_uploaded_file($file['tmp_name'])) {
            $errors[] = "Image {$i}: invalid upload.";
            continue;
        }

        if ($file['size'] > 10 * 1024 * 1024) {
            $errors[] = "Image {$i}: maximum size 10 MB hai.";
            continue;
        }

        $mime = $finfo->file($file['tmp_name']);

        if (
            !isset($allowedImages[$mime]) ||
            @getimagesize($file['tmp_name']) === false
        ) {
            $errors[] = "Image {$i}: JPG, PNG, WEBP ya GIF valid image upload karein.";
            continue;
        }

        $validImages[] = [
            'tmp' => $file['tmp_name'],
            'name' => basename($file['name']),
            'mime' => $mime,
            'extension' => $allowedImages[$mime],
            'size' => (int)$file['size']
        ];
    }

    if (
        isset($_FILES['product_video']) &&
        $_FILES['product_video']['error'] !== UPLOAD_ERR_NO_FILE
    ) {
        $file = $_FILES['product_video'];

        if ($file['error'] !== UPLOAD_ERR_OK) {
            $errors[] = 'Video upload mein error aaya hai.';
        } elseif (!is_uploaded_file($file['tmp_name'])) {
            $errors[] = 'Invalid video upload.';
        } elseif ($file['size'] > 100 * 1024 * 1024) {
            $errors[] = 'Video maximum 100 MB ki honi chahiye.';
        } else {
            $mime = $finfo->file($file['tmp_name']);

            if (!isset($allowedVideos[$mime])) {
                $errors[] = 'MP4, WEBM, OGG ya MOV video upload karein.';
            } else {
                $validVideo = [
                    'tmp' => $file['tmp_name'],
                    'name' => basename($file['name']),
                    'mime' => $mime,
                    'extension' => $allowedVideos[$mime],
                    'size' => (int)$file['size']
                ];
            }
        }
    }

    /* Save everything in one transaction */

    if (!$errors) {
        $GLOBALS['ap_uploaded_files'] = [];

        try {
            $pdo->beginTransaction();

            $slug = apUniqueSlug($pdo, $form['slug']);
            $publishedAt = $form['status'] === 'published'
                ? date('Y-m-d H:i:s')
                : null;

            // Keep author fields NULL to avoid mismatched admin/user foreign keys.
            $insert = $pdo->prepare("
                INSERT INTO products (
                    name, slug, product_code, cas_number, grade,
                    molecular_formula, molecular_weight, sku,
                    short_description, description, application, packaging,
                    featured_image_id, status, featured, sort_order,
                    published_at, created_by, updated_by
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
                    NULL, ?, ?, ?, ?, NULL, NULL
                )
            ");

            $insert->execute([
                $form['name'],
                $slug,
                $form['product_code'] !== '' ? $form['product_code'] : null,
                $form['cas_number'] !== '' ? $form['cas_number'] : null,
                $form['grade'] !== '' ? $form['grade'] : null,
                $form['molecular_formula'] !== '' ? $form['molecular_formula'] : null,
                $form['molecular_weight'] !== '' ? $form['molecular_weight'] : null,
                $form['sku'] !== '' ? $form['sku'] : null,
                $form['short_description'] !== '' ? $form['short_description'] : null,
                $form['description'] !== '' ? $form['description'] : null,
                $form['application'] !== '' ? $form['application'] : null,
                $form['packaging'] !== '' ? $form['packaging'] : null,
                $form['status'],
                (int)$form['featured'],
                (int)$sortOrder,
                $publishedAt
            ]);

            $productId = (int)$pdo->lastInsertId();

            if ($form['category_id'] !== '') {
                $stmt = $pdo->prepare("
                    INSERT INTO product_categories (product_id, category_id)
                    VALUES (?, ?)
                ");
                $stmt->execute([$productId, (int)$form['category_id']]);
            }

            if ($form['menu_id'] !== '') {
                $stmt = $pdo->prepare("
                    INSERT INTO menu_items (
                        menu_id, parent_id, title, slug, item_type,
                        reference_id, url, target, sort_order, status
                    ) VALUES (?, NULL, ?, ?, 'product', ?, NULL, '_self', ?, 1)
                ");

                $stmt->execute([
                    (int)$form['menu_id'],
                    $form['name'],
                    $slug,
                    $productId,
                    (int)$sortOrder
                ]);
            }

            $featuredImageId = null;

            foreach ($validImages as $index => $image) {
                $media = apStoreMedia(
                    $pdo,
                    $image['tmp'],
                    $image['name'],
                    $image['mime'],
                    $image['extension'],
                    'image',
                    $image['size'],
                    $form['name']
                );

                $role = $index === 0 ? 'featured' : 'gallery';

                apAttachMedia(
                    $pdo,
                    $productId,
                    $media['id'],
                    $role,
                    $index,
                    $form['name']
                );

                if ($index === 0) {
                    $featuredImageId = $media['id'];
                }
            }

            if ($featuredImageId !== null) {
                $stmt = $pdo->prepare("
                    UPDATE products
                    SET featured_image_id = ?
                    WHERE id = ?
                ");
                $stmt->execute([$featuredImageId, $productId]);
            }

            if ($validVideo !== null) {
                $video = apStoreMedia(
                    $pdo,
                    $validVideo['tmp'],
                    $validVideo['name'],
                    $validVideo['mime'],
                    $validVideo['extension'],
                    'video',
                    $validVideo['size'],
                    $form['name'] . ' video'
                );

                apAttachMedia(
                    $pdo,
                    $productId,
                    $video['id'],
                    'video',
                    count($validImages),
                    $form['name'] . ' video'
                );
            }

            $pdo->commit();

            header('Location: add_product.php?saved=1');
            exit;
        } catch (Throwable $exception) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            foreach (($GLOBALS['ap_uploaded_files'] ?? []) as $path) {
                if (is_file($path)) {
                    @unlink($path);
                }
            }

            error_log(
                'Add product error: ' . $exception->getMessage() .
                ' | File: ' . $exception->getFile() .
                ' | Line: ' . $exception->getLine()
            );

            // Local XAMPP diagnostic. Hide detailed errors on production.
            $errors[] = 'Product save error: ' . $exception->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Add Product | Pure Chemical Admin</title>
<style>
:root {
    --green: #16745d;
    --green-dark: #105542;
    --green-soft: #eaf7f1;
    --bg: #f3f6fa;
    --text: #172b3a;
    --muted: #728093;
    --border: #e2e8f0;
    --white: #fff;
    --radius: 17px;
    --shadow: 0 8px 28px rgba(25, 45, 65, .055);
}
* { box-sizing: border-box; }
body {
    margin: 0;
    color: var(--text);
    background: var(--bg);
    font: 14px/1.5 Inter, "Segoe UI", Arial, sans-serif;
}
button, input, select, textarea { font: inherit; }
.ap-main { margin-left: 285px; padding: 28px; min-height: 100vh; }
.ap-container { max-width: 1500px; margin: auto; }
.ap-header {
    display: flex; align-items: center; justify-content: space-between;
    gap: 16px; flex-wrap: wrap; margin-bottom: 24px;
}
.ap-eyebrow {
    color: var(--green); text-transform: uppercase; letter-spacing: 1.5px;
    font-weight: 800; font-size: 11px; margin-bottom: 7px;
}
.ap-header h1 { margin: 0 0 7px; font-size: clamp(26px, 3vw, 35px); letter-spacing: -1px; }
.ap-header p { margin: 0; color: var(--muted); }
.ap-back {
    text-decoration: none; color: var(--text); background: #fff;
    border: 1px solid var(--border); border-radius: 11px;
    padding: 11px 15px; font-weight: 700;
}
.ap-layout {
    display: grid; grid-template-columns: minmax(0, 1fr) 290px;
    gap: 20px; align-items: start;
}
.ap-card, .ap-side {
    background: var(--white); border: 1px solid var(--border);
    border-radius: var(--radius); box-shadow: var(--shadow);
    overflow: hidden; margin-bottom: 20px; min-width: 0;
}
.ap-card-head {
    display: flex; gap: 13px; align-items: center;
    padding: 20px 22px; border-bottom: 1px solid #edf1f5;
}
.ap-icon {
    display: grid; place-items: center; width: 43px; height: 43px;
    flex: 0 0 auto; border-radius: 13px; color: var(--green);
    background: var(--green-soft); font-size: 20px;
}
.ap-card-head h2 { font-size: 15px; margin: 0 0 4px; }
.ap-card-head p { margin: 0; font-size: 12px; color: var(--muted); }
.ap-card-body { padding: 22px; }
.ap-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; }
.ap-field { min-width: 0; }
.ap-full { grid-column: 1 / -1; }
.ap-field label, .ap-label {
    display: block; font-size: 12px; font-weight: 800;
    margin-bottom: 7px; color: #34495e;
}
.ap-required { color: #d83d3d; }
.ap-input, .ap-select, .ap-textarea {
    width: 100%; min-width: 0; border: 1px solid #dce4ec;
    border-radius: 10px; color: var(--text); background: #fff;
    outline: none; transition: .2s;
}
.ap-input, .ap-select { min-height: 44px; padding: 0 12px; }
.ap-textarea { min-height: 105px; padding: 12px; resize: vertical; line-height: 1.65; }
.ap-input:focus, .ap-select:focus, .ap-textarea:focus {
    border-color: var(--green); box-shadow: 0 0 0 3px rgba(22,116,93,.09);
}
.ap-help { color: var(--muted); font-size: 11px; margin-top: 6px; line-height: 1.6; }
.ap-separator { height: 1px; background: #edf1f5; margin: 22px 0; }
.ap-image-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
.ap-image-card {
    border: 1px dashed #cbd7e1; border-radius: 13px; padding: 9px;
    background: #fbfdff; min-width: 0;
}
.ap-image-card:focus-within, .ap-image-card:hover { border-color: var(--green); }
.ap-preview {
    width: 100%; aspect-ratio: 1 / .82; background: #f0f4f7;
    border-radius: 9px; overflow: hidden; display: grid; place-items: center;
    margin-bottom: 10px; color: #9aa8b6; font-size: 25px;
}
.ap-preview img { width: 100%; height: 100%; object-fit: cover; display: none; }
.ap-preview.has-image img { display: block; }
.ap-preview.has-image .ap-placeholder { display: none; }
.ap-placeholder { text-align: center; }
.ap-placeholder small { display: block; font-size: 10px; margin-top: 4px; }
.ap-image-card label { display: block; font-size: 11px; font-weight: 800; margin-bottom: 7px; }
.ap-image-card input { width: 100%; font-size: 10px; min-width: 0; }
.ap-video-box { border: 1px dashed #cbd7e1; border-radius: 13px; padding: 16px; background: #fbfdff; }
.ap-video-row { display: flex; gap: 13px; align-items: center; }
.ap-video-icon {
    width: 48px; height: 48px; flex: 0 0 auto; display: grid;
    place-items: center; background: #f0ebff; color: #7251c5;
    border-radius: 13px; font-size: 21px;
}
.ap-video-row strong { display: block; font-size: 13px; margin-bottom: 4px; }
.ap-video-row p { margin: 0; color: var(--muted); font-size: 11px; }
.ap-video-input { width: 100%; margin-top: 15px; font-size: 12px; }
.ap-video-preview {
    display: none; width: 100%; max-height: 320px;
    margin-top: 15px; background: #111; border-radius: 10px;
}
.ap-side { padding: 20px; }
.ap-side h3 { margin: 0 0 17px; font-size: 14px; }
.ap-side .ap-field { margin-bottom: 17px; }
.ap-check {
    display: flex; align-items: flex-start; gap: 10px; padding: 13px;
    border: 1px solid var(--border); border-radius: 11px; background: #fcfdff;
}
.ap-check input { accent-color: var(--green); margin-top: 4px; }
.ap-check strong { display: block; font-size: 12px; }
.ap-check span { color: var(--muted); font-size: 11px; }
.ap-tip {
    background: #eff8f4; color: #285e50; border-radius: 10px;
    padding: 12px; margin-top: 10px; font-size: 11px; line-height: 1.7;
}
.ap-notice { padding: 14px 17px; border-radius: 11px; margin-bottom: 18px; line-height: 1.7; }
.ap-success { background: #e7f8ee; border: 1px solid #bce8cb; color: #166534; }
.ap-error { background: #fff0ef; border: 1px solid #ffd0cb; color: #982d27; }
.ap-error ul { padding-left: 20px; margin-bottom: 0; }
.ap-actions {
    position: sticky; bottom: 12px; z-index: 5; display: flex; gap: 10px;
    padding: 12px; border: 1px solid var(--border); border-radius: 13px;
    background: rgba(255,255,255,.96); box-shadow: 0 8px 28px rgba(20,42,60,.1);
}
.ap-btn {
    min-height: 44px; display: inline-flex; justify-content: center;
    align-items: center; border: 0; border-radius: 10px; padding: 12px 17px;
    font-size: 12px; font-weight: 800; cursor: pointer; text-decoration: none;
}
.ap-btn-light { background: #edf1f5; color: #34495e; }
.ap-btn-primary { flex: 1; background: var(--green); color: #fff; }
.ap-btn-primary:hover { background: var(--green-dark); }
.ap-footnote { color: var(--muted); font-size: 11px; margin-top: 12px; }
@media (max-width: 1200px) {
    .ap-layout { grid-template-columns: minmax(0, 1fr) 260px; gap: 14px; }
    .ap-main { padding: 20px; }
    .ap-card-body { padding: 17px; }
    .ap-image-grid { gap: 8px; }
}
@media (max-width: 980px) {
    .ap-main { margin-left: 0; padding: 18px; }
    .ap-layout { grid-template-columns: 1fr; }
    .ap-side-column { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
}
@media (max-width: 600px) {
    .ap-main { padding: 12px; }
    .ap-grid { grid-template-columns: 1fr; gap: 14px; }
    .ap-full { grid-column: auto; }
    .ap-image-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
    .ap-side-column { grid-template-columns: 1fr; }
    .ap-card-head { padding: 15px; }
    .ap-card-body { padding: 14px; }
    .ap-actions { flex-wrap: wrap; }
}
</style>
</head>
<body>

<?php
$sidebarPath = __DIR__ . '/sidebar.php';
if (is_file($sidebarPath)) {
    require_once $sidebarPath;
}
?>

<main class="ap-main">
<div class="ap-container">

    <header class="ap-header">
        <div>
            <div class="ap-eyebrow">Product Management / Catalog</div>
            <h1>Add New Product</h1>
            <p>Manage chemical details, category, menu, images and product video.</p>
        </div>
        <a class="ap-back" href="products.php">← Back to Products</a>
    </header>

    <?php if ($saved): ?>
        <div class="ap-notice ap-success">
            <strong>Product successfully saved!</strong>
            Product aur uska selected media database mein save ho gaya hai.
        </div>
    <?php endif; ?>

    <?php if ($pageError !== ''): ?>
        <div class="ap-notice ap-error"><?= apEscape($pageError) ?></div>
    <?php endif; ?>

    <?php if ($errors): ?>
        <div class="ap-notice ap-error">
            <strong>Product save karne mein dikkat aayi:</strong>
            <ul>
                <?php foreach ($errors as $error): ?>
                    <li><?= apEscape($error) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <form method="post" action="add_product.php" enctype="multipart/form-data" id="addProductForm">
        <?= apCsrfField() ?>

        <div class="ap-layout">
            <div>

                <section class="ap-card">
                    <div class="ap-card-head">
                        <div class="ap-icon">✦</div>
                        <div>
                            <h2>Basic Product Information</h2>
                            <p>Product name, URL and chemical identification.</p>
                        </div>
                    </div>
                    <div class="ap-card-body">
                        <div class="ap-grid">
                            <div class="ap-field ap-full">
                                <label for="name">Product Name <span class="ap-required">*</span></label>
                                <input class="ap-input" id="name" name="name" maxlength="255"
                                       required value="<?= apEscape($form['name']) ?>"
                                       placeholder="e.g. Sodium Hydroxide">
                            </div>
                            <div class="ap-field ap-full">
                                <label for="slug">Product URL Slug</label>
                                <input class="ap-input" id="slug" name="slug" maxlength="255"
                                       value="<?= apEscape($form['slug']) ?>"
                                       placeholder="sodium-hydroxide">
                                <div class="ap-help">Blank chhodne par product name se slug banega.</div>
                            </div>
                            <div class="ap-field">
                                <label for="product_code">Product Code</label>
                                <input class="ap-input" id="product_code" name="product_code"
                                       maxlength="100" value="<?= apEscape($form['product_code']) ?>"
                                       placeholder="PRD-001">
                            </div>
                            <div class="ap-field">
                                <label for="sku">SKU</label>
                                <input class="ap-input" id="sku" name="sku" maxlength="150"
                                       value="<?= apEscape($form['sku']) ?>" placeholder="SKU-001">
                            </div>
                            <div class="ap-field">
                                <label for="cas_number">CAS Number</label>
                                <input class="ap-input" id="cas_number" name="cas_number"
                                       maxlength="100" value="<?= apEscape($form['cas_number']) ?>"
                                       placeholder="1310-73-2">
                            </div>
                            <div class="ap-field">
                                <label for="grade">Chemical Grade</label>
                                <input class="ap-input" id="grade" name="grade" maxlength="150"
                                       value="<?= apEscape($form['grade']) ?>"
                                       placeholder="Industrial / Laboratory">
                            </div>
                            <div class="ap-field">
                                <label for="molecular_formula">Molecular Formula</label>
                                <input class="ap-input" id="molecular_formula" name="molecular_formula"
                                       maxlength="255" value="<?= apEscape($form['molecular_formula']) ?>"
                                       placeholder="NaOH">
                            </div>
                            <div class="ap-field">
                                <label for="molecular_weight">Molecular Weight</label>
                                <input class="ap-input" id="molecular_weight" name="molecular_weight"
                                       maxlength="100" value="<?= apEscape($form['molecular_weight']) ?>"
                                       placeholder="40.00 g/mol">
                            </div>
                        </div>
                    </div>
                </section>

                <section class="ap-card">
                    <div class="ap-card-head">
                        <div class="ap-icon">☷</div>
                        <div>
                            <h2>Menu & Product Category</h2>
                            <p>Classify the product and optionally add it to a menu.</p>
                        </div>
                    </div>
                    <div class="ap-card-body">
                        <div class="ap-grid">
                            <div class="ap-field">
                                <label for="category_id">Product Category</label>
                                <select class="ap-select" id="category_id" name="category_id">
                                    <option value="">— Select Category —</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?= (int)$category['id'] ?>"
                                            <?= (string)$form['category_id'] === (string)$category['id'] ? 'selected' : '' ?>>
                                            <?= apEscape($category['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <?php if (!$categories): ?>
                                    <div class="ap-help">Active product categories nahi mili.</div>
                                <?php endif; ?>
                            </div>
                            <div class="ap-field">
                                <label for="menu_id">Website Menu (Optional)</label>
                                <select class="ap-select" id="menu_id" name="menu_id">
                                    <option value="">— Don't add to menu —</option>
                                    <?php foreach ($menus as $menu): ?>
                                        <option value="<?= (int)$menu['id'] ?>"
                                            <?= (string)$form['menu_id'] === (string)$menu['id'] ? 'selected' : '' ?>>
                                            <?= apEscape($menu['name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <?php if (!$menus): ?>
                                    <div class="ap-help">Active menus nahi mile. Menu selection optional hai.</div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="ap-tip">
                            <strong>Note:</strong> Category product ko classify karti hai.
                            Menu select karne par alag menu item create hoga.
                        </div>
                    </div>
                </section>

                <section class="ap-card">
                    <div class="ap-card-head">
                        <div class="ap-icon">≡</div>
                        <div>
                            <h2>Product Description</h2>
                            <p>Website par dikhne wali product information.</p>
                        </div>
                    </div>
                    <div class="ap-card-body">
                        <div class="ap-grid">
                            <div class="ap-field ap-full">
                                <label for="short_description">Short Description</label>
                                <textarea class="ap-textarea" id="short_description"
                                          name="short_description"
                                          placeholder="Product ka short introduction..."><?= apEscape($form['short_description']) ?></textarea>
                            </div>
                            <div class="ap-field ap-full">
                                <label for="description">Full Description</label>
                                <textarea class="ap-textarea" id="description" name="description"
                                          style="min-height:160px"
                                          placeholder="Complete product information..."><?= apEscape($form['description']) ?></textarea>
                            </div>
                            <div class="ap-field ap-full">
                                <label for="application">Applications</label>
                                <textarea class="ap-textarea" id="application" name="application"
                                          placeholder="Industrial uses and applications..."><?= apEscape($form['application']) ?></textarea>
                            </div>
                            <div class="ap-field ap-full">
                                <label for="packaging">Packaging Details</label>
                                <textarea class="ap-textarea" id="packaging" name="packaging"
                                          placeholder="Available packaging sizes..."><?= apEscape($form['packaging']) ?></textarea>
                            </div>
                        </div>
                    </div>
                </section>

                <section class="ap-card">
                    <div class="ap-card-head">
                        <div class="ap-icon">▧</div>
                        <div>
                            <h2>Product Images</h2>
                            <p>Up to 4 images. First uploaded image becomes featured.</p>
                        </div>
                    </div>
                    <div class="ap-card-body">
                        <div class="ap-image-grid">
                            <?php for ($i = 1; $i <= 4; $i++): ?>
                                <div class="ap-image-card">
                                    <div class="ap-preview" id="previewBox<?= $i ?>">
                                        <img id="previewImage<?= $i ?>" alt="Product image preview">
                                        <div class="ap-placeholder">▧<small>Image <?= $i ?></small></div>
                                    </div>
                                    <label for="image_<?= $i ?>">
                                        Image <?= $i ?> <?= $i === 1 ? '(Featured)' : '(Gallery)' ?>
                                    </label>
                                    <input type="file" id="image_<?= $i ?>" name="image_<?= $i ?>"
                                           accept=".jpg,.jpeg,.png,.webp,.gif,image/jpeg,image/png,image/webp,image/gif"
                                           data-preview="<?= $i ?>">
                                </div>
                            <?php endfor; ?>
                        </div>
                        <div class="ap-footnote">
                            JPG, PNG, WEBP or GIF. Maximum 10 MB per image. All images optional hain.
                        </div>
                    </div>
                </section>

                <section class="ap-card">
                    <div class="ap-card-head">
                        <div class="ap-icon">▷</div>
                        <div>
                            <h2>Product Video</h2>
                            <p>Optional product demonstration or promotional video.</p>
                        </div>
                    </div>
                    <div class="ap-card-body">
                        <div class="ap-video-box">
                            <div class="ap-video-row">
                                <div class="ap-video-icon">▶</div>
                                <div>
                                    <strong>Upload Product Video</strong>
                                    <p>MP4, WEBM, OGG or MOV. Maximum 100 MB.</p>
                                </div>
                            </div>
                            <input class="ap-video-input" type="file" id="product_video"
                                   name="product_video"
                                   accept=".mp4,.webm,.ogv,.ogg,.mov,video/mp4,video/webm,video/ogg,video/quicktime">
                            <video class="ap-video-preview" id="videoPreview" controls preload="metadata"></video>
                        </div>
                        <div class="ap-footnote">
                            Video file aur uska record media aur product_media tables mein save hoga.
                        </div>
                    </div>
                </section>

            </div>

            <aside class="ap-side-column">
                <section class="ap-side">
                    <h3>Publishing Settings</h3>
                    <div class="ap-field">
                        <label for="status">Product Status</label>
                        <select class="ap-select" id="status" name="status">
                            <option value="draft" <?= $form['status'] === 'draft' ? 'selected' : '' ?>>Draft</option>
                            <option value="published" <?= $form['status'] === 'published' ? 'selected' : '' ?>>Published</option>
                            <option value="inactive" <?= $form['status'] === 'inactive' ? 'selected' : '' ?>>Inactive</option>
                        </select>
                        <div class="ap-help">Published select karne par publish date set hogi.</div>
                    </div>
                    <div class="ap-field">
                        <label for="sort_order">Sort Order</label>
                        <input class="ap-input" type="number" min="0" step="1"
                               id="sort_order" name="sort_order"
                               value="<?= apEscape($form['sort_order']) ?>">
                    </div>
                    <div class="ap-check">
                        <input type="checkbox" id="featured" name="featured" value="1"
                            <?= $form['featured'] === '1' ? 'checked' : '' ?>>
                        <label for="featured">
                            <strong>Featured Product</strong>
                            <span>Mark this as a featured product.</span>
                        </label>
                    </div>
                </section>

                <section class="ap-side">
                    <h3>Before You Publish</h3>
                    <div class="ap-tip">1. Product name aur chemical details check karein.</div>
                    <div class="ap-tip">2. Zaroorat ke mutabik category select karein.</div>
                    <div class="ap-tip">3. Website menu mein dikhana ho to menu select karein.</div>
                    <div class="ap-tip">4. Images aur video upload karna optional hai.</div>
                </section>

                <section class="ap-side">
                    <h3>Media Limits</h3>
                    <div class="ap-help">Images: maximum 4</div>
                    <div class="ap-help">Image size: 10 MB each</div>
                    <div class="ap-help">Video size: 100 MB</div>
                    <div class="ap-help">Formats: JPG, PNG, WEBP, GIF, MP4, WEBM, OGG, MOV</div>
                </section>
            </aside>
        </div>

        <div class="ap-actions">
            <a class="ap-btn ap-btn-light" href="products.php">Cancel</a>
            <button class="ap-btn ap-btn-primary" type="submit" id="saveProductButton">
                ✓ Save Product
            </button>
        </div>
    </form>
</div>
</main>

<script>
(function () {
    'use strict';

    const nameInput = document.getElementById('name');
    const slugInput = document.getElementById('slug');

    function makeSlug(value) {
        return value.toLowerCase().trim()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
    }

    if (nameInput && slugInput) {
        nameInput.addEventListener('input', function () {
            if (slugInput.dataset.edited !== '1') {
                slugInput.value = makeSlug(nameInput.value);
            }
        });

        slugInput.addEventListener('input', function () {
            slugInput.dataset.edited = slugInput.value.trim() ? '1' : '0';
        });
    }

    document.querySelectorAll('input[data-preview]').forEach(function (input) {
        input.addEventListener('change', function () {
            const number = input.dataset.preview;
            const box = document.getElementById('previewBox' + number);
            const img = document.getElementById('previewImage' + number);
            const file = input.files && input.files[0];

            if (!file) {
                img.removeAttribute('src');
                box.classList.remove('has-image');
                return;
            }

            if (!file.type.startsWith('image/')) {
                alert('Please select a valid image file.');
                input.value = '';
                img.removeAttribute('src');
                box.classList.remove('has-image');
                return;
            }

            const reader = new FileReader();
            reader.onload = function (event) {
                img.src = event.target.result;
                box.classList.add('has-image');
            };
            reader.readAsDataURL(file);
        });
    });

    const videoInput = document.getElementById('product_video');
    const videoPreview = document.getElementById('videoPreview');
    let videoUrl = null;

    if (videoInput && videoPreview) {
        videoInput.addEventListener('change', function () {
            const file = videoInput.files && videoInput.files[0];

            if (videoUrl) {
                URL.revokeObjectURL(videoUrl);
                videoUrl = null;
            }

            if (!file) {
                videoPreview.removeAttribute('src');
                videoPreview.style.display = 'none';
                videoPreview.load();
                return;
            }

            if (!file.type.startsWith('video/')) {
                alert('Please select a valid video file.');
                videoInput.value = '';
                videoPreview.style.display = 'none';
                return;
            }

            videoUrl = URL.createObjectURL(file);
            videoPreview.src = videoUrl;
            videoPreview.style.display = 'block';
            videoPreview.load();
        });
    }

    const form = document.getElementById('addProductForm');
    const button = document.getElementById('saveProductButton');

    if (form && button) {
        form.addEventListener('submit', function (event) {
            if (!form.checkValidity()) {
                return;
            }

            if (button.dataset.submitted === '1') {
                event.preventDefault();
                return;
            }

            button.dataset.submitted = '1';
            button.disabled = true;
            button.textContent = 'Saving Product...';
        });
    }
})();
</script>
</body>
</html>