<?php
/**
 * Agentic Square - Admin Item Creation Console
 * Path: admin/add-item.php
 */

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

if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$success_message = '';
$error_message = '';

$categories = $pdo->query("SELECT * FROM categories ORDER BY category_name ASC")->fetchAll(PDO::FETCH_ASSOC);
$sellers = $pdo->query("SELECT id, user_id, seller_name FROM sellers ORDER BY seller_name ASC")->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $seller_db_id = (int)($_POST['seller_id'] ?? 0);
    $item_name = substr(trim($_POST['item_name'] ?? ''), 0, 255);
    $item_slug = trim($_POST['item_slug'] ?? '');
    $category_id = (int)($_POST['category_id'] ?? 0);
    $amount = max(0, (float)($_POST['amount'] ?? 0));
    $item_details = trim($_POST['item_details'] ?? '');
    $files_included = trim($_POST['files_included'] ?? '');
    $ai_brain_used = trim($_POST['ai_brain_used'] ?? '');
    $demo_url = trim($_POST['demo_url'] ?? '');
    $video_url = trim($_POST['video_url'] ?? '');
    $support_days = (int)($_POST['support_days'] ?? 365);

    $selectedSeller = null;
    foreach ($sellers as $seller) {
        if ((int)$seller['id'] === $seller_db_id) {
            $selectedSeller = $seller;
            break;
        }
    }

    if (!$selectedSeller || $item_name === '' || $item_slug === '' || $category_id <= 0 || $item_details === '') {
        $error_message = 'Please complete seller, name, slug, category, and description fields.';
    } else {
        $slugStmt = $pdo->prepare("SELECT id FROM items WHERE item_slug = ? LIMIT 1");
        $slugStmt->execute([$item_slug]);

        if ($slugStmt->fetch()) {
            $error_message = 'This item slug is already used. Please choose a unique slug.';
        } else {
            $uploadDir = __DIR__ . '/../uploads/products/';
            $zipDir = __DIR__ . '/../uploads/products/zips/';

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

            $images = [
                'feature_image' => '',
                'screenshot_2' => null,
                'screenshot_3' => 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) {
                    continue;
                }

                $extension = strtolower(pathinfo($_FILES[$key]['name'], PATHINFO_EXTENSION));
                if (!in_array($extension, ['jpg', 'jpeg', 'png', 'webp', 'gif'], true)) {
                    $error_message = 'Only JPG, PNG, WEBP, or GIF images are allowed.';
                    break;
                }

                $fileName = time() . '_' . $idx . '_' . preg_replace('/[^a-zA-Z0-9.]/', '_', $_FILES[$key]['name']);
                if (move_uploaded_file($_FILES[$key]['tmp_name'], $uploadDir . $fileName)) {
                    $images[$targetColumn] = 'uploads/products/' . $fileName;
                }
            }

            $item_zip_file = null;
            if ($error_message === '' && isset($_FILES['item_zip']) && $_FILES['item_zip']['error'] === UPLOAD_ERR_OK) {
                $zipExt = strtolower(pathinfo($_FILES['item_zip']['name'], PATHINFO_EXTENSION));
                if ($zipExt !== 'zip') {
                    $error_message = 'Only ZIP files are allowed for the product package.';
                } else {
                    $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;
                    }
                }
            }

            if ($error_message === '' && $images['feature_image'] === '') {
                $error_message = 'Feature image is required.';
            } elseif ($error_message === '' && empty($item_zip_file)) {
                $error_message = 'Product ZIP file is required.';
            }

            if ($error_message === '') {
                $stmt = $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')
                ");
                $stmt->execute([
                    (int)$selectedSeller['user_id'],
                    (int)$selectedSeller['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,
                ]);

                $success_message = 'Item created successfully.';
            }
        }
    }
}

