@extends('layouts.admin')

@section('title', 'Order Details')
@section('page-title', 'Order Details')

@section('header-actions')
<a href="{{ route('admin.orders') }}" class="back-btn">
    <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
    </svg>
    Back to Orders
</a>
@endsection

@section('styles')
<style>
    /* Order Details Card */
    .order-details-card {
        background: white;
        border-radius: 1rem;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        border: 1px solid #e5e7eb;
        overflow: hidden;
    }
    
    .order-header {
        background: linear-gradient(135deg, #371C16 0%, #B5702F 100%);
        color: white;
        padding: 2rem;
        text-align: center;
    }
    
    .order-title {
        font-family: 'Lato', sans-serif;
        font-size: 1.875rem;
        font-weight: 700;
        margin: 0 0 0.5rem 0;
    }
    
    .order-subtitle {
        font-size: 1.125rem;
        opacity: 0.9;
        margin: 0;
    }
    
    .order-content {
        padding: 2rem;
    }
    
    .details-grid {
        display: grid;
        grid-template-columns: 1fr 460px; /* wider preview column for clearer visibility */
        gap: 2rem;
        margin-bottom: 2rem;
    }
    
    .order-info {
        background: #f9fafb;
        border-radius: 0.75rem;
        padding: 1.5rem;
    }
    
    .info-section {
        margin-bottom: 1.5rem;
    }
    
    .info-section:last-child {
        margin-bottom: 0;
    }
    
    .info-label {
        font-size: 1rem;
        font-weight: 600;
        color: #6b7280;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 0.5rem;
    }
    
    .info-value {
        font-size: 1.125rem;
        color: #1f2937;
        margin-bottom: 0.25rem;
    }
    
    .info-value:last-child {
        margin-bottom: 0;
    }
    
    .status-badge {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }
    
    .status-badge.pending {
        background: #fef3c7;
        color: #d97706;
    }
    
    .status-badge.completed {
        background: #d1fae5;
        color: #059669;
    }
    
    /* Preview Section */
    .preview-section {
        background: #f9fafb;
        border-radius: 0.75rem;
        padding: 1.5rem;
        text-align: center;
    }
    
    .preview-title {
        font-family: 'Lato', sans-serif;
        font-size: 1.25rem;
        font-weight: 600;
        color: #1f2937;
        margin: 0 0 1rem 0;
    }
    
    .preview-container {
        background: white;
        border: 2px solid #e5e7eb;
        border-radius: 0.75rem;
        padding: 1rem;
        min-height: 520px; /* taller for bookmark visibility */
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s ease;
        position: relative;
    }
    
    #konvaContainer {
        width: 100% !important;
        height: 100% !important;
        min-height: 520px; /* match preview container */
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    #konvaContainer canvas {
        max-width: 100% !important;
        max-height: 100% !important;
        width: auto !important;
        height: auto !important;
        object-fit: contain;
    }
    
    .preview-container:hover {
        border-color: #B5702F;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    /* Lightbox Styles */
    .lightbox {
        display: none;
        position: fixed;
        z-index: 9999;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.9);
        cursor: pointer;
    }
    
    .lightbox-content {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        max-width: 90%;
        max-height: 90%;
        background: white;
        border-radius: 0.5rem;
        padding: 1rem;
    }
    
    .lightbox img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
    }
    
    .lightbox-close {
        position: absolute;
        top: 10px;
        right: 15px;
        color: #fff;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .lightbox-close:hover {
        background: rgba(0, 0, 0, 0.8);
    }
    
    .preview-placeholder {
        color: #9ca3af;
        font-size: 0.875rem;
    }
    
    /* Actions Section */
    .actions-section {
        background: #f9fafb;
        border-radius: 0.75rem;
        padding: 1.5rem;
        text-align: center;
    }
    
    .actions-title {
        font-family: 'Lato', sans-serif;
        font-size: 1.25rem;
        font-weight: 600;
        color: #1f2937;
        margin: 0 0 1rem 0;
    }
    
    .action-buttons {
        display: flex;
        gap: 1rem;
        justify-content: center;
    }
    
    .btn {
        padding: 0.75rem 1.5rem;
        border-radius: 0.5rem;
        font-size: 0.875rem;
        font-weight: 500;
        border: none;
        cursor: pointer;
        transition: all 0.3s ease;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
    }
    
    .btn-success {
        background: #059669;
        color: white;
    }
    
    .btn-success:hover {
        background: #047857;
    }
    
    .btn-secondary {
        background: #6b7280;
        color: white;
    }
    
    .btn-secondary:hover {
        background: #4b5563;
    }
    
    /* Mobile Responsive */
    @media (max-width: 768px) {
        .details-grid {
            grid-template-columns: 1fr;
        }
        
        .action-buttons {
            flex-direction: column;
        }
    }
