@extends('layouts.admin')

@section('title', 'Create Product')

@push('styles')
<link rel="stylesheet" href="{{ asset('css/admin-product-form.css') }}">
@endpush

@section('content')
@php
    $defaultShipping = old('shipping_days', \App\Models\Setting::get('default_shipping_days'));
@endphp

<div class="pp-page tw-migrated">
    <nav class="pp-crumb" aria-label="Breadcrumb">
        <span>Catalogue</span>
        <span class="pp-crumb__sep">/</span>
        <a href="{{ route('admin.products.index') }}">Products</a>
        <span class="pp-crumb__sep">/</span>
        <span class="pp-crumb__current">Create</span>
    </nav>

    <div class="pp-header">
        <h1>Create Product</h1>
        <div class="pp-header__actions">
            <a href="{{ route('admin.products.index') }}" class="pp-btn pp-btn--ghost">
                <i class="bi bi-arrow-left"></i> Back
            </a>
            <button type="submit" form="productForm" class="pp-btn pp-btn--primary">
                <i class="bi bi-save"></i> Save Product
            </button>
        </div>
    </div>

    @if ($errors->any())
        <x-ui.alert type="danger" class="mb-3">
            <ul class="mb-0">@foreach ($errors->all() as $e)<li>{{ $e }}</li>@endforeach</ul>
        </x-ui.alert>
    @endif

    <form id="productForm" action="{{ route('admin.products.store') }}" method="POST" enctype="multipart/form-data">
        @csrf

        <div class="pp-layout">
            <div class="pp-main">
                <section class="pp-card">
                    <div class="pp-card__head">
                        <span class="pp-card__icon"><i class="bi bi-info-circle"></i></span>
                        <div>
                            <h2 class="pp-card__title">Basic Information</h2>
                            <p class="pp-card__sub">Name, category and searchable tags</p>
                        </div>
                    </div>
                    <div class="pp-card__body">
                        <div class="pp-grid pp-grid--2">
                            <div class="pp-field">
                                <label for="name">Product Name <span class="pp-req">*</span></label>
                                <input type="text" name="name" id="name" class="form-control @error('name') is-invalid @enderror"
                                       value="{{ old('name') }}" required placeholder="Enter product name"
                                       data-pp-sync="name">
                                @error('name')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                            </div>
                            <div class="pp-field">
                                <label for="category_id">Category <span class="pp-req">*</span></label>
                                <select name="category_id" id="category_id" class="form-select @error('category_id') is-invalid @enderror" required data-pp-sync="category">
                                    <option value="">Select Category</option>
                                    @foreach ($categories as $category)
                                        <option value="{{ $category->id }}" {{ (string) old('category_id') === (string) $category->id ? 'selected' : '' }}>
                                            {{ $category->name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('category_id')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                            </div>
                            <div class="pp-field">
                                <label for="barcode">Barcode</label>
                                <div class="pp-barcode-row">
                                    <input type="text" name="barcode" id="barcode" class="form-control @error('barcode') is-invalid @enderror"
                                           value="{{ old('barcode') }}" maxlength="8" placeholder="Auto-generated">
                                    <button type="button" class="pp-btn pp-btn--ghost" onclick="generateNewBarcode()" title="Generate barcode">
                                        <i class="bi bi-arrow-clockwise"></i>
                                    </button>
                                </div>
                                <span class="pp-hint">Leave blank to auto-generate an 8-digit barcode</span>
                                @error('barcode')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                            </div>
                            <div class="pp-field">
                                <label for="brand_id">Brand</label>
                                <select name="brand_id" id="brand_id" class="form-select" data-pp-sync="brand">
                                    <option value="">Select Brand</option>
                                    @foreach ($brands as $brand)
                                        @php
                                            $brandSelected = old('brand_id') !== null
                                                ? (string) old('brand_id') === (string) $brand->id
                                                : $loop->first;
                                        @endphp
                                        <option value="{{ $brand->id }}" {{ $brandSelected ? 'selected' : '' }}>
                                            {{ $brand->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="pp-field mt-3">
                            <label for="productTagsTextarea">Product Tags</label>
                            <input type="text" id="productTagsTextarea" class="form-control pp-tags-input"
                                   placeholder="Add a tag" autocomplete="off">
                            <input type="hidden" name="tags" id="productTagsHidden" value="{{ old('tags') }}">
                            <div class="pp-tags" id="tagsDisplay"></div>
                            <span class="pp-hint">Press Enter or comma to add tags</span>
                        </div>

                        <div class="pp-field mt-3">
                            <label for="short_desc">Description</label>
                            <textarea name="short_desc" id="short_desc" class="form-control" rows="3"
                                      placeholder="Short product description">{{ old('short_desc') }}</textarea>
                        </div>
                    </div>
                </section>

                <section class="pp-card">
                    <div class="pp-card__head">
                        <span class="pp-card__icon"><i class="bi bi-currency-rupee"></i></span>
                        <div>
                            <h2 class="pp-card__title">Pricing &amp; Cost</h2>
                            <p class="pp-card__sub">Live profit and margin update as you type</p>
                        </div>
                    </div>
                    <div class="pp-card__body">
                        <div class="pp-grid pp-grid--4">
                            <div class="pp-field">
                                <label for="purchase_price">Purchase Price (₹) <span class="pp-req">*</span></label>
                                <input type="number" step="0.01" min="0" name="purchase_price" id="purchase_price"
                                       class="form-control @error('purchase_price') is-invalid @enderror"
                                       value="{{ old('purchase_price') }}" required placeholder="0.00" data-pp-price>
                                <span class="pp-hint">Your cost price</span>
                                @error('purchase_price')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                            </div>
                            <div class="pp-field">
                                <label for="price">Selling Price (₹) <span class="pp-req">*</span></label>
                                <input type="number" step="0.01" min="0" name="price" id="price"
                                       class="form-control @error('price') is-invalid @enderror"
                                       value="{{ old('price') }}" required placeholder="0.00" data-pp-price>
                                <span class="pp-hint">Customer price</span>
                                @error('price')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                            </div>
                            <div class="pp-field">
                                <label for="mrp">MRP (₹)</label>
                                <input type="number" step="0.01" min="0" name="mrp" id="mrp"
                                       class="form-control" value="{{ old('mrp') }}" placeholder="Optional" data-pp-price>
                                <span class="pp-hint">Optional maximum price</span>
                            </div>
                            <div class="pp-field">
                                <label for="wholesale_price">Wholesale Price (₹)</label>
                                <input type="number" step="0.01" min="0" name="wholesale_price" id="wholesale_price"
                                       class="form-control" value="{{ old('wholesale_price') }}" placeholder="Optional">
                                <span class="pp-hint">Optional wholesale price</span>
                            </div>
                        </div>
                        <div class="pp-alert-loss" id="ppLossAlert" role="status">
                            <i class="bi bi-graph-down-arrow"></i>
                            <span id="ppLossText">Selling below cost</span>
                        </div>
                    </div>
                </section>

                <section class="pp-card">
                    <div class="pp-card__head">
                        <span class="pp-card__icon"><i class="bi bi-box-seam"></i></span>
                        <div>
                            <h2 class="pp-card__title">Inventory &amp; Classification</h2>
                            <p class="pp-card__sub">Stock, unit and tax details</p>
                        </div>
                    </div>
                    <div class="pp-card__body">
                        <div class="pp-grid pp-grid--4">
                            <div class="pp-field">
                                <label for="opening_stock">Opening Stock <span class="pp-req">*</span></label>
                                <input type="number" name="opening_stock" id="opening_stock" min="0"
                                       class="form-control @error('opening_stock') is-invalid @enderror"
                                       value="{{ old('opening_stock', 0) }}" required data-pp-price>
                                <span class="pp-hint">Posted to Central Warehouse first</span>
                                @error('opening_stock')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                            </div>
                            <div class="pp-field">
                                <label for="unit_id">Unit</label>
                                <select name="unit_id" id="unit_id" class="form-select" data-pp-sync="unit">
                                    <option value="">Select Unit</option>
                                    @foreach ($units as $unit)
                                        <option value="{{ $unit->id }}" {{ (string) old('unit_id') === (string) $unit->id ? 'selected' : '' }}>
                                            {{ ucfirst($unit->name) }}
                                        </option>
                                    @endforeach
                                </select>
                                <span class="pp-hint">Measurement unit</span>
                            </div>
                            <div class="pp-field">
                                <label for="hsn_code">HSN Code</label>
                                <input type="text" name="hsn_code" id="hsn_code" class="form-control"
                                       value="{{ old('hsn_code') }}" maxlength="50" placeholder="Tax classification">
                                <span class="pp-hint">For tax classification</span>
                            </div>
                            <div class="pp-field">
                                <label for="tax_id">Tax</label>
                                <select name="tax_id" id="tax_id" class="form-select" data-pp-price>
                                    <option value="" data-rate="0">No Tax</option>
                                    @foreach ($taxes as $tax)
                                        @php
                                            $taxSelected = old('tax_id') !== null
                                                ? (string) old('tax_id') === (string) $tax->id
                                                : $loop->first;
                                        @endphp
                                        <option value="{{ $tax->id }}" data-rate="{{ $tax->rate }}" {{ $taxSelected ? 'selected' : '' }}>
                                            {{ $tax->name }} — {{ number_format($tax->rate, 2) }}%
                                        </option>
                                    @endforeach
                                </select>
                                <span class="pp-hint">Applicable tax rate</span>
                            </div>
                            <div class="pp-field">
                                <label for="shipping_days">Shipping Days</label>
                                <input type="number" name="shipping_days" id="shipping_days" min="0"
                                       class="form-control" value="{{ $defaultShipping }}" placeholder="e.g. 5">
                                <span class="pp-hint">Estimated dispatch days</span>
                            </div>
                        </div>

                        <div class="pp-toggles">
                            <label class="pp-toggle" for="isActive">
                                <input type="hidden" name="is_active" value="0">
                                <input type="checkbox" class="form-check-input" role="switch" name="is_active" id="isActive"
                                       value="1" {{ old('is_active', true) ? 'checked' : '' }} data-pp-sync="active">
                                Active
                            </label>
                            <label class="pp-toggle" for="isFeatured">
                                <input type="hidden" name="is_featured" value="0">
                                <input type="checkbox" class="form-check-input" role="switch" name="is_featured" id="isFeatured"
                                       value="1" {{ old('is_featured') ? 'checked' : '' }}>
                                Featured
                            </label>
                        </div>
                    </div>
                </section>

                <section class="pp-card">
                    <div class="pp-card__head">
                        <span class="pp-card__icon"><i class="bi bi-images"></i></span>
                        <div>
                            <h2 class="pp-card__title">Media &amp; Visibility</h2>
                            <p class="pp-card__sub">Images, videos and where this product appears</p>
                        </div>
                    </div>
                    <div class="pp-card__body">
                        <div class="pp-grid pp-grid--2">
                            <div class="pp-field">
                                <label for="product-image-input">Product Image (Main)</label>
                                <input type="file" name="image" id="product-image-input" class="form-control"
                                       accept="image/jpeg,image/png,image/jpg,image/webp">
                                <span class="pp-hint">Max 5MB. JPG, PNG, WebP</span>
                            </div>
                            <div class="pp-field">
                                <label for="additional_images">Additional Images (Max 5)</label>
                                <input type="file" name="additional_images[]" id="additional_images" class="form-control"
                                       accept="image/jpeg,image/png,image/jpg,image/gif,image/webp" multiple>
                                <span class="pp-hint">Max 2MB each</span>
                                <div id="image-preview-container" class="mt-2"></div>
                            </div>
                            <div class="pp-field">
                                <label for="videos">Videos (Max 2)</label>
                                <input type="file" name="videos[]" id="videos" class="form-control"
                                       accept="video/mp4,video/webm,video/quicktime,video/x-msvideo" multiple>
                                <span class="pp-hint">Max 50MB each</span>
                                <div id="video-preview-container" class="mt-2"></div>
                            </div>
                            <div class="pp-field">
                                <label for="long_desc">Long Description</label>
                                <textarea name="long_desc" id="long_desc" class="form-control" rows="4"
                                          placeholder="Full product details">{{ old('long_desc') }}</textarea>
                            </div>
                        </div>

                        <div class="pp-field mt-3">
                            <label>Show Product In <span class="pp-req">*</span></label>
                            <div class="pp-channel">
                                <label>
                                    <input type="radio" name="channel_visibility" value="both"
                                           {{ old('channel_visibility', 'both') === 'both' ? 'checked' : '' }}>
                                    Both POS &amp; Website
                                </label>
                                <label>
                                    <input type="radio" name="channel_visibility" value="website_only"
                                           {{ old('channel_visibility') === 'website_only' ? 'checked' : '' }}>
                                    Website only
                                </label>
                                <label>
                                    <input type="radio" name="channel_visibility" value="pos_only"
                                           {{ old('channel_visibility') === 'pos_only' ? 'checked' : '' }}>
                                    POS only
                                </label>
                            </div>
                        </div>

                        <div class="pp-checks mt-3">
                            <div class="form-check">
                                <input type="hidden" name="is_verified" value="0">
                                <input type="checkbox" class="form-check-input" name="is_verified" id="isVerified"
                                       value="1" {{ old('is_verified') ? 'checked' : '' }}>
                                <label class="form-check-label" for="isVerified">Verified</label>
                            </div>
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" name="is_prebooking" id="isPrebooking"
                                       value="1" {{ old('is_prebooking') ? 'checked' : '' }}>
                                <label class="form-check-label" for="isPrebooking">Pre Booking</label>
                            </div>
                        </div>
                    </div>
                </section>
            </div>

            <aside class="pp-aside">
                <section class="pp-card">
                    <div class="pp-card__head">
                        <span class="pp-card__icon pp-card__icon--profit"><i class="bi bi-percent"></i></span>
                        <div>
                            <h2 class="pp-card__title">Live Profit</h2>
                        </div>
                    </div>
                    <div class="pp-card__body">
                        <div class="pp-profit__value">
                            <span class="pp-profit__amount is-pos" id="ppProfitAmount">₹0</span>
                            <span class="pp-profit__label">Profit per unit</span>
                        </div>
                        <div class="pp-profit__rows">
                            <div class="pp-profit__row"><span>Margin</span><span id="ppMargin">—</span></div>
                            <div class="pp-profit__row"><span>Markup on cost</span><span id="ppMarkup">—</span></div>
                            <div class="pp-profit__row"><span>Price incl. tax</span><span id="ppPriceInclTax">—</span></div>
                            <div class="pp-profit__row"><span>Discount off MRP</span><span id="ppMrpDisc">—</span></div>
                            <div class="pp-profit__row"><span>Stock value at cost</span><span id="ppStockValue">—</span></div>
                        </div>
                    </div>
                </section>

                <section class="pp-card">
                    <div class="pp-card__head">
                        <span class="pp-card__icon pp-card__icon--summary"><i class="bi bi-tags"></i></span>
                        <div>
                            <h2 class="pp-card__title">Summary</h2>
                        </div>
                    </div>
                    <div class="pp-card__body">
                        <span class="pp-summary__status" id="ppSummaryStatus">Active</span>
                        <div class="pp-summary__rows">
                            <div class="pp-summary__row"><span>Category</span><span id="ppSummaryCategory">—</span></div>
                            <div class="pp-summary__row"><span>Brand</span><span id="ppSummaryBrand">—</span></div>
                            <div class="pp-summary__row"><span>Unit</span><span id="ppSummaryUnit">—</span></div>
                        </div>
                        <button type="submit" class="pp-btn pp-btn--primary pp-btn--block">
                            <i class="bi bi-save"></i> Save Product
                        </button>
                    </div>
                </section>
            </aside>
        </div>
    </form>
</div>
@endsection

@push('scripts')
<script>
(function () {
    const money = (n) => '₹' + (Math.round((n + Number.EPSILON) * 100) / 100).toLocaleString('en-IN', {
        minimumFractionDigits: n % 1 === 0 ? 0 : 2,
        maximumFractionDigits: 2,
    });
    const pct = (n) => (Number.isFinite(n) ? n.toFixed(1) + '%' : '—');

    function selectedText(selectEl) {
        if (!selectEl || !selectEl.selectedOptions.length) return '—';
        const t = selectEl.selectedOptions[0].textContent.trim();
        return selectEl.value ? t : '—';
    }

    function taxRate() {
        const sel = document.getElementById('tax_id');
        if (!sel || !sel.selectedOptions.length) return 0;
        return parseFloat(sel.selectedOptions[0].getAttribute('data-rate') || '0') || 0;
    }

    function refreshProfit() {
        const cost = parseFloat(document.getElementById('purchase_price')?.value) || 0;
        const sell = parseFloat(document.getElementById('price')?.value) || 0;
        const mrp = parseFloat(document.getElementById('mrp')?.value) || 0;
        const stock = parseFloat(document.getElementById('opening_stock')?.value) || 0;
        const rate = taxRate();

        const profit = sell - cost;
        const margin = sell > 0 ? (profit / sell) * 100 : NaN;
        const markup = cost > 0 ? (profit / cost) * 100 : NaN;
        const inclTax = sell * (1 + rate / 100);
        const mrpDisc = mrp > 0 ? ((mrp - sell) / mrp) * 100 : NaN;
        const stockValue = cost * stock;

        const amountEl = document.getElementById('ppProfitAmount');
        const sellInput = document.getElementById('price');
        const lossAlert = document.getElementById('ppLossAlert');
        const lossText = document.getElementById('ppLossText');

        if (amountEl) {
            amountEl.textContent = (profit < 0 ? '-' : '') + money(Math.abs(profit));
            amountEl.classList.toggle('is-pos', profit >= 0);
            amountEl.classList.toggle('is-neg', profit < 0);
        }

        document.getElementById('ppMargin').textContent = sell > 0 ? pct(margin) : '—';
        document.getElementById('ppMarkup').textContent = cost > 0 ? pct(markup) : '—';
        document.getElementById('ppPriceInclTax').textContent = sell > 0 ? money(inclTax) : '—';
        document.getElementById('ppMrpDisc').textContent = mrp > 0 ? pct(mrpDisc) : '—';
        document.getElementById('ppStockValue').textContent = (cost > 0 || stock > 0) ? money(stockValue) : '—';

        const belowCost = sell > 0 && cost > 0 && sell < cost;
        if (sellInput) sellInput.classList.toggle('is-loss', belowCost);
        if (lossAlert) {
            lossAlert.classList.toggle('is-visible', belowCost);
            if (belowCost && lossText) {
                lossText.textContent = 'Selling below cost — every unit loses ' + money(cost - sell) + '.';
            }
        }
    }

    function refreshSummary() {
        document.getElementById('ppSummaryCategory').textContent = selectedText(document.getElementById('category_id'));
        document.getElementById('ppSummaryBrand').textContent = selectedText(document.getElementById('brand_id'));
        document.getElementById('ppSummaryUnit').textContent = selectedText(document.getElementById('unit_id'));
        const active = document.getElementById('isActive')?.checked;
        const status = document.getElementById('ppSummaryStatus');
        if (status) {
            status.textContent = active ? 'Active' : 'Inactive';
            status.classList.toggle('is-inactive', !active);
        }
    }

    document.querySelectorAll('[data-pp-price]').forEach((el) => {
        el.addEventListener('input', refreshProfit);
        el.addEventListener('change', refreshProfit);
    });
    document.querySelectorAll('[data-pp-sync]').forEach((el) => {
        el.addEventListener('change', refreshSummary);
        el.addEventListener('input', refreshSummary);
    });

    const tagInput = document.getElementById('productTagsTextarea');
    const tagsDisplay = document.getElementById('tagsDisplay');
    const tagsHidden = document.getElementById('productTagsHidden');
    let tags = [];

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function syncTagsHidden() {
        tagsHidden.value = tags.join(', ');
    }

    function renderTags() {
        tagsDisplay.innerHTML = '';
        tags.forEach((tag, index) => {
            const el = document.createElement('span');
            el.className = 'pp-tag';
            el.innerHTML = '<span>' + escapeHtml(tag) + '</span><button type="button" data-index="' + index + '" aria-label="Remove tag"><i class="bi bi-x"></i></button>';
            tagsDisplay.appendChild(el);
        });
        tagsDisplay.querySelectorAll('button').forEach((btn) => {
            btn.addEventListener('click', function () {
                tags.splice(parseInt(this.getAttribute('data-index'), 10), 1);
                renderTags();
            });
        });
        syncTagsHidden();
    }

    function addTag(raw) {
        const tag = (raw || '').trim();
        if (!tag || tags.includes(tag)) return false;
        tags.push(tag);
        renderTags();
        return true;
    }

    if (tagInput && tagsHidden) {
        const initial = (tagsHidden.value || '').split(',').map((t) => t.trim()).filter(Boolean);
        tags = [...new Set(initial)];
        renderTags();

        tagInput.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' || e.key === ',') {
                e.preventDefault();
                if (addTag(tagInput.value.replace(/,/g, ''))) tagInput.value = '';
            }
        });
        tagInput.addEventListener('blur', function () {
            if (addTag(tagInput.value.replace(/,/g, ''))) tagInput.value = '';
        });
        document.getElementById('productForm')?.addEventListener('submit', syncTagsHidden);
    }

    window.generateNewBarcode = function () {
        document.getElementById('barcode').value = String(Math.floor(Math.random() * 90000000 + 10000000));
    };

    const img = document.getElementById('product-image-input');
    if (img) {
        const maxBytes = 5 * 1024 * 1024;
        const allowed = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
        img.addEventListener('change', function () {
            const file = this.files[0];
            if (!file) return;
            if (file.size > maxBytes) {
                alert('Image must be 5MB or less.');
                this.value = '';
            } else if (!allowed.includes(file.type)) {
                alert('Allowed types: JPG, PNG, WebP.');
                this.value = '';
            }
        });
    }

    refreshProfit();
    refreshSummary();
})();
</script>
<script src="{{ asset('js/admin-product-media.js') }}"></script>
@endpush
