@extends('layouts.admin')

@section('title', 'Add New Product')

@section('content')
<div style="margin-bottom: 24px;">
    <a href="{{ route('admin.products.index') }}" style="color: var(--text-muted); text-decoration: none; font-size: 13px;">← Back to Product Catalog</a>
    <h1 class="serif" style="font-size: 26px; margin-top: 8px; color: #0f172a;">Create New Skincare Product</h1>
</div>

<div class="admin-card" style="max-width: 950px;">
    <form action="{{ route('admin.products.store') }}" method="POST" enctype="multipart/form-data">
        @csrf
        
        <div style="display: grid; grid-template-columns: 2fr 2fr 1.5fr; gap: 20px; margin-bottom: 20px;">
            <div>
                <label style="display: block; margin-bottom: 6px; font-size: 13px; color: var(--text-muted); font-weight: 500;">Product Name *</label>
                <input type="text" name="name" id="product-name-input" class="form-control" required placeholder="e.g. Milk Cream Face Wash" oninput="onProductNameChange()">
            </div>
            <div>
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
                    <label style="font-size: 13px; color: var(--text-muted); font-weight: 500;">URL Slug (Permalink)</label>
                    <button type="button" onclick="resetSlugFromName()" style="background: none; border: none; color: #186297; font-size: 11px; font-weight: 600; cursor: pointer; text-decoration: underline;">⚡ Sync from Name</button>
                </div>
                <div style="display: flex; align-items: center; background: #f1f5f9; border: 1px solid #cbd5e1; border-radius: 8px; overflow: hidden;">
                    <span style="padding: 0 10px; font-size: 12px; color: #64748b; font-weight: 500; background: #e2e8f0; height: 38px; display: flex; align-items: center; border-right: 1px solid #cbd5e1;">/product/</span>
                    <input type="text" name="slug" id="product-slug-input" class="form-control" style="border: none; border-radius: 0; background: transparent; height: 38px;" oninput="onSlugUserEdit()" placeholder="auto-generated-slug">
                </div>
            </div>
            <div>
                <label style="display: block; margin-bottom: 6px; font-size: 13px; color: var(--text-muted); font-weight: 500;">Category *</label>
                <select name="category_id" class="form-control" required>
                    @foreach($categories as $cat)
                        <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                    @endforeach
                </select>
            </div>
        </div>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 24px;">
            <div>
                <label style="display: block; margin-bottom: 6px; font-size: 13px; color: var(--text-muted); font-weight: 500;">Short Tagline</label>
                <input type="text" name="tag" class="form-control" placeholder="e.g. Gently brightens in one wash">
            </div>
            <div>
                <label style="display: block; margin-bottom: 6px; font-size: 13px; color: var(--text-muted); font-weight: 500;">Badge / Offer Label</label>
                <input type="text" name="badge" class="form-control" placeholder="e.g. Best Seller, Flat 15% Off">
            </div>
        </div>

        <!-- Product Size, Pricing & Stock Variants Manager -->
        <div style="background: #f8faf9; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; margin-bottom: 24px;">
            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; flex-wrap: wrap; gap: 12px;">
                <div>
                    <h3 class="serif" style="font-size: 18px; margin: 0; color: #0f172a; display: flex; align-items: center; gap: 10px;">
                        <span>Product Variants (Sizes, Pricing & Inventory)</span>
                        <span id="total-stock-badge" style="background: #e2e8f0; color: #334155; font-size: 11px; font-weight: 600; padding: 3px 10px; border-radius: 20px;">📦 Total Stock: 85 units</span>
                    </h3>
                    <p style="font-size: 12px; color: var(--text-muted); margin-top: 2px;">Manage size options with specific selling prices, MRP compare prices, and inventory levels.</p>
                </div>
                <button type="button" onclick="addVariantRow()" class="btn-admin btn-secondary" style="padding: 7px 14px; font-size: 12px;">
                    <i data-lucide="plus" style="width: 14px;"></i> Add Size Variant
                </button>
            </div>

            <div style="overflow-x: auto;">
                <table class="admin-table" style="background: white; border-radius: 10px; border: 1px solid #e2e8f0;">
                    <thead>
                        <tr>
                            <th style="width: 180px;">Variant Size *</th>
                            <th>Price (₹) *</th>
                            <th>MRP / Compare (₹)</th>
                            <th>Stock Units *</th>
                            <th style="width: 90px; text-align: center;">Default</th>
                            <th style="width: 60px;">Action</th>
                        </tr>
                    </thead>
                    <tbody id="variants-table-body">
                        <tr>
                            <td><input type="text" name="variant_names[]" value="100 ml" class="form-control" required placeholder="e.g. 100 ml"></td>
                            <td><input type="number" step="0.01" name="variant_prices[]" value="349" class="form-control" required placeholder="349"></td>
                            <td><input type="number" step="0.01" name="variant_compares[]" value="449" class="form-control" placeholder="449"></td>
                            <td><input type="number" name="variant_stocks[]" value="50" class="form-control" required placeholder="50" oninput="calculateTotalStock()"></td>
                            <td style="text-align: center;"><input type="radio" name="variant_default" value="0" checked></td>
                            <td><button type="button" onclick="removeVariantRow(this)" class="btn-admin btn-danger" style="padding: 6px 10px; font-size: 12px;"><i data-lucide="trash-2" style="width: 14px;"></i></button></td>
                        </tr>
                        <tr>
                            <td><input type="text" name="variant_names[]" value="200 ml" class="form-control" required placeholder="e.g. 200 ml"></td>
                            <td><input type="number" step="0.01" name="variant_prices[]" value="595" class="form-control" required placeholder="595"></td>
                            <td><input type="number" step="0.01" name="variant_compares[]" value="699" class="form-control" placeholder="699"></td>
                            <td><input type="number" name="variant_stocks[]" value="35" class="form-control" required placeholder="35" oninput="calculateTotalStock()"></td>
                            <td style="text-align: center;"><input type="radio" name="variant_default" value="1"></td>
                            <td><button type="button" onclick="removeVariantRow(this)" class="btn-admin btn-danger" style="padding: 6px 10px; font-size: 12px;"><i data-lucide="trash-2" style="width: 14px;"></i></button></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Search Engine Optimization (SEO) & Social Meta Section -->
        <div style="background: #f8faf9; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; margin-bottom: 24px;">
            <h3 class="serif" style="font-size: 18px; margin: 0 0 4px 0; color: #0f172a;">Search Engine Optimization (SEO) & Social Meta</h3>
            <p style="font-size: 12px; color: var(--text-muted); margin-bottom: 16px;">Customize how this product appears on Google Search results and social media shares (Facebook, WhatsApp, Twitter).</p>

            <!-- Google Search Snippet Preview Card -->
            <div style="background: white; border: 1px solid #cbd5e1; border-radius: 10px; padding: 16px; margin-bottom: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.05);">
                <div style="font-size: 11px; color: #5f6368; display: flex; align-items: center; gap: 6px; margin-bottom: 4px;">
                    <span style="display: inline-block; width: 16px; height: 16px; border-radius: 50%; background: #186297; color: white; text-align: center; line-height: 16px; font-weight: bold; font-size: 9px;">D</span>
                    <span>https://divnedrops.com › product › <span id="seo-preview-slug">new-product-slug</span></span>
                </div>
                <div id="seo-preview-title" style="font-size: 18px; color: #1a0dab; font-weight: 500; text-decoration: underline; margin-bottom: 4px; cursor: pointer;">
                    Product Title Preview — Divine Drops Luxury Skincare
                </div>
                <div id="seo-preview-desc" style="font-size: 13px; color: #4d5156; line-height: 1.5;">
                    Buy 100% natural Indian skincare online at Divine Drops. Free shipping on orders over ₹499.
                </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 16px;">
                <div>
                    <label style="display: block; margin-bottom: 6px; font-size: 13px; color: var(--text-muted); font-weight: 500;">Meta Title (SEO Title)</label>
                    <input type="text" name="meta_title" id="meta-title-input" class="form-control" placeholder="e.g. Milk Cream Face Wash — Gentle Botanical Cleanser" oninput="updateSeoPreview()">
                    <span style="font-size: 11px; color: var(--text-muted); display: block; margin-top: 4px;">Recommended: 50-60 characters</span>
                </div>
                <div>
                    <label style="display: block; margin-bottom: 6px; font-size: 13px; color: var(--text-muted); font-weight: 500;">Meta Keywords</label>
                    <input type="text" name="meta_keywords" class="form-control" placeholder="e.g. face wash, milk cleanser, natural face wash">
                    <span style="font-size: 11px; color: var(--text-muted); display: block; margin-top: 4px;">Comma-separated keywords</span>
                </div>
            </div>

            <div style="margin-bottom: 16px;">
                <label style="display: block; margin-bottom: 6px; font-size: 13px; color: var(--text-muted); font-weight: 500;">Meta Description</label>
                <textarea name="meta_description" id="meta-desc-input" rows="3" class="form-control" placeholder="Brief summary of product for Google search results..." oninput="updateSeoPreview()"></textarea>
                <span style="font-size: 11px; color: var(--text-muted); display: block; margin-top: 4px;">Recommended: 150-160 characters</span>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <label style="display: block; margin-bottom: 6px; font-size: 13px; color: var(--text-muted); font-weight: 500;">OpenGraph Social Title</label>
                    <input type="text" name="og_title" class="form-control" placeholder="Title for Facebook/WhatsApp shares">
                </div>
                <div>
                    <label style="display: block; margin-bottom: 6px; font-size: 13px; color: var(--text-muted); font-weight: 500;">OpenGraph Social Description</label>
                    <input type="text" name="og_description" class="form-control" placeholder="Description for social shares">
                </div>
            </div>
        </div>

        <!-- Product Images & Gallery Section -->
        <div style="background: #f8faf9; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; margin-bottom: 24px;">
            <h3 class="serif" style="font-size: 18px; margin: 0 0 16px 0; color: #0f172a;">Product Images & Media Gallery</h3>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div style="background: white; border: 1px solid #e2e8f0; border-radius: 10px; padding: 16px;">
                    <label style="display: block; margin-bottom: 8px; font-size: 13px; font-weight: 600; color: #0f172a;">1. Main Display Image *</label>
                    <div style="display: flex; gap: 14px; align-items: center;">
                        <div id="main-preview" style="width: 84px; height: 84px; background: #f1f5f9; border-radius: 8px; overflow: hidden; border: 1px solid #cbd5e1; flex-shrink: 0; display: flex; align-items: center; justify-content: center; color: #94a3b8; font-size: 12px;">
                            Preview
                        </div>
                        <div style="flex: 1;">
                            <input type="file" name="image_file" accept="image/*" class="form-control" style="padding: 8px; font-size: 13px;" onchange="previewImage(this, 'main-preview')">
                            <span style="font-size: 11px; color: var(--text-muted); display: block; margin-top: 6px;">Select main photo file</span>
                        </div>
                    </div>
                </div>

                <div style="background: white; border: 1px solid #e2e8f0; border-radius: 10px; padding: 16px;">
                    <label style="display: block; margin-bottom: 8px; font-size: 13px; font-weight: 600; color: #0f172a;">2. Hover / Secondary Image</label>
                    <div style="display: flex; gap: 14px; align-items: center;">
                        <div id="hover-preview" style="width: 84px; height: 84px; background: #f1f5f9; border-radius: 8px; overflow: hidden; border: 1px solid #cbd5e1; flex-shrink: 0; display: flex; align-items: center; justify-content: center; color: #94a3b8; font-size: 12px;">
                            Preview
                        </div>
                        <div style="flex: 1;">
                            <input type="file" name="hover_image_file" accept="image/*" class="form-control" style="padding: 8px; font-size: 13px;" onchange="previewImage(this, 'hover-preview')">
                            <span style="font-size: 11px; color: var(--text-muted); display: block; margin-top: 6px;">Select hover photo file</span>
                        </div>
                    </div>
                </div>
            </div>

            <div style="background: white; border: 1px solid #e2e8f0; border-radius: 10px; padding: 16px;">
                <label style="display: block; margin-bottom: 8px; font-size: 13px; font-weight: 600; color: #0f172a;">3. Additional Product Gallery Images</label>
                <div>
                    <label style="display: block; margin-bottom: 6px; font-size: 12px; color: #334155; font-weight: 500;">Upload Additional Gallery Photos (Select Multiple Files):</label>
                    <input type="file" name="gallery_files[]" multiple accept="image/*" class="form-control" style="padding: 8px; font-size: 13px;">
                </div>
            </div>
        </div>

        <div style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 6px; font-size: 13px; color: var(--text-muted); font-weight: 500;">Full Description</label>
            <textarea name="description" id="product-desc-input" rows="4" class="form-control" placeholder="Formulated with natural botanicals..." oninput="updateSeoPreview()"></textarea>
        </div>

        <div style="display: flex; gap: 24px; margin-bottom: 24px; color: #334155;">
            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                <input type="checkbox" name="is_featured" value="1" checked> Mark as Featured Product
            </label>
            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                <input type="checkbox" name="is_active" value="1" checked> Active on Storefront
            </label>
        </div>

        <div style="display: flex; gap: 12px;">
            <button type="submit" class="btn-admin btn-primary">Save Product</button>
            <a href="{{ route('admin.products.index') }}" class="btn-admin btn-secondary">Cancel</a>
        </div>
    </form>