</style>
@endsection

@section('content')
<div class="order-details-card">
    <div class="order-header">
        <h1 class="order-title">{{ $order->student_name }}</h1>
        <p class="order-subtitle">{{ ucfirst($order->product->name) }} • Order #{{ $order->id }}</p>
            </div>

    <div class="order-content">
        <div class="details-grid">
            <div class="order-info">
                <div class="info-section">
                    <div class="info-label">Customer Information</div>
                    <div class="info-value"><strong>Name:</strong> {{ $order->student_name }}</div>
                    <div class="info-value"><strong>Order Date:</strong> {{ $order->created_at->format('F j, Y \a\t g:i A') }}</div>
                    <div class="info-value"><strong>Status:</strong> <span class="status-badge {{ $order->status }}">{{ ucfirst($order->status) }}</span></div>
            </div>

                <div class="info-section">
                    <div class="info-label">Product Details</div>
                    <div class="info-value"><strong>Product:</strong> {{ ucfirst($order->product->name) }}</div>
                    <div class="info-value"><strong>Size:</strong> {{ ucfirst($order->size) }}</div>
                </div>

                <div class="info-section">
                    <div class="info-label">Customization</div>
                    @php
                        $textString = '';
                        if (is_array($order->text_characters)) {
                            $textString = implode('', array_filter($order->text_characters));
                        } elseif (is_string($order->text_characters)) {
                            $textString = $order->text_characters;
                        }
                    @endphp
                    <div class="info-value"><strong>Text:</strong> {{ $textString !== '' ? $textString : '—' }}</div>
                    @if($order->selected_stamps && count($order->selected_stamps) > 0)
                        <div class="info-value" style="margin-top: 0.25rem;"><strong>Stamps:</strong> {{ count($order->selected_stamps) }} selected</div>
                        <div class="info-value" style="display: flex; flex-wrap: wrap; gap: 6px; align-items: center;">
                            @foreach($order->selected_stamps as $stamp)
                                @php
                                    $productName = strtolower($order->product->name);
                                    $stampFile = '';
                                    $stampDir = null;
                                    if (is_string($stamp)) {
                                        $stampFile = $stamp;
                                    } elseif (is_array($stamp)) {
                                        $stampFile = $stamp['filename'] ?? ($stamp['value'] ?? '');
                                        $stampDir = $stamp['directory'] ?? null;
                                    } elseif (is_object($stamp)) {
                                        $stampFile = $stamp->filename ?? ($stamp->value ?? '');
                                        $stampDir = $stamp->directory ?? null;
                                    }
                                    if (!$stampDir) {
                                        if ($productName === 'bracelet') {
                                            $stampDir = 'small';
                                        } elseif ($productName === 'bookmark') {
                                            $stampDir = 'large';
                                        } elseif ($productName === 'keychain') {
                                            $stampDir = (is_array($order->text_characters) && count($order->text_characters) === 3) ? 'large' : 'small';
                                        } else {
                                            $stampDir = 'small';
                                        }
                                    }
                                @endphp
                                @if($stampFile)
                                    <img src="/images/stamps/{{ $stampDir }}/{{ $stampFile }}" alt="stamp"
                                         style="width: 44px; height: 44px; object-fit: contain; border: 1px solid #e5e7eb; border-radius: 6px; background:#fff; padding:4px;" />
                                @endif
                            @endforeach
                        </div>
                    @else
                        <div class="info-value"><strong>Stamps:</strong> None selected</div>
                    @endif
            </div>
        </div>

            <div class="preview-section">
                <h3 class="preview-title">Product Preview</h3>
                <div class="preview-container" id="previewContainer">
                    @if($order->preview_json)
                        <div id="konvaContainer"></div>
                    @elseif($order->preview_image_url)
                        <img src="{{ asset('storage/' . $order->preview_image_url) }}" 
                             alt="Order Preview" 
                             id="previewImage"
                             style="max-width: 100%; max-height: 100%; object-fit: contain;"
                             onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
                        <div class="preview-placeholder" style="display: none;">
                            <svg width="48" height="48" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="margin: 0 auto 1rem;">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                            </svg>
                            <p>Preview image not available</p>
                    </div>
                @else
                        <div class="preview-placeholder">
                            <svg width="48" height="48" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="margin: 0 auto 1rem;">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                        </svg>
                            <p>No preview available</p>
                    </div>
                @endif
            </div>
                </div>
            </div>

        @if($order->status === 'pending')
            <div class="actions-section">
                <h3 class="actions-title">Order Actions</h3>
                <div class="action-buttons">
                    <button class="btn btn-success" onclick="markCompleted({{ $order->id }})">
                        <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                        Mark as Completed
                    </button>
                            </div>
                        </div>
                    @endif
    </div>
