<?php
    use Illuminate\Support\Str;
    use Illuminate\Support\Facades\Storage;
?>

<?php $__env->startSection('backend_content'); ?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h4 class="fw-bold mb-1">Edit Reel</h4>
            <small class="text-muted">Update reel details</small>
        </div>
        <a href="<?php echo e(route('admin.reels.index')); ?>" class="btn btn-light">
            <i class="bx bx-arrow-back me-1"></i> Back
        </a>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-body">
            <form action="<?php echo e(route('admin.reels.update', $reel)); ?>" method="POST" enctype="multipart/form-data"
                class="row g-3">
                <?php echo csrf_field(); ?>
                <?php echo method_field('PUT'); ?>

                
                <div class="col-md-6">
                    <label class="form-label fw-600">Shop Name <span class="text-danger">*</span></label>
                    <input type="text" id="shopSearch" class="form-control" placeholder="Type shop name to search..."
                        autocomplete="off" value="<?php echo e(old('shop_name', $reel->shop?->name)); ?>">
                    <input type="hidden" name="shop_id" id="shopId" value="<?php echo e(old('shop_id', $reel->shop_id)); ?>"
                        required>
                    <small class="text-muted">Type and select from suggestion list.</small>
                    <div id="shopResults" class="list-group mt-2 d-none"></div>
                    <?php $__errorArgs = ['shop_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <div class="text-danger small mt-1"><?php echo e($message); ?></div>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                
                <div class="col-md-6">
                    <label class="form-label fw-600">Title</label>
                    <input type="text" name="title" class="form-control <?php $__errorArgs = ['title'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                        value="<?php echo e(old('title', $reel->title)); ?>" required placeholder="Enter reel title">
                    <?php $__errorArgs = ['title'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                
                <div class="col-12">
                    <label class="form-label fw-600">Caption</label>
                    <input type="text" name="caption" class="form-control <?php $__errorArgs = ['caption'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                        value="<?php echo e(old('caption', $reel->caption)); ?>" placeholder="Optional brief description">
                    <?php $__errorArgs = ['caption'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                
                <div class="col-md-6">
                    <label class="form-label fw-600">Video URL <span class="text-danger">*</span></label>
                    <input type="url" name="video_url" class="form-control <?php $__errorArgs = ['video_url'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                        value="<?php echo e(old('video_url', $reel->video_url)); ?>" required
                        placeholder="https://youtube.com/shorts/...">
                    <small class="text-muted">If no thumbnail image is uploaded, one is auto-generated from this
                        URL.</small>
                    <?php $__errorArgs = ['video_url'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                
                <div class="col-md-6">
                    <label class="form-label fw-600">Thumbnail Image</label>
                    <input type="file" name="thumbnail_image" id="thumbnailImage"
                        class="form-control <?php $__errorArgs = ['thumbnail_image'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                        accept="image/jpeg,image/png,image/jpg,image/gif,image/webp">
                    <small class="text-muted">Accepted: JPEG, PNG, JPG, GIF, WebP. Leave blank to keep current
                        thumbnail.</small>
                    <div class="mt-2">
                        <?php if($reel->thumbnail_url): ?>
                            <div id="currentThumbnailWrapper">
                                <small class="text-muted d-block mb-1">Current thumbnail:</small>
                                <img id="currentThumbnail"
                                    src="<?php echo e(Str::startsWith($reel->thumbnail_url, 'http') ? $reel->thumbnail_url : Storage::url($reel->thumbnail_url)); ?>"
                                    alt="Current thumbnail"
                                    style="max-width: 180px; max-height: 140px; object-fit: cover; border-radius: 8px; border: 1px solid #e5e7eb;">
                            </div>
                        <?php endif; ?>
                        <img id="thumbnailPreview" src="" alt="New thumbnail preview"
                            style="max-width: 180px; max-height: 140px; object-fit: cover; border-radius: 8px; border: 1px solid #e5e7eb; display:none;">
                    </div>
                    <?php $__errorArgs = ['thumbnail_image'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                </div>

                
                <div class="col-md-6 d-flex align-items-end">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" value="1" id="is_active" name="is_active"
                            <?php if(old('is_active', $reel->is_active)): echo 'checked'; endif; ?>>
                        <label class="form-check-label" for="is_active">
                            <strong>Active</strong> (visible on homepage)
                        </label>
                    </div>
                </div>

                
                <div class="col-12">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="bx bx-save me-1"></i> Update Reel
                    </button>
                    <a href="<?php echo e(route('admin.reels.index')); ?>" class="btn btn-outline-secondary btn-lg ms-1">Cancel</a>
                </div>
            </form>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('shopSearch');
            const shopIdInput = document.getElementById('shopId');
            const shopResults = document.getElementById('shopResults');
            const thumbnailImage = document.getElementById('thumbnailImage');
            const thumbnailPreview = document.getElementById('thumbnailPreview');
            const currentThumbnailWrapper = document.getElementById('currentThumbnailWrapper');
            const searchEndpoint = <?php echo json_encode(route('admin.reels.shops.search'), 15, 512) ?>;
            let debounceTimer = null;

            const hideResults = () => {
                shopResults.classList.add('d-none');
                shopResults.innerHTML = '';
            };

            const renderResults = (shops) => {
                if (!shops.length) {
                    hideResults();
                    return;
                }
                shopResults.innerHTML = shops.map((shop) =>
                    `<button type="button" class="list-group-item list-group-item-action" data-id="${shop.id}" data-name="${shop.name}">${shop.name}</button>`
                ).join('');
                shopResults.classList.remove('d-none');
            };

            const searchShops = (query) => {
                fetch(`${searchEndpoint}?q=${encodeURIComponent(query)}`, {
                        headers: {
                            'Accept': 'application/json'
                        }
                    })
                    .then((res) => res.ok ? res.json() : [])
                    .then((shops) => renderResults(Array.isArray(shops) ? shops : []))
                    .catch(() => hideResults());
            };

            searchInput.addEventListener('input', () => {
                shopIdInput.value = '';
                const query = searchInput.value.trim();
                clearTimeout(debounceTimer);
                if (query.length < 1) {
                    hideResults();
                    return;
                }
                debounceTimer = setTimeout(() => searchShops(query), 250);
            });

            shopResults.addEventListener('click', (event) => {
                const option = event.target.closest('[data-id][data-name]');
                if (!option) return;
                searchInput.value = option.dataset.name;
                shopIdInput.value = option.dataset.id;
                hideResults();
            });

            document.addEventListener('click', (event) => {
                if (!shopResults.contains(event.target) && event.target !== searchInput) {
                    hideResults();
                }
            });

            // Thumbnail preview — hide current when new file selected
            thumbnailImage?.addEventListener('change', (event) => {
                const file = event.target.files?.[0];
                if (!file) {
                    thumbnailPreview.style.display = 'none';
                    thumbnailPreview.src = '';
                    if (currentThumbnailWrapper) currentThumbnailWrapper.style.display = 'block';
                    return;
                }
                thumbnailPreview.src = URL.createObjectURL(file);
                thumbnailPreview.style.display = 'block';
                if (currentThumbnailWrapper) currentThumbnailWrapper.style.display = 'none';
            });

            // Validate shop chosen before submit
            searchInput.form?.addEventListener('submit', (event) => {
                if (!shopIdInput.value) {
                    event.preventDefault();
                    searchInput.focus();
                    window.appToast?.('Please choose a shop from the suggestions.', 'error');
                }
            });
        });
    </script>

    <style>
        .fw-600 {
            font-weight: 600;
        }
    </style>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('backend.layout', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\Abdur Rahman\Desktop\faa\resources\views\backend\reels\edit.blade.php ENDPATH**/ ?>