</div>

<script>
var isSlugManuallyEdited = false;

function slugify(text) {
    return text.toString().toLowerCase()
        .replace(/\s+/g, '-')
        .replace(/[^\w\-]+/g, '')
        .replace(/\-\-+/g, '-')
        .replace(/^-+/, '')
        .replace(/-+$/, '');
}

function calculateTotalStock() {
    var stockInputs = document.querySelectorAll('input[name="variant_stocks[]"]');
    var total = 0;
    stockInputs.forEach(function(inp) {
        var val = parseInt(inp.value, 10);
        if (!isNaN(val)) total += val;
    });
    var badge = document.getElementById('total-stock-badge');
    if (badge) {
        badge.innerText = '📦 Total Stock: ' + total + ' units across ' + stockInputs.length + ' variants';
    }
}

function onProductNameChange() {
    var name = document.getElementById('product-name-input').value;
    var slugField = document.getElementById('product-slug-input');

    if (!isSlugManuallyEdited) {
        slugField.value = slugify(name);
    }
    updateSeoPreview();
}

function onSlugUserEdit() {
    isSlugManuallyEdited = true;
    updateSeoPreview();
}

function resetSlugFromName() {
    isSlugManuallyEdited = false;
    var name = document.getElementById('product-name-input').value;
    document.getElementById('product-slug-input').value = slugify(name);
    updateSeoPreview();
}