</div>

<!-- Lightbox -->
<div id="lightbox" class="lightbox" onclick="closeLightbox()">
    <div class="lightbox-content" onclick="event.stopPropagation()">
        <span class="lightbox-close" onclick="closeLightbox()">&times;</span>
        <img id="lightboxImage" src="" alt="Order Preview">
    </div>
</div>
@endsection

@section('scripts')
<script>
    // Initialize Konva preview
    @if($order->preview_json)
    document.addEventListener('DOMContentLoaded', function() {
        try {
            console.log('Initializing Konva preview...');
            
            // Get raw preview JSON from database
            let previewJson = {!! json_encode($order->preview_json) !!};
            console.log('Initial preview JSON:', typeof previewJson, previewJson);
            
            // Handle multiple levels of encoding
            let parseAttempts = 0;
            while (typeof previewJson === 'string' && parseAttempts < 3) {
                parseAttempts++;
                console.log(`Parse attempt ${parseAttempts}...`);
                try {
                    previewJson = JSON.parse(previewJson);
                    console.log(`After parse ${parseAttempts}:`, typeof previewJson);
                } catch (e) {
                    console.error(`Parse attempt ${parseAttempts} failed:`, e);
                    break;
                }
            }
            
            console.log('Final parse attempts:', parseAttempts);
            console.log('Final type:', typeof previewJson);
            
            console.log('Final preview JSON:', previewJson);
            console.log('Has attrs?', previewJson && previewJson.attrs);
            console.log('Type check:', typeof previewJson, previewJson instanceof Object);
            
            // Validate JSON structure - check for required Konva Stage properties
            const isValidKonvaJson = previewJson && 
                                    typeof previewJson === 'object' && 
                                    (previewJson.attrs || previewJson.className === 'Stage');
            
            console.log('Is valid Konva JSON?', isValidKonvaJson);
            
            if (isValidKonvaJson) {
                const container = document.getElementById('konvaContainer');
                if (!container) {
                    console.error('Konva container not found!');
                    return;
                }
                
                console.log('Container found:', container);
                console.log('Container dimensions:', container.offsetWidth, 'x', container.offsetHeight);
                
                // Calculate proper dimensions maintaining aspect ratio
                const originalWidth = previewJson.attrs.width;
                const originalHeight = previewJson.attrs.height;
                const aspectRatio = originalWidth / originalHeight;
                
                // Compute container-based maximums for responsive scaling
                const cs = getComputedStyle(container);
                const padX = parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);
                const padY = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom);
                const containerW = container.clientWidth - padX;
                const containerH = container.clientHeight - padY;
                
                // Scale multiplier to make product render larger within container (1.75x scale)
                const PRODUCT_SCALE_MULTIPLIER = 1.75;
                
                // Use full container dimensions with small margins, then apply scale multiplier
                const maxWidth = Math.max(400, containerW * 0.9) * PRODUCT_SCALE_MULTIPLIER;
                const maxHeight = Math.max(500, containerH * 0.9) * PRODUCT_SCALE_MULTIPLIER;

                let stageWidth, stageHeight;
                
                // Calculate dimensions that fit within container while maintaining aspect ratio
                if (aspectRatio > maxWidth / maxHeight) {
                    stageWidth = maxWidth;
                    stageHeight = maxWidth / aspectRatio;
                } else {
                    stageHeight = maxHeight;
                    stageWidth = maxHeight * aspectRatio;
                }
                
                console.log('Original dimensions:', originalWidth, 'x', originalHeight);
                console.log('Aspect ratio:', aspectRatio.toFixed(2));
                console.log('Calculated stage dimensions:', stageWidth, 'x', stageHeight);
                
                console.log('Creating Konva stage from JSON...');
                const stage = Konva.Node.create(previewJson, container);
                console.log('Stage created:', stage);
                
                // Helper to apply stage size and uniform scale
                function applyStageSize(width, height) {
                    stage.width(width);
                    stage.height(height);
                    const scale = width / originalWidth;
                    stage.scale({ x: scale, y: scale });
                }
                applyStageSize(stageWidth, stageHeight);
                
                const initialScale = stageWidth / originalWidth;
                console.log('Scale factor:', initialScale.toFixed(3));
                console.log('Final stage dimensions:', stage.width(), 'x', stage.height());
                
                // Reload all images in the stage
                const images = stage.find('Image');
                console.log('Found images:', images.length);
                
                let imagesLoaded = 0;
                const totalImages = images.length;
                
                if (totalImages === 0) {
                    // No images, just draw
                    stage.draw();
                    console.log('Preview rendered successfully (no images)!');
                } else {
                    // Separate images by type for proper indexing
                const backgroundImages = [];
                const stampImages = [];
                const textImages = [];
                const otherImages = [];
                
                images.forEach(imageNode => {
                    const imageName = imageNode.name();
                    if (imageName === 'background') {
                        backgroundImages.push(imageNode);
                    } else if (imageName === 'stamp' || imageName === 'sequentialStamp' || imageName === 'keychainStamp' || imageName === 'bookmarkStamp') {
                        stampImages.push(imageNode);
                    } else if (imageName === 'userText' || imageName === 'sequentialText' || imageName === 'keychainText') {
                        textImages.push(imageNode);
                    } else {
                        otherImages.push(imageNode);
                    }
                });
                
                console.log('Image categorization:');
                console.log('- Backgrounds:', backgroundImages.length);
                console.log('- Stamps:', stampImages.length);
                console.log('- Text:', textImages.length);
                console.log('- Other:', otherImages.length);
                
                const allImages = [...backgroundImages, ...stampImages, ...textImages, ...otherImages];
                const stamps = @json($order->selected_stamps ?? []);
                console.log('Available stamp files from database:', stamps);
                
                allImages.forEach((imageNode, globalIndex) => {
                    const imageName = imageNode.name();
                    console.log(`Loading image ${globalIndex + 1}/${totalImages}, name: ${imageName}`);
                    
                    let imageUrl = '';
                    
                    // Determine image URL based on node name
                    if (imageName === 'background') {
                        // Product background image
                        const productName = '{{ $order->product->name }}';
                        imageUrl = `/images/products/${productName}.png`;
                        console.log('Background image URL:', imageUrl);
                    } else if (imageName === 'stamp' || imageName === 'sequentialStamp' || imageName === 'keychainStamp' || imageName === 'bookmarkStamp') {
                        // Stamp image - match by index in stamp images array
                        const stampIndex = stampImages.indexOf(imageNode);
                        console.log(`This is stamp #${stampIndex} out of ${stampImages.length} stamps`);
                        
                        if (stamps && stamps.length > 0) {
                            // Handle different stamp data formats
                            let stampFile = '';
                            let stampDirectory = 'small';
                            
                            if (typeof stamps[stampIndex] === 'string') {
                                // Simple string format: just filename
                                stampFile = stamps[stampIndex];
                            } else if (stamps[stampIndex] && stamps[stampIndex].filename) {
                                // Object format with filename and directory
                                stampFile = stamps[stampIndex].filename;
                                stampDirectory = stamps[stampIndex].directory || 'small';
                            } else if (stamps[stampIndex] && stamps[stampIndex].value) {
                                // Bracelet format with value field
                                stampFile = stamps[stampIndex].value;
                            }
                            
                            if (stampFile) {
                                // Determine directory based on product and size
                                const productName = '{{ $order->product->name }}';
                                const orderSize = '{{ $order->size }}';
                                
                                if (productName === 'bracelet') {
                                    stampDirectory = 'small'; // Bracelets always use small stamps
                                } else if (productName === 'keychain') {
                                    // Keychain v1 uses large, v2 uses small
                                    const textChars = @json($order->text_characters ?? []);
                                    stampDirectory = textChars.length === 3 ? 'large' : 'small';
                                } else if (productName === 'bookmark') {
                                    stampDirectory = 'large'; // Bookmarks use large stamp assets
                                }
                                
                                imageUrl = `/images/stamps/${stampDirectory}/${stampFile}`;
                                console.log(`Stamp ${stampIndex} URL:`, imageUrl, `(directory: ${stampDirectory})`);
                            } else {
                                console.warn(`Stamp ${stampIndex} has no valid filename:`, stamps[stampIndex]);
                            }
                        } else {
                            console.warn('No stamps array available in database');
                        }
                    }
                    
                    if (imageUrl) {
                        const img = new Image();
                        img.crossOrigin = 'anonymous';
                        img.onload = function() {
                            console.log(`✓ Image ${globalIndex + 1} loaded successfully:`, imageUrl);
                            imageNode.image(img);
                            imagesLoaded++;
                            
                            if (imagesLoaded === totalImages) {
                                stage.draw();
                                console.log('✓ All images loaded, preview rendered successfully!');
                            }
                        };
                        img.onerror = function() {
                            console.error(`✗ Failed to load image ${globalIndex + 1}:`, imageUrl);
                            imagesLoaded++;
                            
                            if (imagesLoaded === totalImages) {
                                stage.draw();
                                console.warn('Preview rendered (some images failed to load)');
                            }
                        };
                        img.src = imageUrl;
                    } else {
                        console.warn(`No image URL determined for node ${globalIndex + 1} (name: ${imageName})`);
                        imagesLoaded++;
                        
                        if (imagesLoaded === totalImages) {
                            stage.draw();
                            console.log('Preview rendered (some images skipped)');
                        }
                    }
                });

                // Keep preview filling the container on resize
                const resizeObserver = new ResizeObserver(() => {
                    const rcs = getComputedStyle(container);
                    const rpadX = parseFloat(rcs.paddingLeft) + parseFloat(rcs.paddingRight);
                    const rpadY = parseFloat(rcs.paddingTop) + parseFloat(rcs.paddingBottom);
                    const rw = container.clientWidth - rpadX;
                    const rh = container.clientHeight - rpadY;
                    const rMaxW = Math.max(400, rw * 0.9) * PRODUCT_SCALE_MULTIPLIER;
                    const rMaxH = Math.max(500, rh * 0.9) * PRODUCT_SCALE_MULTIPLIER;
                    let w, h;
                    if (aspectRatio > rMaxW / rMaxH) {
                        w = rMaxW; h = rMaxW / aspectRatio;
                    } else {
                        h = rMaxH; w = rMaxH * aspectRatio;
                    }
                    applyStageSize(w, h);
                    stage.batchDraw();
                });
                resizeObserver.observe(container);
                }
            } else {
                console.error('Invalid preview JSON structure:', previewJson);
            }
        } catch (error) {
            console.error('Error rendering Konva preview:', error);
            console.error('Error stack:', error.stack);
            
            // Show error message in preview container
            const container = document.getElementById('konvaContainer');
            if (container) {
                container.innerHTML = `
                    <div style="padding: 2rem; text-align: center; color: #dc2626;">
                        <svg width="48" height="48" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="margin: 0 auto 1rem;">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
                        </svg>
                        <p style="font-size: 14px; margin: 0;">Failed to load preview</p>
                        <p style="font-size: 12px; margin: 0.5rem 0 0 0; color: #6b7280;">${error.message}</p>
                    </div>
                `;
            }
        }
    });
    @endif

    // Lightbox functions
    function openLightbox() {
        const previewImage = document.getElementById('previewImage');
        if (previewImage && previewImage.src) {
            const lightbox = document.getElementById('lightbox');
            const lightboxImage = document.getElementById('lightboxImage');
            lightboxImage.src = previewImage.src;
            lightbox.style.display = 'block';
        }
    }

    function closeLightbox() {
        const lightbox = document.getElementById('lightbox');
        lightbox.style.display = 'none';
    }

    // Close lightbox with Escape key
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeLightbox();
        }
    });

    // Mark order as completed
    function markCompleted(orderId) {
        if (confirm('Mark this order as completed?')) {
    fetch(`/admin/orders/${orderId}/complete`, {
        method: 'POST',
        headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
                    alert('Error updating order status');
        }
    })
    .catch(error => {
        console.error('Error:', error);
                alert('Error updating order status');
    });
        }
}
</script>
@endsection