@extends('layouts.app')

@section('content')
    @php
        $normalizeUnitLabel = function ($unit) {
            $unit = strtolower(trim((string) $unit));

            return match ($unit) {
                'm2', 'm²' => 'm²',
                'meter', 'm' => 'meter',
                'pcs', 'pc', 'piece', 'lembar' => 'lembar',
                default => $unit !== '' ? $unit : 'lembar',
            };
        };

        $normalizeUnitKey = function ($unit) {
            $unit = strtolower(trim((string) $unit));

            return match ($unit) {
                'm2', 'm²' => 'm2',
                'meter', 'm' => 'meter',
                'pcs', 'pc', 'piece', 'lembar' => 'lembar',
                default => $unit !== '' ? $unit : 'lembar',
            };
        };

        $formatNumberClean = function ($value, $decimals = 2) {
            $formatted = number_format((float) $value, $decimals, ',', '.');
            $formatted = rtrim($formatted, '0');
            $formatted = rtrim($formatted, ',');

            return $formatted === '' ? '0' : $formatted;
        };

        $parseTwoDimensions = function ($text) {
            $clean = strtolower(trim((string) $text));

            if ($clean === '') {
                return null;
            }

            $clean = preg_replace('/\s+/', '', $clean);
            $clean = str_replace(['×', '*'], 'x', $clean);

            if (!preg_match('/^(\d+(?:[.,]\d+)?)x(\d+(?:[.,]\d+)?)(cm|m)?$/', $clean, $matches)) {
                return null;
            }

            $a = (float) str_replace(',', '.', $matches[1]);
            $b = (float) str_replace(',', '.', $matches[2]);
            $suffix = $matches[3] ?? '';

            if ($suffix === 'cm') {
                return [$a, $b, 'cm'];
            }

            if ($suffix === 'm') {
                return [$a, $b, 'm'];
            }

            $unit = ($a >= 10 && $b >= 10) ? 'cm' : 'm';

            return [$a, $b, $unit];
        };

        $resolveAreaValue = function ($sizeValue, $sizeDescription, $basePrice, $qty, $storedSubtotal) use ($parseTwoDimensions) {
            $sizeValue = (float) $sizeValue;
            $basePrice = (float) $basePrice;
            $qty = max((float) $qty, 0);
            $storedSubtotal = (float) $storedSubtotal;

            if ($sizeValue > 0) {
                return round($sizeValue, 4);
            }

            $dims = $parseTwoDimensions($sizeDescription);
            if ($dims) {
                [$a, $b, $parsedUnit] = $dims;

                if ($parsedUnit === 'cm') {
                    return round(($a * $b) / 10000, 4);
                }

                return round($a * $b, 4);
            }

            if ($storedSubtotal > 0 && $basePrice > 0 && $qty > 0) {
                return round($storedSubtotal / ($basePrice * $qty), 4);
            }

            return 1;
        };

        $resolveMeterValue = function ($sizeValue, $sizeDescription, $material, $basePrice, $qty, $storedSubtotal) use ($parseTwoDimensions) {
            $sizeValue = (float) $sizeValue;
            $basePrice = (float) $basePrice;
            $qty = max((float) $qty, 0);
            $storedSubtotal = (float) $storedSubtotal;

            if ($sizeValue > 0) {
                return round($sizeValue, 4);
            }

            $dims = $parseTwoDimensions($sizeDescription);
            if ($dims) {
                [$a, $b, $parsedUnit] = $dims;

                $aCm = $parsedUnit === 'cm' ? $a : ($a * 100);
                $bCm = $parsedUnit === 'cm' ? $b : ($b * 100);

                $rollWidthCm = (float) ($material->roll_width_cm ?? 0);
                $allowRotation = (bool) ($material->allow_rotation ?? true);

                if ($rollWidthCm > 0) {
                    $candidates = [];

                    if ($aCm <= $rollWidthCm) {
                        $candidates[] = $bCm;
                    }

                    if ($allowRotation && $bCm <= $rollWidthCm) {
                        $candidates[] = $aCm;
                    }

                    if (!empty($candidates)) {
                        return round(min($candidates) / 100, 4);
                    }

                    return round(max($aCm, $bCm) / 100, 4);
                }

                return round(min($aCm, $bCm) / 100, 4);
            }

            if ($storedSubtotal > 0 && $basePrice > 0 && $qty > 0) {
                return round($storedSubtotal / ($basePrice * $qty), 4);
            }

            return 1;
        };

        $resolveSizeValue = function ($sizeValue, $sizeDescription, $unit, $material = null, $basePrice = 0, $qty = 1, $storedSubtotal = 0) use (
            $normalizeUnitKey,
            $resolveAreaValue,
            $resolveMeterValue
        ) {
            $unitKey = $normalizeUnitKey($unit);

            if ($unitKey === 'm2') {
                return $resolveAreaValue($sizeValue, $sizeDescription, $basePrice, $qty, $storedSubtotal);
            }

            if ($unitKey === 'meter') {
                return $resolveMeterValue($sizeValue, $sizeDescription, $material, $basePrice, $qty, $storedSubtotal);
            }

            return 1;
        };

        $applyRoundingOnly = function ($amount) {
            $amount = max((float) $amount, 0);
            $roundTo = 1000;

            if ($amount <= 0) {
                return 0;
            }

            return (float) (ceil($amount / $roundTo) * $roundTo);
        };

        $applyMeterMinimumAndRounding = function ($amount) {
            $amount = max((float) $amount, 0);
            $minimumOrder = 10000;
            $roundTo = 1000;

            if ($amount <= 0) {
                return 0;
            }

            if ($amount < $minimumOrder) {
                $amount = $minimumOrder;
            }

            return (float) (ceil($amount / $roundTo) * $roundTo);
        };

        $calculateDisplaySubtotal = function ($basePrice, $qty, $unit, $resolvedSizeValue, $storedSubtotal = 0) use ($normalizeUnitKey, $applyRoundingOnly, $applyMeterMinimumAndRounding) {
            $unitKey = $normalizeUnitKey($unit);

            $basePrice = max((float) $basePrice, 0);
            $qty = max((float) $qty, 0);
            $resolvedSizeValue = max((float) $resolvedSizeValue, 0);
            $storedSubtotal = max((float) $storedSubtotal, 0);

            // Wajib utamakan subtotal final yang tersimpan.
            // Setelah ada minimal order + pembulatan, angka tampilan juga dipaksa rapi:
            // minimal Rp 10.000 dan pembulatan ke atas Rp 1.000.
            if ($storedSubtotal > 0) {
                return in_array($unitKey, ['m2', 'meter'], true)
                    ? round($applyMeterMinimumAndRounding($storedSubtotal), 2)
                    : round($applyRoundingOnly($storedSubtotal), 2);
            }

            if (in_array($unitKey, ['m2', 'meter'], true)) {
                return round($applyMeterMinimumAndRounding($basePrice * $resolvedSizeValue * $qty), 2);
            }

            return round($applyRoundingOnly($basePrice * $qty), 2);
        };

        $rawItems = method_exists($order, 'items')
            ? ($order->relationLoaded('items') ? $order->items : $order->items()->with('material')->get())
            : collect();

        $displayItems = $rawItems->isNotEmpty()
            ? $rawItems->map(function ($item) use ($normalizeUnitLabel,
                $normalizeUnitKey,
                $resolveSizeValue,
                $calculateDisplaySubtotal, $order) {
                $sizeUnit = $item->size_unit ?? 'lembar';
                $sizeUnitKey = $normalizeUnitKey($sizeUnit);
                $basePrice = (float) ($item->base_price ?? 0);
                $qty = (float) ($item->qty ?? 1);
                $storedSubtotal = (float) ($item->system_subtotal ?? $item->subtotal ?? 0);

                $resolvedSizeValue = $resolveSizeValue(
                    $item->size_value ?? 0,
                    $item->size_description ?? '',
                    $sizeUnit,
                    $item->material ?? null,
                    $basePrice,
                    $qty,
                    $storedSubtotal
                );

                $displaySubtotal = $calculateDisplaySubtotal(
                    $basePrice,
                    $qty,
                    $sizeUnit,
                    $resolvedSizeValue,
                    $storedSubtotal
                );

                return [
                    'model' => $item,
                    'id' => $item->id ?? null,
                    'product_name' => $item->product_name ?? '-',
                    'material_name' => $item->material_name ?? null,
                    'file_name' => $item->file_name ?? '-',
                    'size_description' => $item->size_description ?? '-',
                    'size_value' => (float) ($item->size_value ?? 0),
                    'resolved_size_value' => $resolvedSizeValue,
                    'size_unit' => $sizeUnitKey,
                    'size_unit_label' => $normalizeUnitLabel($sizeUnit),
                    'qty' => $qty,
                    'sisi' => (int) ($item->sisi ?? 1),
                    'base_price' => $basePrice,
                    'stored_subtotal' => $storedSubtotal,
                    'display_subtotal' => $displaySubtotal,
                    'finishing_note' => $item->finishing_note ?? null,
                    'file_url' => $item->file_url ?? $item->file_path_url ?? null,
                    'preview_image_path' => $item->preview_image_path ?? null,
                    'preview_image_url' => !empty($item->preview_image_path) ? route('orders.items.preview', [$order, $item]) : null,
                    'is_cancelled' => method_exists($item, 'isCancelled') ? $item->isCancelled() : (bool) ($item->is_cancelled ?? false),
                    'has_pending_cancellation' => method_exists($item, 'hasPendingCancellationRequest') ? $item->hasPendingCancellationRequest() : false,
                    'cancel_reason' => $item->cancel_reason ?? null,
                    'can_cancel' => method_exists($item, 'canBeCancelled') && auth()->check() && method_exists(auth()->user(), 'canRequestCancellations')
                        ? ($item->canBeCancelled() && !$item->hasPendingCancellationRequest() && auth()->user()->canRequestCancellations())
                        : false,
                ];
            })->values()
            : collect([
                (function () use (
                    $order,
                    $normalizeUnitLabel,
                    $normalizeUnitKey,
                    $resolveSizeValue,
                    $calculateDisplaySubtotal
                ) {
                    $sizeUnit = $order->size_unit ?? 'lembar';
                    $sizeUnitKey = $normalizeUnitKey($sizeUnit);
                    $basePrice = (float) ($order->base_price ?? 0);
                    $qty = (float) ($order->qty ?? 1);
                    $storedSubtotal = (float) ($order->total_price ?? 0);

                    $resolvedSizeValue = $resolveSizeValue(
                        $order->size_value ?? 0,
                        $order->size ?? '',
                        $sizeUnit,
                        null,
                        $basePrice,
                        $qty,
                        $storedSubtotal
                    );

                    $displaySubtotal = $calculateDisplaySubtotal(
                        $basePrice,
                        $qty,
                        $sizeUnit,
                        $resolvedSizeValue,
                        $storedSubtotal
                    );

                    return [
                        'model' => null,
                        'id' => null,
                        'product_name' => $order->product_name ?? '-',
                        'material_name' => $order->material_name ?? null,
                        'file_name' => $order->file_name ?? '-',
                        'size_description' => $order->size ?? '-',
                        'size_value' => (float) ($order->size_value ?? 0),
                        'resolved_size_value' => $resolvedSizeValue,
                        'size_unit' => $sizeUnitKey,
                        'size_unit_label' => $normalizeUnitLabel($sizeUnit),
                        'qty' => $qty,
                        'sisi' => (int) ($order->sisi ?? 1),
                        'base_price' => $basePrice,
                        'stored_subtotal' => $storedSubtotal,
                        'display_subtotal' => $displaySubtotal,
                        'finishing_note' => $order->finishing_note ?? null,
                        'file_url' => null,
                        'preview_image_path' => null,
                        'preview_image_url' => null,
                        'is_cancelled' => false,
                        'has_pending_cancellation' => false,
                        'cancel_reason' => null,
                        'can_cancel' => false,
                    ];
                })(),
            ]);

        $activeItems = $displayItems->where('is_cancelled', false)->values();
        $activeItemsCount = $activeItems->count();
        $cancelledItemsCount = $displayItems->where('is_cancelled', true)->count();
        $displayGrandTotal = (float) $activeItems->sum(fn ($item) => (float) $item['display_subtotal']);

        // Sinkron tampilan pembayaran dengan total final yang sudah kena minimal order + pembulatan.
        // Jangan lagi pakai change_amount lama apa adanya, karena data lama bisa masih menyimpan
        // kembalian dari total sebelum pembulatan.
        $displayPaidAmount = (float) ($order->paid_amount ?? 0);

        if ($displayPaidAmount <= 0 && isset($order->payments)) {
            $displayPaidAmount = (float) $order->payments->sum('amount');
        }

        $displayChangeAmount = 0;

        if ($order->isPaid()) {
            $displayChangeAmount = max($displayPaidAmount - $displayGrandTotal, 0);

            // Jika paid_amount sudah berupa nilai bersih setelah dikurangi kembalian,
            // maka kembalian wajib 0 agar tidak muncul angka lama seperti Rp 600.
            if ($displayPaidAmount <= $displayGrandTotal) {
                $displayChangeAmount = 0;
            }
        }
    @endphp

    <x-common.page-breadcrumb pageTitle="{{ $title ?? 'Detail Order' }}" />

    @if(session('success'))
        <div class="mb-4 rounded-lg bg-success-50 p-4 text-sm text-success-700 dark:bg-success-500/15 dark:text-success-500">
            {{ session('success') }}
        </div>
    @endif

    @if(session('error'))
        <div class="mb-4 rounded-lg bg-error-50 p-4 text-sm text-error-700 dark:bg-error-500/15 dark:text-error-500">
            {{ session('error') }}
        </div>
    @endif

    @if($order->isCancelled())
        <div class="mb-4 rounded-lg border border-error-200 bg-error-50 p-4 dark:border-error-500/30 dark:bg-error-500/10">
            <div class="flex items-start gap-3">
                <div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-error-100 dark:bg-error-500/20">
                    <svg class="size-4 text-error-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
                    </svg>
                </div>
                <div>
                    <h4 class="text-sm font-semibold text-error-700 dark:text-error-400">Order Dibatalkan</h4>
                    <p class="mt-1 text-sm text-error-600 dark:text-error-300">
                        {{ $order->cancel_reason }}
                    </p>
                    <p class="mt-1 text-xs text-error-500 dark:text-error-400">
                        Dibatalkan oleh {{ $order->canceller->name ?? '-' }} pada {{ $order->cancelled_at?->format('d M Y H:i') }}
                    </p>
                </div>
            </div>
        </div>
    @endif

    @if(!$order->isCancelled() && $order->hasPendingCancellationRequest())
        <div class="mb-4 rounded-lg border border-warning-200 bg-warning-50 p-4 dark:border-warning-500/30 dark:bg-warning-500/10">
            <div class="flex items-center gap-3">
                <svg class="size-5 text-warning-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <p class="text-sm font-medium text-warning-700 dark:text-warning-400">
                    Menunggu approval pembatalan order dari supervisor
                </p>
            </div>
        </div>
    @endif

    <div class="grid grid-cols-1 gap-6 lg:grid-cols-3">
        <div class="lg:col-span-2 space-y-6">
            <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
                <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800">
                    <div class="flex items-center justify-between">
                        <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">{{ $order->invoice_number }}</h3>
                        <div class="flex items-center gap-2 flex-wrap">
                            @if($order->isCancelled())
                                <span class="inline-flex rounded-full px-3 py-1 text-xs font-medium {{ $order->getCancelledBadgeClass() }}">
                                    Dibatalkan
                                </span>
                            @endif

                            @if($order->is_credit)
                                <span class="inline-flex rounded-full px-3 py-1 text-xs font-medium bg-warning-100 text-warning-700 dark:bg-warning-500/20 dark:text-warning-400">
                                    Piutang
                                </span>
                            @endif

                            <span class="inline-flex rounded-full px-3 py-1 text-xs font-medium {{ $order->getPaymentStatusBadgeClass() }}">
                                {{ $order->getPaymentStatusLabel() }}
                            </span>

                            @if(!$order->isCancelled())
                                <span class="inline-flex rounded-full px-3 py-1 text-xs font-medium {{ $order->getProductionStatusBadgeClass() }}">
                                    {{ $order->getProductionStatusLabel() }}
                                </span>
                            @endif

                            <span class="inline-flex rounded-full px-3 py-1 text-xs font-medium {{ $order->getPickupStatusBadgeClass() }}">
                                {{ $order->getPickupStatusLabel() }}
                            </span>
                        </div>
                    </div>
                </div>

                <div class="p-5">
                    <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
                        <div>
                            <h4 class="text-sm font-semibold text-gray-500 dark:text-gray-400 mb-3">Data Pelanggan</h4>
                            <dl class="space-y-2">
                                <div>
                                    <dt class="text-xs text-gray-500">Nama</dt>
                                    <dd class="text-sm font-medium text-gray-800 dark:text-white/90">{{ $order->customer_name }}</dd>
                                </div>

                                @if($order->customer_phone)
                                    <div>
                                        <dt class="text-xs text-gray-500">Telepon</dt>
                                        <dd class="text-sm font-medium text-gray-800 dark:text-white/90">{{ $order->customer_phone }}</dd>
                                    </div>
                                @endif
                            </dl>
                        </div>

                        <div>
                            <h4 class="text-sm font-semibold text-gray-500 dark:text-gray-400 mb-3">Detail Order</h4>
                            <dl class="space-y-2">
                                <div>
                                    <dt class="text-xs text-gray-500">Tanggal</dt>
                                    <dd class="text-sm font-medium text-gray-800 dark:text-white/90">{{ $order->created_at->format('d M Y H:i') }}</dd>
                                </div>
                                <div>
                                    <dt class="text-xs text-gray-500">Designer</dt>
                                    <dd class="text-sm font-medium text-gray-800 dark:text-white/90">{{ $order->designer->name ?? '-' }}</dd>
                                </div>
                                <div>
                                    <dt class="text-xs text-gray-500">Jumlah Item</dt>
                                    <dd class="text-sm font-medium text-gray-800 dark:text-white/90">{{ $displayItems->count() }} item</dd>
                                </div>
                            </dl>
                        </div>
                    </div>

                    @if($order->notes)
                        <div class="mt-4 rounded-lg bg-gray-50 dark:bg-gray-800 p-3">
                            <dt class="text-xs text-gray-500 mb-1">Catatan Order</dt>
                            <dd class="text-sm text-gray-700 dark:text-gray-300">{{ $order->notes }}</dd>
                        </div>
                    @endif
                </div>
            </div>

            <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
                <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800">
                    <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Item Order</h3>
                </div>

                <div class="p-5">
                    <div class="space-y-4">
                        @foreach($displayItems as $index => $displayItem)
                            @php
                                $itemModel = $displayItem['model'];
                                $isCancelled = $displayItem['is_cancelled'];
                                $hasPendingCancellation = $displayItem['has_pending_cancellation'];
                                $canCancelItem = $displayItem['can_cancel'] && $itemModel;
                                $qtyDisplay = $formatNumberClean($displayItem['qty']);
                                $sizeValueDisplay = $displayItem['size_unit'] === 'lembar'
                                    ? '1'
                                    : $formatNumberClean($displayItem['resolved_size_value'], 4);
                                $displaySubtotal = (float) $displayItem['display_subtotal'];
                            @endphp

                            <div class="rounded-xl border {{ $isCancelled ? 'border-error-200 dark:border-error-500/30 opacity-60' : 'border-gray-200 dark:border-gray-700' }} p-4 relative">
                                @if($isCancelled)
                                    <div class="absolute -top-2 -right-2 z-10">
                                        <span class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium bg-error-500 text-white shadow-sm">
                                            Dibatalkan
                                        </span>
                                    </div>
                                @endif

                                @if(!$isCancelled && $hasPendingCancellation)
                                    <div class="absolute -top-2 -right-2 z-10">
                                        <span class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium bg-warning-500 text-white shadow-sm">
                                            Menunggu Approval
                                        </span>
                                    </div>
                                @endif

                                <div class="flex items-start justify-between mb-3">
                                    <div class="flex items-center gap-3">
                                        <span class="inline-flex items-center justify-center h-6 w-6 rounded-full {{ $isCancelled ? 'bg-error-100 dark:bg-error-500/20 text-error-700 dark:text-error-400' : 'bg-brand-100 dark:bg-brand-500/20 text-brand-700 dark:text-brand-400' }} text-xs font-bold">
                                            {{ $index + 1 }}
                                        </span>

                                        <div>
                                            <h5 class="text-sm font-semibold text-gray-800 dark:text-white/90 {{ $isCancelled ? 'line-through' : '' }}">
                                                {{ $displayItem['product_name'] }}
                                            </h5>

                                            @if($displayItem['material_name'])
                                                <p class="text-xs text-gray-500">{{ $displayItem['material_name'] }}</p>
                                            @endif
                                        </div>
                                    </div>

                                    <div class="flex items-center gap-2">
                                        <span class="text-sm font-bold {{ $isCancelled ? 'text-error-400 line-through' : 'text-brand-600 dark:text-brand-400' }}">
                                            Rp {{ number_format($displaySubtotal, 0, ',', '.') }}
                                        </span>

                                        @if($canCancelItem)
                                            <button
                                                @click="$dispatch('open-cancel-modal', {
                                                    action: '{{ route('orders.items.request-cancel', $itemModel) }}',
                                                    title: 'Batalkan Item: {{ addslashes($displayItem['product_name']) }}?',
                                                    description: '{{ auth()->user()->canApproveCancellations() ? 'Item akan langsung dibatalkan.' : 'Request akan dikirim ke supervisor untuk approval.' }}'
                                                })"
                                                class="ml-1 rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-error-50 hover:text-error-500 dark:hover:bg-error-500/10"
                                                title="Batalkan item">
                                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
                                                </svg>
                                            </button>
                                        @endif
                                    </div>
                                </div>

                                <div class="grid grid-cols-2 md:grid-cols-5 gap-3 text-sm">
                                    <div>
                                        <dt class="text-xs text-gray-500">Nama File</dt>
                                        <dd class="font-medium text-gray-800 dark:text-white/90">{{ $displayItem['file_name'] }}</dd>
                                    </div>

                                    <div>
                                        <dt class="text-xs text-gray-500">Ukuran</dt>
                                        <dd class="font-medium text-gray-800 dark:text-white/90">{{ $displayItem['size_description'] }}</dd>
                                    </div>

                                    <div>
                                        <dt class="text-xs text-gray-500">Sisi</dt>
                                        <dd class="font-medium text-gray-800 dark:text-white/90">
                                            @if($displayItem['size_unit'] === 'm2')
                                                <span class="text-gray-500">-</span>
                                            @elseif(($displayItem['sisi'] ?? 1) == 2)
                                                <span class="inline-flex items-center rounded-full bg-brand-100 px-2 py-0.5 text-xs font-semibold text-brand-700 dark:bg-brand-500/20 dark:text-brand-400">
                                                    2 sisi
                                                </span>
                                            @else
                                                1 sisi
                                            @endif
                                        </dd>
                                    </div>

                                    <div>
                                        <dt class="text-xs text-gray-500">Harga/{{ $displayItem['size_unit_label'] }}</dt>
                                        <dd class="font-medium text-gray-800 dark:text-white/90">
                                            Rp {{ number_format((float) $displayItem['base_price'], 0, ',', '.') }}
                                        </dd>
                                    </div>

                                    <div>
                                        <dt class="text-xs text-gray-500">Qty</dt>
                                        <dd class="font-medium text-gray-800 dark:text-white/90">{{ $qtyDisplay }}</dd>
                                    </div>
                                </div>

                                @if($displayItem['finishing_note'])
                                    <div class="mt-3 rounded-lg bg-brand-50 dark:bg-brand-500/10 p-2">
                                        <span class="text-xs text-gray-500">Finishing:</span>
                                        <span class="text-sm text-brand-700 dark:text-brand-400">{{ $displayItem['finishing_note'] }}</span>
                                    </div>
                                @endif

                                @if($displayItem['file_url'])
                                    <div class="mt-3">
                                        <a href="{{ $displayItem['file_url'] }}" target="_blank"
                                            class="inline-flex items-center gap-2 text-xs font-medium text-brand-600 hover:underline dark:text-brand-400">
                                            <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828L18 9.828M8 7h8a2 2 0 012 2v8" />
                                            </svg>
                                            Lihat File
                                        </a>
                                    </div>
                                @endif

                                @if(!empty($displayItem['preview_image_url']))
                                    <div class="mt-3 rounded-xl border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-800/60">
                                        <div class="mb-2 flex items-center justify-between gap-3">
                                            <div>
                                                <p class="text-xs font-semibold text-gray-700 dark:text-gray-300">
                                                    Preview Upload
                                                </p>
                                                <p class="text-[11px] text-gray-500 dark:text-gray-400">
                                                    Klik gambar untuk lihat ukuran besar.
                                                </p>
                                            </div>

                                            <button
                                                type="button"
                                                onclick="openPreviewImageModal(@js($displayItem['preview_image_url']), @js($displayItem['file_name'] ?? 'Preview Order'))"
                                                class="rounded-lg bg-brand-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-brand-600"
                                            >
                                                Lihat Besar
                                            </button>
                                        </div>

                                        <button
                                            type="button"
                                            onclick="openPreviewImageModal(@js($displayItem['preview_image_url']), @js($displayItem['file_name'] ?? 'Preview Order'))"
                                            class="inline-block overflow-hidden rounded-lg border border-gray-200 bg-white shadow-sm transition hover:scale-[1.02] dark:border-gray-700 dark:bg-gray-900"
                                        >
                                            <img
                                                src="{{ $displayItem['preview_image_url'] }}"
                                                alt="Preview {{ $displayItem['file_name'] ?? 'Order' }}"
                                                class="h-28 w-28 object-cover"
                                                loading="lazy"
                                            >
                                        </button>
                                    </div>
                                @endif

                                @if($isCancelled && $displayItem['cancel_reason'])
                                    <div class="mt-3 rounded-lg bg-error-50 dark:bg-error-500/10 p-2">
                                        <span class="text-xs text-error-500">Alasan:</span>
                                        <span class="text-sm text-error-700 dark:text-error-400">{{ $displayItem['cancel_reason'] }}</span>
                                    </div>
                                @endif

                                <div class="mt-3 pt-2 border-t {{ $isCancelled ? 'border-error-100 dark:border-error-500/20' : 'border-gray-100 dark:border-gray-700' }} text-xs text-gray-500">
                                    Rp {{ number_format((float) $displayItem['base_price'], 0, ',', '.') }}
                                    × {{ $sizeValueDisplay }} {{ $displayItem['size_unit_label'] }}
                                    × {{ $qtyDisplay }}
                                    = <span class="font-semibold {{ $isCancelled ? 'text-error-500 line-through' : 'text-gray-700 dark:text-gray-300' }}">
                                        Rp {{ number_format($displaySubtotal, 0, ',', '.') }}
                                    </span>
                                </div>
                            </div>
                        @endforeach
                    </div>

                    <div class="mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
                        <div class="flex items-center justify-between">
                            <span class="text-sm text-gray-600 dark:text-gray-400">
                                Grand Total ({{ $activeItemsCount }} item aktif)
                            </span>
                            <span class="text-xl font-bold text-brand-600 dark:text-brand-400">
                                Rp {{ number_format($displayGrandTotal, 0, ',', '.') }}
                            </span>
                        </div>

                        @if($cancelledItemsCount > 0)
                            <p class="mt-1 text-xs text-error-500">
                                {{ $cancelledItemsCount }} item dibatalkan
                            </p>
                        @endif

                        @if($order->isPaid())
                            <div class="mt-2 space-y-1">
                                <div class="flex justify-between text-sm">
                                    <span class="text-gray-500">Dibayar</span>
                                    <span class="text-gray-800 dark:text-white/90">
                                        Rp {{ number_format($displayPaidAmount, 0, ',', '.') }}
                                    </span>
                                </div>
                                <div class="flex justify-between text-sm">
                                    <span class="text-gray-500">Kembalian</span>
                                    <span class="text-gray-800 dark:text-white/90">
                                        Rp {{ number_format($displayChangeAmount, 0, ',', '.') }}
                                    </span>
                                </div>
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>

        <div class="space-y-6">
            <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
                <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800">
                    <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Aksi</h3>
                </div>

                <div class="p-5 space-y-3">
                    @if(!$order->isCancelled())
                        @if($order->canPrintSPK() && auth()->user()->canPrintSPK())
                            <a href="{{ route('print.spk', $order) }}" target="_blank"
                                class="flex w-full items-center justify-center gap-2 rounded-lg bg-brand-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-600">
                                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
                                </svg>
                                Cetak SPK
                            </a>
                        @endif

                        @if($order->isPaid() && auth()->user()->canProcessPayments())
                            <a href="{{ route('print.nota', $order) }}" target="_blank"
                                class="flex w-full items-center justify-center gap-2 rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700">
                                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
                                </svg>
                                Cetak Nota
                            </a>

                            <a href="{{ route('print.faktur', $order) }}" target="_blank"
                                class="flex w-full items-center justify-center gap-2 rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700">
                                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                </svg>
                                Cetak Faktur
                            </a>
                        @endif

                        @if(auth()->user()->can('edit orders'))
                            <a href="{{ route('orders.edit', $order) }}"
                                class="flex w-full items-center justify-center gap-2 rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700">
                                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                </svg>
                                Edit Order
                            </a>
                        @endif

                        @if($order->canMarkAsPickedUp())
                            <form action="{{ route('orders.mark-picked-up', $order) }}" method="POST">
                                @csrf
                                <button type="submit"
                                    class="flex w-full items-center justify-center gap-2 rounded-lg bg-success-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-success-600">
                                    <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                                    </svg>
                                    Tandai Sudah Diambil
                                </button>
                            </form>
                        @endif

                        @if($order->canBeCancelled() && !$order->hasPendingCancellationRequest() && auth()->user()->canRequestCancellations())
                            <button
                                @click="$dispatch('open-cancel-modal', {
                                    action: '{{ route('orders.request-cancel', $order) }}',
                                    title: 'Batalkan Order {{ $order->invoice_number }}?',
                                    description: '{{ auth()->user()->canApproveCancellations() ? 'Semua item dalam order ini akan dibatalkan.' : 'Request akan dikirim ke supervisor untuk approval.' }}'
                                })"
                                class="flex w-full items-center justify-center gap-2 rounded-lg border border-error-300 bg-white px-4 py-2.5 text-sm font-medium text-error-600 transition-colors hover:bg-error-50 dark:border-error-500/30 dark:bg-gray-800 dark:text-error-400 dark:hover:bg-error-500/10">
                                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
                                </svg>
                                Batalkan Order
                            </button>
                        @endif

                        @if($order->customer_phone)
                            @php
                                $phone = preg_replace('/[^0-9]/', '', $order->customer_phone);
                                if (str_starts_with($phone, '08')) {
                                    $phone = '62' . substr($phone, 1);
                                } elseif (str_starts_with($phone, '8')) {
                                    $phone = '62' . $phone;
                                } elseif (str_starts_with($phone, '+62')) {
                                    $phone = substr($phone, 1);
                                }
                                $waMessage = urlencode(\App\Models\Setting::buildWaMessage($order));
                            @endphp

                            <a href="https://wa.me/{{ $phone }}?text={{ $waMessage }}"
                               target="_blank"
                               class="flex w-full items-center justify-center gap-2 rounded-lg bg-green-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-green-600">
                                <svg class="size-5" viewBox="0 0 24 24" fill="currentColor">
                                    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
                                </svg>
                                Kirim WA
                            </a>
                        @endif
                    @endif

                    <a href="{{ route('orders.index') }}"
                        class="flex w-full items-center justify-center gap-2 rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700">
                        Kembali
                    </a>
                </div>
            </div>

            <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
                <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800">
                    <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Riwayat</h3>
                </div>

                <div class="p-5">
                    <div class="space-y-4">
                        <div class="flex gap-3">
                            <div class="flex h-8 w-8 items-center justify-center rounded-full bg-brand-100 text-brand-500 dark:bg-brand-500/20">
                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                                </svg>
                            </div>
                            <div>
                                <p class="text-sm font-medium text-gray-800 dark:text-white/90">Order Dibuat</p>
                                <p class="text-xs text-gray-500">{{ $order->created_at->format('d M Y H:i') }}</p>
                                <p class="text-xs text-gray-500">oleh {{ $order->designer->name ?? '-' }}</p>
                            </div>
                        </div>

                        @if($order->isPaid())
                            <div class="flex gap-3">
                                <div class="flex h-8 w-8 items-center justify-center rounded-full bg-success-100 text-success-500 dark:bg-success-500/20">
                                    <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                                    </svg>
                                </div>
                                <div>
                                    <p class="text-sm font-medium text-gray-800 dark:text-white/90">Pembayaran</p>
                                    <p class="text-xs text-gray-500">{{ $order->paid_at?->format('d M Y H:i') }}</p>
                                    <p class="text-xs text-gray-500">oleh {{ $order->cashier->name ?? '-' }}</p>
                                </div>
                            </div>
                        @endif

                        @if($order->spk_printed)
                            <div class="flex gap-3">
                                <div class="flex h-8 w-8 items-center justify-center rounded-full bg-blue-light-100 text-blue-light-500 dark:bg-blue-light-500/20">
                                    <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
                                    </svg>
                                </div>
                                <div>
                                    <p class="text-sm font-medium text-gray-800 dark:text-white/90">SPK Dicetak</p>
                                    <p class="text-xs text-gray-500">{{ $order->spk_printed_at?->format('d M Y H:i') }}</p>
                                </div>
                            </div>
                        @endif

                        @if($order->started_at)
                            <div class="flex gap-3">
                                <div class="flex h-8 w-8 items-center justify-center rounded-full bg-warning-100 text-warning-500 dark:bg-warning-500/20">
                                    <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                    </svg>
                                </div>
                                <div>
                                    <p class="text-sm font-medium text-gray-800 dark:text-white/90">Produksi Dimulai</p>
                                    <p class="text-xs text-gray-500">{{ $order->started_at->format('d M Y H:i') }}</p>
                                    <p class="text-xs text-gray-500">oleh {{ $order->operator->name ?? '-' }}</p>
                                </div>
                            </div>
                        @endif

                        @if($order->finished_at)
                            <div class="flex gap-3">
                                <div class="flex h-8 w-8 items-center justify-center rounded-full bg-success-100 text-success-500 dark:bg-success-500/20">
                                    <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <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" />
                                    </svg>
                                </div>
                                <div>
                                    <p class="text-sm font-medium text-gray-800 dark:text-white/90">Selesai</p>
                                    <p class="text-xs text-gray-500">{{ $order->finished_at->format('d M Y H:i') }}</p>
                                </div>
                            </div>
                        @endif

                        @if($order->picked_up_at)
                            <div class="flex gap-3">
                                <div class="flex h-8 w-8 items-center justify-center rounded-full bg-success-100 text-success-500 dark:bg-success-500/20">
                                    <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                                    </svg>
                                </div>
                                <div>
                                    <p class="text-sm font-medium text-gray-800 dark:text-white/90">Diambil</p>
                                    <p class="text-xs text-gray-500">{{ $order->picked_up_at->format('d M Y H:i') }}</p>
                                </div>
                            </div>
                        @endif

                        @if($order->isCancelled())
                            <div class="flex gap-3">
                                <div class="flex h-8 w-8 items-center justify-center rounded-full bg-error-100 text-error-500 dark:bg-error-500/20">
                                    <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
                                    </svg>
                                </div>
                                <div>
                                    <p class="text-sm font-medium text-error-700 dark:text-error-400">Dibatalkan</p>
                                    <p class="text-xs text-gray-500">{{ $order->cancelled_at?->format('d M Y H:i') }}</p>
                                    <p class="text-xs text-gray-500">oleh {{ $order->canceller->name ?? '-' }}</p>
                                    @if($order->cancel_reason)
                                        <p class="mt-1 text-xs text-error-500">{{ $order->cancel_reason }}</p>
                                    @endif
                                </div>
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>

    <x-ui.cancel-confirm />

    {{-- Modal Preview Gambar --}}
    <div
        id="previewImageModal"
        class="fixed inset-0 z-[999999] hidden items-center justify-center bg-black/70 p-4 backdrop-blur-sm"
        onclick="closePreviewImageModal()"
    >
        <div
            class="relative max-h-[92vh] w-full max-w-5xl overflow-hidden rounded-2xl bg-white shadow-2xl ring-1 ring-black/10 dark:bg-gray-900 dark:ring-white/10"
            onclick="event.stopPropagation()"
        >
            <div class="flex items-center justify-between border-b border-gray-200 px-4 py-3 dark:border-gray-800">
                <div>
                    <h3 class="text-sm font-semibold text-gray-800 dark:text-white/90">Preview Upload</h3>
                    <p id="previewImageTitle" class="mt-0.5 text-xs text-gray-500 dark:text-gray-400">-</p>
                </div>

                <button
                    type="button"
                    onclick="closePreviewImageModal()"
                    class="inline-flex h-9 w-9 items-center justify-center rounded-lg text-gray-500 transition hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-white"
                    aria-label="Tutup preview"
                >
                    <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                </button>
            </div>

            <div class="max-h-[calc(92vh-64px)] overflow-auto bg-gray-50 p-4 text-center dark:bg-gray-950">
                <img
                    id="previewImageModalImg"
                    src=""
                    alt="Preview Upload"
                    class="mx-auto max-h-[78vh] max-w-full rounded-xl object-contain shadow-sm"
                >
            </div>
        </div>
    </div>

    <script>
        function openPreviewImageModal(imageUrl, title) {
            const modal = document.getElementById('previewImageModal');
            const image = document.getElementById('previewImageModalImg');
            const titleEl = document.getElementById('previewImageTitle');

            if (!modal || !image || !titleEl) {
                return;
            }

            image.src = imageUrl || '';
            titleEl.textContent = title || 'Preview Order';

            modal.classList.remove('hidden');
            modal.classList.add('flex');
            document.body.classList.add('overflow-hidden');
        }

        function closePreviewImageModal() {
            const modal = document.getElementById('previewImageModal');
            const image = document.getElementById('previewImageModalImg');

            if (!modal || !image) {
                return;
            }

            modal.classList.add('hidden');
            modal.classList.remove('flex');
            image.src = '';
            document.body.classList.remove('overflow-hidden');
        }

        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') {
                closePreviewImageModal();
            }
        });
    </script>

@endsection

{{-- Preview gambar tersedia via $item->preview_image_path --}}
