<?php

/**
 * Agentic Square - Digital Product Licensing Wizard Engine
 * CodeCanyon Commercial Premium Core Architecture
 */

require_once __DIR__ . '/../config/config.php';

// Access Control Interceptor Guard
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'seller') {
    header('Location: ../login.php');
    exit;
}

$user_id = (int)$_SESSION['user_id'];

// Cross-Reference Authorization Step: Check if seller profile exists
$checkSeller = $pdo->prepare("SELECT * FROM sellers WHERE user_id = ? LIMIT 1");
$checkSeller->execute([$user_id]);
$sellerProfile = $checkSeller->fetch();

// Dynamic extraction of catalog nodes for configuration drops
try {
    // Attempt standard ordering
    $categories = $pdo->query("SELECT * FROM categories ORDER BY name ASC")->fetchAll();
} catch (\PDOException $e) {
    // Fallback if 'name' column doesn't exist (e.g., table uses 'title', 'category_name', or just 'id')
    try {
        $categories = $pdo->query("SELECT * FROM categories ORDER BY title ASC")->fetchAll();
    } catch (\PDOException $ex) {
        // Ultimate safe fallback: grab everything sorted by primary key ID
        $categories = $pdo->query("SELECT * FROM categories ORDER BY id ASC")->fetchAll();
    }
}

$error_msg = "";

// Submission Transaction Hook Execution
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $sellerProfile) {
    $item_name      = substr(trim($_POST['item_name'] ?? ''), 0, 30);
    $item_slug      = trim($_POST['item_slug'] ?? '');
    $category_id    = (int)($_POST['category_id'] ?? 0);
    $amount         = (float)($_POST['amount'] ?? 0.00);
    $item_details   = trim($_POST['item_details'] ?? '');
    $video_url      = trim($_POST['video_url'] ?? '');
    $demo_url       = trim($_POST['demo_url'] ?? '');
    $files_included = trim($_POST['files_included'] ?? '');
    $ai_brain_used  = trim($_POST['ai_brain_used'] ?? '');
    $support_days   = (int)($_POST['support_days'] ?? 365);

    // Slug Validation Engine Checks
    $checkSlug = $pdo->prepare("SELECT id FROM items WHERE item_slug = ? LIMIT 1");
    $checkSlug->execute([$item_slug]);

    if ($checkSlug->fetch()) {
        $error_msg = "Asset conflict detected: The item SLUG provided is already reserved by another framework product.";
    } else {
        // Upload Handlers Pipeline
        $uploadDir = __DIR__ . '/../uploads/products/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $images = [
            'feature_image' => '',
            'screenshot_2' => null,
            'screenshot_3' => null
        ];

        $item_zip_file = null;
        foreach (['img1', 'img2', 'img3'] as $idx => $key) {
            $targetColumn = ($idx === 0) ? 'feature_image' : 'screenshot_' . ($idx + 1);
            if (isset($_FILES[$key]) && $_FILES[$key]['error'] === UPLOAD_ERR_OK) {
                $fileTmp = $_FILES[$key]['tmp_name'];
                $fileName = time() . '_' . $idx . '_' . preg_replace("/[^a-zA-Z0-9.]/", "_", $_FILES[$key]['name']);
                if (move_uploaded_file($fileTmp, $uploadDir . $fileName)) {
                    $images[$targetColumn] = 'uploads/products/' . $fileName;
                }
            }
        }
        // ZIP File Upload
        if (isset($_FILES['item_zip']) && $_FILES['item_zip']['error'] === UPLOAD_ERR_OK) {

            $zipExt = strtolower(pathinfo($_FILES['item_zip']['name'], PATHINFO_EXTENSION));

            if ($zipExt !== 'zip') {

                $error_msg = "Only ZIP files are allowed.";
            } else {

                $zipDir = __DIR__ . '/../uploads/products/zips/';

                if (!is_dir($zipDir)) {
                    mkdir($zipDir, 0755, true);
                }

                $zipName = time() . '_product_' .
                    preg_replace("/[^a-zA-Z0-9.]/", "_", $_FILES['item_zip']['name']);

                if (move_uploaded_file($_FILES['item_zip']['tmp_name'], $zipDir . $zipName)) {

                    $item_zip_file = 'uploads/products/zips/' . $zipName;
                } else {

                    $error_msg = "Failed to upload ZIP file.";
                }
            }
        }

        if (empty($images['feature_image'])) {

            $error_msg = "Foundational configuration baseline missing: Item Cover/Feature Image file required.";
        } elseif (empty($item_zip_file)) {

            $error_msg = "Product ZIP file is required.";
        } else {
            $insertItem = $pdo->prepare("INSERT INTO items (
user_id,
seller_id,
item_name,
item_slug,
category_id,
amount,
item_details,
feature_image,
screenshot_2,
screenshot_3,
item_zip_file,
video_url,
demo_url,
files_included,
ai_brain_used,
support_days,
status
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')");
            $insertItem->execute([
                $user_id,
                $sellerProfile['id'],
                $item_name,
                $item_slug,
                $category_id,
                $amount,
                $item_details,
                $images['feature_image'],
                $images['screenshot_2'],
                $images['screenshot_3'],
                $item_zip_file,
                $video_url,
                $demo_url,
                $files_included,
                $ai_brain_used,
                $support_days
            ]);

            header('Location: seller-dashboard.php?upload=success');
            exit;
        }
    }
}