$page_title = 'Add New Item';
require_once __DIR__ . '/../sections/header.php';
?>

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

    <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-5xl mx-auto space-y-8">
            <div class="border-b border-slate-900/60 pb-6">
                <span class="text-xs font-bold tracking-widest text-nftAccentCyan uppercase block mb-1">// Digital Core Catalog</span>
                <h1 class="text-3xl font-extrabold tracking-tight text-white">Add New Item</h1>
                <p class="text-sm text-nftTextGray mt-1">Create a marketplace item for a selected seller profile.</p>
            </div>

            <?php if ($success_message): ?>
                <div class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 p-4 rounded-xl text-xs font-mono">
                    <?php echo htmlspecialchars($success_message, ENT_QUOTES, 'UTF-8'); ?>
                </div>
            <?php endif; ?>

            <?php if ($error_message): ?>
                <div class="bg-rose-500/10 border border-rose-500/20 text-rose-400 p-4 rounded-xl text-xs font-mono">
                    <?php echo htmlspecialchars($error_message, ENT_QUOTES, 'UTF-8'); ?>
                </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data" class="glass-card p-6 rounded-2xl border border-slate-800/80 bg-slate-950/20 space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div class="space-y-2">
                        <label class="text-xs font-bold uppercase text-nftTextGray">Seller</label>
                        <select name="seller_id" required class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none">
                            <option value="">Select seller</option>
                            <?php foreach ($sellers as $seller): ?>
                                <option value="<?php echo (int)$seller['id']; ?>"><?php echo htmlspecialchars($seller['seller_name'], ENT_QUOTES, 'UTF-8'); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="space-y-2">
                        <label class="text-xs font-bold uppercase text-nftTextGray">Category</label>
                        <select name="category_id" required class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none">
                            <option value="">Select category</option>
                            <?php foreach ($categories as $category): ?>
                                <option value="<?php echo (int)$category['id']; ?>"><?php echo htmlspecialchars($category['category_name'] ?? ('Category #' . $category['id']), ENT_QUOTES, 'UTF-8'); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="space-y-2">
                        <label class="text-xs font-bold uppercase text-nftTextGray">Item Name</label>
                        <input type="text" id="item_name" name="item_name" required class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none">
                    </div>
                    <div class="space-y-2">
                        <label class="text-xs font-bold uppercase text-nftTextGray">Item Slug</label>
                        <input type="text" id="item_slug" name="item_slug" required class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none font-mono text-nftAccentCyan">
                    </div>
                    <div class="space-y-2">
                        <label class="text-xs font-bold uppercase text-nftTextGray">Price</label>
                        <input type="number" step="0.01" min="0" name="amount" required class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none">
                    </div>
                    <div class="space-y-2">
                        <label class="text-xs font-bold uppercase text-nftTextGray">Support Days</label>
                        <input type="number" min="0" name="support_days" value="365" required class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none">
                    </div>
                </div>

                <div class="space-y-2">
                    <label class="text-xs font-bold uppercase text-nftTextGray">Details</label>
                    <textarea name="item_details" rows="6" required class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none resize-none"></textarea>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <input type="text" name="files_included" placeholder="Files included" class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none">
                    <input type="text" name="ai_brain_used" placeholder="AI tools used" class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none">
                    <input type="url" name="demo_url" placeholder="Demo URL" class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none">
                    <input type="url" name="video_url" placeholder="Video URL" class="w-full bg-slate-950 p-3 rounded-xl border border-slate-800 focus:border-nftAccentCyan outline-none">
                </div>

                <div class="grid grid-cols-1 md:grid-cols-4 gap-5">
                    <label class="space-y-2 text-xs font-bold uppercase text-nftTextGray">Feature Image<input type="file" name="img1" accept="image/*" required class="block w-full text-slate-300"></label>
                    <label class="space-y-2 text-xs font-bold uppercase text-nftTextGray">Screenshot 2<input type="file" name="img2" accept="image/*" class="block w-full text-slate-300"></label>
                    <label class="space-y-2 text-xs font-bold uppercase text-nftTextGray">Screenshot 3<input type="file" name="img3" accept="image/*" class="block w-full text-slate-300"></label>
                    <label class="space-y-2 text-xs font-bold uppercase text-nftTextGray">Product ZIP<input type="file" name="item_zip" accept=".zip" required class="block w-full text-slate-300"></label>
                </div>

                <button type="submit" class="w-full py-4 rounded-xl bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple font-bold text-white uppercase tracking-widest hover:opacity-90 transition-all">
                    Create Item
                </button>
            </form>
        </div>
    </main>

    <script>
        document.getElementById('item_name')?.addEventListener('input', function () {
            const slug = this.value.toLowerCase().replace(/[^a-z0-9\s-]/g, '').replace(/\s+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
            document.getElementById('item_slug').value = slug;
        });
    </script>
</body>
</html>