function updateSeoPreview() {
    var name = document.getElementById('product-name-input').value;
    var slugInput = document.getElementById('product-slug-input').value;
    var metaTitle = document.getElementById('meta-title-input').value;
    var metaDesc = document.getElementById('meta-desc-input').value;
    var prodDesc = document.getElementById('product-desc-input').value;

    var slugTarget = document.getElementById('seo-preview-slug');
    var titleTarget = document.getElementById('seo-preview-title');
    var descTarget = document.getElementById('seo-preview-desc');

    slugTarget.innerText = slugInput || (name ? slugify(name) : 'new-product-slug');
    titleTarget.innerText = metaTitle || (name ? name + ' — Divine Drops Luxury Skincare' : 'Product Title Preview');
    descTarget.innerText = metaDesc || (prodDesc ? prodDesc.substring(0, 155) : 'Buy 100% natural Indian skincare online at Divine Drops. Free shipping on orders over ₹499.');
}

function previewImage(input, previewId) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var target = document.getElementById(previewId);
            target.innerHTML = '<img src="' + e.target.result + '" style="width:100%;height:100%;object-fit:cover;">';
        }
        reader.readAsDataURL(input.files[0]);
    }
}

function addVariantRow() {
    var tbody = document.getElementById('variants-table-body');
    var rowCount = tbody.rows.length;
    var tr = document.createElement('tr');
    tr.innerHTML = `
        <td><input type="text" name="variant_names[]" placeholder="e.g. 200 ml" class="form-control" required></td>
        <td><input type="number" step="0.01" name="variant_prices[]" placeholder="695" class="form-control" required></td>
        <td><input type="number" step="0.01" name="variant_compares[]" placeholder="799" class="form-control"></td>
        <td><input type="number" name="variant_stocks[]" value="50" class="form-control" required oninput="calculateTotalStock()"></td>
        <td style="text-align: center;"><input type="radio" name="variant_default" value="${rowCount}"></td>
        <td>
            <button type="button" onclick="removeVariantRow(this)" class="btn-admin btn-danger" style="padding: 6px 10px; font-size: 12px;">
                <i data-lucide="trash-2" style="width: 14px;"></i>
            </button>
        </td>
    `;
    tbody.appendChild(tr);
    lucide.createIcons();
    calculateTotalStock();
}

function removeVariantRow(btn) {
    var tbody = document.getElementById('variants-table-body');
    if (tbody.rows.length > 1) {
        btn.closest('tr').remove();
        calculateTotalStock();
    } else {
        alert('At least one product variant is required.');
    }
}

document.addEventListener('DOMContentLoaded', calculateTotalStock);
</script>
@endsection