require_once __DIR__ . '/../sections/header.php';
?>

<body class="bg-nftDark text-white antialiased overflow-x-hidden">
    <?php include_once __DIR__ . '/seller-sidebar.php'; ?>

    <?php if (!$sellerProfile): ?>
        <div class="fixed inset-0 bg-slate-950/90 backdrop-blur-md z-[100] flex items-center justify-center p-4">
            <div class="glass-card max-w-md w-full p-8 border border-slate-800 text-center space-y-6 rounded-3xl relative">
                <div class="w-16 h-16 bg-nftAccentPurple/10 border border-nftAccentPurple/30 text-nftAccentPurple text-3xl rounded-2xl flex items-center justify-center mx-auto shadow-xl">
                    <i class="fa-solid fa-store-slash"></i>
                </div>
                <div class="space-y-2">
                    <h3 class="text-xl font-extrabold tracking-wide text-white">Merchant Record Uninitialized</h3>
                    <p class="text-xs text-nftTextGray leading-relaxed">Envato deployment quality regulations dictate all developer pipelines must populate metadata context blocks before publishing products.</p>
                </div>
                <div class="pt-2">
                    <a href="profile.php" class="btn-gradient w-full block text-center py-3.5 rounded-xl text-xs font-bold uppercase tracking-widest text-white shadow-lg">
                        <i class="fa-solid fa-address-card mr-2"></i> Configure Storefront Profile
                    </a>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-16 px-4 sm:px-6 lg:px-8">
        <div class="max-w-4xl mx-auto space-y-8">
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div>
                    <span class="text-xs font-bold tracking-widest text-nftAccentCyan uppercase block mb-1">// Automation Blueprint Foundry</span>
                    <h1 class="text-3xl font-extrabold tracking-tight text-white">Deploy Engine Architecture</h1>
                    <p class="text-sm text-nftTextGray mt-1">Initialize production parameters for decentralized commercial sales loops.</p>
                </div>
            </div>

            <div class="grid grid-cols-3 bg-slate-950 p-1.5 rounded-xl border border-slate-900/60 text-center text-xs font-bold tracking-wider uppercase">
                <div id="tab-indicator-1" class="py-2.5 rounded-lg text-nftAccentCyan bg-slate-900 border border-slate-800/80 transition-all">1. Identity</div>
                <div id="tab-indicator-2" class="py-2.5 rounded-lg text-nftTextGray transition-all">2. Ecosystem</div>
                <div id="tab-indicator-3" class="py-2.5 rounded-lg text-nftTextGray transition-all">3. Interface Assets</div>
            </div>

            <?php if (!empty($error_msg)): ?>
                <div class="p-4 rounded-xl bg-rose-500/10 border border-rose-500/20 text-rose-400 text-xs font-semibold">
                    <i class="fa-solid fa-triangle-exclamation mr-1.5"></i> <?php echo $error_msg; ?>
                </div>
            <?php endif; ?>

            <form id="wizard-form" action="" method="POST" enctype="multipart/form-data" class="glass-card p-8 rounded-3xl border border-slate-800/80 min-h-[400px] flex flex-col justify-between">

                <div id="step-pane-1" class="space-y-5 animate-fadeIn">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div>
                            <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Item Engine Name (Max 30 Chars)</label>
                            <input type="text" id="item_name" name="item_name" required maxlength="30" class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="e.g. Autonomous Agent Builder">
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Item Resource URL SLUG</label>
                            <input type="text" id="item_slug" name="item_slug" required readonly class="w-full bg-slate-950/60 border border-slate-900 text-sm text-nftAccentCyan font-mono rounded-xl px-4 py-3 focus:outline-none" placeholder="auto-generated-slug-string">
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Platform Repository Category Matrix</label>
                            <select name="category_id" required class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-slate-300 focus:outline-none focus:border-nftAccentCyan transition-colors">
                                <option value="">-- Choose Module Node Class --</option>
                                <?php foreach ($categories as $cat): ?>
                                    <?php
                                    $display_name = $cat['category_name'] ?? $cat['title'] ?? 'Category #' . $cat['id'];
                                    ?>
                                    <option value="<?php echo $cat['id']; ?>">
                                        <?php echo htmlspecialchars($display_name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Commercial License Base Valuation (<?php echo htmlspecialchars(get_site_currency(), ENT_QUOTES, 'UTF-8'); ?>)</label>
                            <input type="number" step="0.01" min="0.00" name="amount" required class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="49.00">
                        </div>
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Architecture Details & Document Operations (HTML Approved)</label>
                        <textarea name="item_details" rows="6" required class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors placeholder-slate-700" placeholder="Provide system build constraints, environment variables, dependencies..."></textarea>
                    </div>
                </div>

                <div id="step-pane-2" class="space-y-5 hidden animate-fadeIn">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div>
                            <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Files Included Stack Array (Comma Separated)</label>
                            <input type="text" name="files_included" required class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="e.g. PHP, HTML, CSS, JS, SQL">
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">AI Brain Core Engines Required (Comma Separated)</label>
                            <input type="text" name="ai_brain_used" required class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="e.g. ChatGPT, Claude, Gemini">
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Extended System Support Lifetime</label>
                            <select name="support_days" class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-slate-300 focus:outline-none focus:border-nftAccentCyan transition-colors">
                                <option value="365">365 Days Premium Technical Retainer Coverage</option>
                                <option value="180">180 Days Standard Engineering Retainer Coverage</option>
                                <option value="90">90 Days Limited Base Deployment Warranty</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Live Demonstration / Proof-of-Concept Endpoint</label>
                            <input type="url" name="demo_url" class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="https://demo.agenticsquare.com">
                        </div>
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Explainer Technical Product Showcase Video URL (Optional)</label>
                        <input type="url" name="video_url" class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="https://youtube.com/watch?v=video_hash">
                    </div>
                </div>

                <div id="step-pane-3" class="space-y-5 hidden animate-fadeIn">
                    <div class="p-4 rounded-xl bg-nftAccentPurple/10 border border-nftAccentPurple/20 text-xs text-nftTextGray leading-relaxed">
                        <i class="fa-solid fa-circle-info text-nftAccentPurple mr-1"></i> File arrays require compressed PNG or JPEG payloads matching clean viewport dimensions for accurate marketplace listing renders.
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-5">
                        <div class="bg-slate-950 p-5 rounded-2xl border border-slate-900 text-center space-y-3">
                            <span class="block text-[10px] font-bold uppercase text-nftAccentCyan tracking-widest">1. Cover Asset (Feature)</span>
                            <div class="h-28 border border-dashed border-slate-800 rounded-xl flex items-center justify-center bg-slate-900/50 relative overflow-hidden group">
                                <div class="preview-placeholder flex flex-col items-center justify-center pointer-events-none transition-all">
                                    <i class="fa-solid fa-cloud-arrow-up text-xl text-slate-700"></i>
                                </div>
                                <img class="image-preview hidden absolute inset-0 w-full h-full object-cover pointer-events-none" src="" alt="Cover Preview">
                                <input type="file" name="img1" required class="absolute inset-0 opacity-0 cursor-pointer preview-input" accept="image/*">
                            </div>
                        </div>
                        <div class="bg-slate-950 p-5 rounded-2xl border border-slate-900 text-center space-y-3">
                            <span class="block text-[10px] font-bold uppercase text-nftTextGray tracking-widest">2. Viewport Screen 2</span>
                            <div class="h-28 border border-dashed border-slate-800 rounded-xl flex items-center justify-center bg-slate-900/50 relative overflow-hidden group">
                                <div class="preview-placeholder flex flex-col items-center justify-center pointer-events-none transition-all">
                                    <i class="fa-solid fa-images text-xl text-slate-700"></i>
                                </div>
                                <img class="image-preview hidden absolute inset-0 w-full h-full object-cover pointer-events-none" src="" alt="Screen 2 Preview">
                                <input type="file" name="img2" class="absolute inset-0 opacity-0 cursor-pointer preview-input" accept="image/*">
                            </div>
                        </div>
                        <div class="bg-slate-950 p-5 rounded-2xl border border-slate-900 text-center space-y-3">
                            <span class="block text-[10px] font-bold uppercase text-nftTextGray tracking-widest">3. Viewport Screen 3</span>
                            <div class="h-28 border border-dashed border-slate-800 rounded-xl flex items-center justify-center bg-slate-900/50 relative overflow-hidden group">
                                <div class="preview-placeholder flex flex-col items-center justify-center pointer-events-none transition-all">
                                    <i class="fa-solid fa-images text-xl text-slate-700"></i>
                                </div>
                                <img class="image-preview hidden absolute inset-0 w-full h-full object-cover pointer-events-none" src="" alt="Screen 3 Preview">
                                <input type="file" name="img3" class="absolute inset-0 opacity-0 cursor-pointer preview-input" accept="image/*">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="bg-slate-950 p-5 rounded-2xl border border-slate-900 text-center space-y-3 mt-6">

                    <span class="block text-[10px] font-bold uppercase text-nftAccentCyan tracking-widest">
                        Product ZIP File
                    </span>

                    <div class="p-6 border border-dashed border-slate-800 rounded-xl bg-slate-900/50">

                        <input
                            type="file"
                            name="item_zip"
                            required
                            accept=".zip"
                            class="w-full text-sm text-slate-300">

                        <p class="text-xs text-slate-500 mt-2">
                            Upload your product ZIP package.
                        </p>

                    </div>

                </div>

                <div class="mt-8 pt-6 border-t border-slate-900/60 flex items-center justify-between">
                    <button type="button" id="prev-btn" class="bg-slate-900 border border-slate-800 hover:border-slate-700 px-6 py-2.5 rounded-xl text-xs font-bold uppercase tracking-widest text-slate-400 invisible transition-all">
                        &larr; Return Back
                    </button>
                    <button type="button" id="next-btn" class="btn-gradient px-8 py-3 rounded-xl text-xs font-bold uppercase tracking-widest text-white shadow-xl transition-all">
                        Advance Engine &rarr;
                    </button>
                </div>

            </form>
        </div>
    </main>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Live sanitized slug pipeline loop logic
            const nameInput = document.getElementById('item_name');
            const slugInput = document.getElementById('item_slug');

            if (nameInput && slugInput) {
                nameInput.addEventListener('input', function() {
                    let text = this.value.toLowerCase()
                        .replace(/[^a-z0-9\s-]/g, '')
                        .replace(/\s+/g, '-')
                        .replace(/-+/g, '-');
                    slugInput.value = text.trim();
                });
            }

            // Live Image Preview Engine Implementation
            const previewInputs = document.querySelectorAll('.preview-input');

            previewInputs.forEach(input => {
                input.addEventListener('change', function() {
                    const box = this.closest('.relative');
                    const placeholder = box.querySelector('.preview-placeholder');
                    const previewImg = box.querySelector('.image-preview');
                    const file = this.files[0];

                    if (file) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            previewImg.src = e.target.result;
                            previewImg.classList.remove('hidden');
                            placeholder.classList.add('opacity-0', 'scale-75');
                        }
                        reader.readAsDataURL(file);
                    } else {
                        previewImg.src = "";
                        previewImg.classList.add('hidden');
                        placeholder.classList.remove('opacity-0', 'scale-75');
                    }
                });
            });

            // Multi-Step Layout Pane Rotation Sequence Mechanics
            let currentStep = 1;
            const totalSteps = 3;

            const nextBtn = document.getElementById('next-btn');
            const prevBtn = document.getElementById('prev-btn');

            function updateWizardUI() {
                for (let i = 1; i <= totalSteps; i++) {
                    const pane = document.getElementById(`step-pane-${i}`);
                    const tab = document.getElementById(`tab-indicator-${i}`);

                    if (i === currentStep) {
                        pane.classList.remove('hidden');
                        tab.className = "py-2.5 rounded-lg text-nftAccentCyan bg-slate-900 border border-slate-800/80 transition-all";
                    } else {
                        pane.classList.add('hidden');
                        tab.className = "py-2.5 rounded-lg text-nftTextGray transition-all";
                    }
                }

                // Back control visibility toggle flags
                if (currentStep === 1) {
                    prevBtn.classList.add('invisible');
                } else {
                    prevBtn.classList.remove('invisible');
                }

                // Submission loop structural execution mutations
                if (currentStep === totalSteps) {
                    nextBtn.innerHTML = '<i class="fa-solid fa-cloud-arrow-up mr-1"></i> Finalize and Upload';
                } else {
                    nextBtn.innerText = 'Advance Engine \u2192';
                }
            }

            nextBtn.addEventListener('click', function() {
                // Native constraint checker pipeline fallback
                const currentFields = document.getElementById(`step-pane-${currentStep}`).querySelectorAll('[required]');
                let stepValid = true;

                currentFields.forEach(field => {
                    if (!field.checkValidity()) {
                        field.reportValidity();
                        stepValid = false;
                    }
                });

                if (!stepValid) return;

                if (currentStep < totalSteps) {
                    currentStep++;
                    updateWizardUI();
                } else {
                    document.getElementById('wizard-form').submit();
                }
            });

            prevBtn.addEventListener('click', function() {
                if (currentStep > 1) {
                    currentStep--;
                    updateWizardUI();
                }
            });
        });
    </script>
</body>

</html>
