@extends('layouts.teknisi')

@section('title', 'Detail Produksi - Teknisi')

@section('content')
<div class="space-y-4">
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
        <div class="flex items-center space-x-3">
            <a href="{{ route('teknisi.productions.index') }}" 
                class="flex items-center justify-center w-10 h-10 text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors duration-200"
                title="Kembali">
                <i class="fas fa-arrow-left text-lg"></i>
            </a>
            <div>
                <h1 class="text-2xl font-bold text-gray-800 dark:text-white">Detail Produksi #{{ $production->id }}</h1>
                <p class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                    {{ $production->product->product_title ?? 'N/A' }} · {{ $production->order->customer_name ?? 'N/A' }}
                </p>
            </div>
        </div>
    </div>

    <!-- Notifications -->
    @if(session('success'))
    <div class="bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800 text-green-800 dark:text-green-200 px-4 py-3 rounded-lg flex items-center gap-3">
        <i class="fas fa-check-circle text-green-500"></i>
        <span>{{ session('success') }}</span>
    </div>
    @endif

    @if(session('info'))
    <div class="bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800 text-blue-800 dark:text-blue-200 px-4 py-3 rounded-lg flex items-center gap-3">
        <i class="fas fa-info-circle text-blue-500"></i>
        <span>{{ session('info') }}</span>
    </div>
    @endif

    @if($errors->any())
    <div class="bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200 px-4 py-3 rounded-lg">
        <ul class="list-disc list-inside text-sm">
            @foreach($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
    @endif

    <!-- Notification Area -->
    <div id="notificationArea" class="fixed top-4 right-4 z-50 space-y-2"></div>

    @if($errors->any())
    <div class="bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200 px-4 py-3 rounded-lg">
        <ul class="list-disc list-inside text-sm">
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
    </div>
    @endif

    <!-- Progress Timeline -->
    @include('teknisi.productions.partials.timeline', ['production' => $production])

    <!-- Info Cards Row -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <!-- Info Produksi -->
        <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <div class="flex items-center gap-2 mb-3">
                <div class="p-2 bg-blue-100 dark:bg-blue-900/40 rounded-lg">
                    <i class="fas fa-industry text-blue-600 dark:text-blue-400 text-sm"></i>
                </div>
                <h3 class="text-sm font-semibold text-gray-900 dark:text-white">Info Produksi</h3>
            </div>
            <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400">Qty:</span>
                    <span class="font-semibold text-gray-900 dark:text-white">{{ $production->quantity ?? 1 }} unit</span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400">Customer:</span>
                    <span class="font-medium text-gray-900 dark:text-white text-xs truncate">{{ $production->order->customer_name ?? 'N/A' }}</span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400">Ditugaskan:</span>
                    <span class="font-medium text-gray-900 dark:text-white text-xs">{{ $production->assigned_at?->format('d/m/Y') ?? 'N/A' }}</span>
                </div>
            </div>
        </div>

        <!-- Info Order -->
        <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <div class="flex items-center gap-2 mb-3">
                <div class="p-2 bg-emerald-100 dark:bg-emerald-900/40 rounded-lg">
                    <i class="fas fa-shopping-cart text-emerald-600 dark:text-emerald-400 text-sm"></i>
                </div>
                <h3 class="text-sm font-semibold text-gray-900 dark:text-white">Info Pesanan</h3>
            </div>
            <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400">Order ID:</span>
                    <span class="font-medium text-gray-900 dark:text-white">#{{ $production->order->id ?? 'N/A' }}</span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400">Produk:</span>
                    <span class="font-medium text-gray-900 dark:text-white text-xs truncate" title="{{ $production->product->product_title ?? 'N/A' }}">{{ Str::limit($production->product->product_title ?? 'N/A', 15) }}</span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400">Harga:</span>
                    <span class="font-semibold text-emerald-600 dark:text-emerald-400">Rp {{ number_format($production->order->total_price ?? 0, 0, ',', '.') }}</span>
                </div>
            </div>
        </div>

        <!-- Quick Stats -->
        <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <div class="flex items-center gap-2 mb-3">
                <div class="p-2 bg-purple-100 dark:bg-purple-900/40 rounded-lg">
                    <i class="fas fa-chart-pie text-purple-600 dark:text-purple-400 text-sm"></i>
                </div>
                <h3 class="text-sm font-semibold text-gray-900 dark:text-white">Ringkasan</h3>
            </div>
            <div class="space-y-2 text-sm">
                @php
                    $materialTotal = $production->total_material_cost ?? 0;
                    $sparepartTotal = $production->total_sparepart_cost ?? 0;
                    $directTotal = $materialTotal + $sparepartTotal;
                @endphp
                <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400">Bahan:</span>
                    <span class="font-medium text-gray-900 dark:text-white">{{ $production->productionMaterials->count() }} item</span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400">Sparepart:</span>
                    <span class="font-medium text-gray-900 dark:text-white">{{ $production->productionSpareparts->count() }} item</span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400">Total:</span>
                    <span class="font-bold text-indigo-600 dark:text-indigo-400">Rp {{ number_format($directTotal, 0, ',', '.') }}</span>
                </div>
            </div>
        </div>

        <!-- Status Info -->
        <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <div class="flex items-center gap-2 mb-3">
                <div class="p-2 bg-orange-100 dark:bg-orange-900/40 rounded-lg">
                    <i class="fas fa-info-circle text-orange-600 dark:text-orange-400 text-sm"></i>
                </div>
                <h3 class="text-sm font-semibold text-gray-900 dark:text-white">Status</h3>
            </div>
            <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400">Planning:</span>
                    @php
                        $statusColors = [
                            'planning' => ['bg' => 'bg-blue-100 dark:bg-blue-900/40', 'text' => 'text-blue-700 dark:text-blue-300', 'label' => 'Planning'],
                            'pending_approval' => ['bg' => 'bg-amber-100 dark:bg-amber-900/40', 'text' => 'text-amber-700 dark:text-amber-300', 'label' => 'Pending'],
                            'approved' => ['bg' => 'bg-green-100 dark:bg-green-900/40', 'text' => 'text-green-700 dark:text-green-300', 'label' => 'Approved'],
                            'rejected' => ['bg' => 'bg-red-100 dark:bg-red-900/40', 'text' => 'text-red-700 dark:text-red-300', 'label' => 'Rejected'],
                        ];
                        $planningStatus = $statusColors[$production->planning_status] ?? $statusColors['planning'];
                    @endphp
                    <span class="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-md {{ $planningStatus['bg'] }} {{ $planningStatus['text'] }}">
                        {{ $planningStatus['label'] }}
                    </span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400">Produksi:</span>
                    @php
                        $prodStatusColors = [
                            'menunggu' => ['bg' => 'bg-gray-100 dark:bg-gray-700/50', 'text' => 'text-gray-700 dark:text-gray-300', 'label' => 'Menunggu'],
                            'dalam_proses' => ['bg' => 'bg-yellow-100 dark:bg-yellow-900/40', 'text' => 'text-yellow-700 dark:text-yellow-300', 'label' => 'Dalam Proses'],
                            'selesai' => ['bg' => 'bg-green-100 dark:bg-green-900/40', 'text' => 'text-green-700 dark:text-green-300', 'label' => 'Selesai'],
                        ];
                        $prodStatus = $prodStatusColors[$production->status] ?? $prodStatusColors['menunggu'];
                    @endphp
                    <span class="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-md {{ $prodStatus['bg'] }} {{ $prodStatus['text'] }}">
                        {{ $prodStatus['label'] }}
                    </span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500 dark:text-gray-400">Bayar:</span>
                    <span class="font-medium text-gray-900 dark:text-white">{{ strtoupper($production->order->payment_method ?? 'N/A') }}</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Supervisor Feedback -->
    @if($production->supervisor_feedback && in_array($production->planning_status, ['rejected', 'planning']))
    <div class="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4">
        <h3 class="text-sm font-semibold text-amber-900 dark:text-amber-200 mb-2 flex items-center gap-2">
            <i class="fas fa-exclamation-triangle"></i> Feedback Supervisor
            @if($production->planning_status === 'planning')
            <span class="px-2 py-0.5 text-xs bg-amber-200 text-amber-800 rounded">Revisi</span>
                            @endif
                                </h3>
        <p class="text-sm text-amber-800 dark:text-amber-200">{{ $production->supervisor_feedback }}</p>
                            </div>
                                    @endif

    {{-- ============================================== --}}
    {{-- TABEL GABUNGAN BAHAN & SPAREPART --}}
    {{-- ============================================== --}}
    @php
        $canEdit = $production->planning_status === 'planning';
        $canCheckReceived = $production->planning_status === 'approved' && in_array($production->status, ['menunggu', 'dalam_proses']);
                        @endphp
    
    <!-- Tabel Bahan & Sparepart -->
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 mb-6">
        <div class="px-5 py-4 border-b border-gray-200 dark:border-gray-700">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="p-2 bg-indigo-100 dark:bg-indigo-900/40 rounded-lg">
                        <i class="fas fa-boxes text-indigo-600 dark:text-indigo-400 text-sm"></i>
                    </div>
                    <div>
                        <h3 class="text-base font-semibold text-gray-900 dark:text-white">Daftar Bahan & Sparepart</h3>
                        <p class="text-xs text-gray-500 dark:text-gray-400">{{ $production->productionMaterials->count() + $production->productionSpareparts->count() }} item · {{ $production->quantity ?? 1 }} unit produk</p>
                    </div>
                </div>
                <div class="flex items-center gap-3">
                    @if($canCheckReceived)
                        @php
                            // Hitung dari production relations langsung
                            $materialCount = $production->productionMaterials->count();
                            $sparepartCount = $production->productionSpareparts->count();
                            $totalItemsHeader = $materialCount + $sparepartCount;
                            
                            $receivedMaterials = $production->productionMaterials->where('is_received', true)->count();
                            $receivedSpareparts = $production->productionSpareparts->where('is_received', true)->count();
                            $receivedItemsHeader = $receivedMaterials + $receivedSpareparts;
                            
                            // Semua item dianggap available kecuali ada pengecekan stok khusus
                            $availableItemsHeader = $totalItemsHeader;
                        @endphp
                        <div class="flex items-center gap-2 px-3 py-1.5 bg-blue-50 border border-blue-200 rounded-lg">
                        <div class="flex items-center gap-1.5">
                                <div class="w-2 h-2 rounded-full {{ $receivedItemsHeader == $availableItemsHeader && $availableItemsHeader > 0 ? 'bg-emerald-500' : 'bg-amber-500' }} animate-pulse"></div>
                                <span id="receivedCounter" class="text-xs font-semibold text-blue-700">
                                    {{ $receivedItemsHeader }}/{{ $availableItemsHeader }} diterima
                        </span>
                    </div>
                        </div>
                        <form method="POST" action="{{ route('teknisi.productions.confirm-all-items', $production) }}" class="inline" id="confirmAllForm">
                            @csrf
                            @php
                                $allReceivedHeader = $receivedItemsHeader == $availableItemsHeader && $availableItemsHeader > 0;
                                $canConfirm = in_array($production->materials_status, ['preparing', 'pending']) || in_array($production->spareparts_status, ['preparing', 'pending']);
                            @endphp
                            @if($canConfirm || !$allReceivedHeader)
                            <button type="button" onclick="confirmAllItems()" id="confirmAllBtn" 
                                    class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors shadow-sm flex items-center gap-2"
                                    {{ $availableItemsHeader == 0 ? 'disabled' : '' }}>
                                <i class="fas fa-check"></i>
                                <span>Konfirmasi Semua</span>
                            </button>
                            @else
                            <span class="px-4 py-2 bg-emerald-100 text-emerald-700 rounded-lg text-sm font-medium flex items-center gap-2">
                                <i class="fas fa-check-circle"></i>
                                <span>Semua Diterima</span>
                        </span>
                    @endif
                        </form>
                    @endif
                    @if($canEdit)
                    <button onclick="openAddItemModal()" class="bg-blue-500 hover:bg-blue-600 text-white font-medium px-6 py-2.5 rounded-lg transition-colors duration-200 flex items-center gap-2">
                        <i class="fas fa-plus"></i>
                        <span>Tambah Item</span>
                    </button>
                    @else
                    <span class="text-xs text-gray-500 dark:text-gray-400 px-3 py-1.5">Planning sudah disubmit</span>
                    @endif
                </div>
            </div>
        </div>
        
        <!-- Table Content -->
        @php
            $allItems = collect();
            $orderQty = $production->quantity ?? 1;
            
            foreach($production->productionMaterials as $pm) {
                $totalNeeded = $pm->quantity * $orderQty;
                $currentStock = $pm->material->stock ?? 0;
                $stockStatus = 'available'; // available, insufficient, pending_purchase
                $stockStatusLabel = 'Tersedia';
                $stockStatusClass = 'bg-green-100 text-green-700';
                
                if ($currentStock < $totalNeeded) {
                    if ($currentStock == 0) {
                        $stockStatus = 'pending_purchase';
                        $stockStatusLabel = 'Perlu Pembelian';
                        $stockStatusClass = 'bg-red-100 text-red-700';
                    } else {
                        $stockStatus = 'insufficient';
                        $stockStatusLabel = 'Kurang';
                        $stockStatusClass = 'bg-amber-100 text-amber-700';
                    }
                }
                
                $allItems->push([
                    'id' => $pm->id,
                    'item_id' => $pm->material_id,
                    'type' => 'material',
                    'name' => $pm->material->name ?? 'N/A',
                    'quantity' => $pm->quantity,
                    'unit' => $pm->unit,
                    'unit_cost' => $pm->unit_cost,
                    'total_cost' => $pm->total_cost,
                    'stock' => $currentStock,
                    'total_needed' => $totalNeeded,
                    'stock_ok' => $currentStock >= $totalNeeded,
                    'stock_status' => $stockStatus,
                    'stock_status_label' => $stockStatusLabel,
                    'stock_status_class' => $stockStatusClass,
                    'is_received' => $pm->is_received ?? false,
                    'is_admin_suggested' => $pm->is_admin_suggested ?? false,
                    'revised_at' => $pm->revised_by_teknisi_at,
                    'is_additional' => $pm->is_additional ?? false,
                ]);
            }
            
            foreach($production->productionSpareparts as $ps) {
                $totalNeeded = $ps->quantity * $orderQty;
                $currentStock = $ps->sparepart->stock ?? 0;
                $stockStatus = 'available';
                $stockStatusLabel = 'Tersedia';
                $stockStatusClass = 'bg-green-100 text-green-700';
                
                if ($currentStock < $totalNeeded) {
                    if ($currentStock == 0) {
                        $stockStatus = 'pending_purchase';
                        $stockStatusLabel = 'Perlu Pembelian';
                        $stockStatusClass = 'bg-red-100 text-red-700';
                    } else {
                        $stockStatus = 'insufficient';
                        $stockStatusLabel = 'Kurang';
                        $stockStatusClass = 'bg-amber-100 text-amber-700';
                    }
                }
                
                $allItems->push([
                    'id' => $ps->id,
                    'item_id' => $ps->sparepart_id,
                    'type' => 'sparepart',
                    'name' => $ps->sparepart->name ?? 'N/A',
                    'quantity' => $ps->quantity,
                    'unit' => $ps->unit,
                    'unit_cost' => $ps->unit_cost,
                    'total_cost' => $ps->total_cost,
                    'stock' => $currentStock,
                    'total_needed' => $totalNeeded,
                    'stock_ok' => $currentStock >= $totalNeeded,
                    'stock_status' => $stockStatus,
                    'stock_status_label' => $stockStatusLabel,
                    'stock_status_class' => $stockStatusClass,
                    'is_received' => $ps->is_received ?? false,
                    'is_admin_suggested' => $ps->is_admin_suggested ?? false,
                    'revised_at' => $ps->revised_by_teknisi_at,
                    'is_additional' => $ps->is_additional ?? false,
                ]);
            }
            
            $totalCost = $allItems->sum('total_cost');
                            @endphp

        @if($allItems->count() > 0)
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 dark:bg-gray-700/50 border-b border-gray-200 dark:border-gray-600">
                    <tr>
                        <th class="px-4 py-3.5 text-left text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase">Nama Item</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase">Tipe</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase">Jumlah</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase">Satuan</th>
                        <th class="px-4 py-3.5 text-right text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase">Harga/Unit</th>
                        <th class="px-4 py-3.5 text-right text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase">Total</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase">Stok</th>
                        <th class="px-4 py-3.5 text-center text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase">Status Ketersediaan</th>
                        @if($canEdit)
                        <th class="px-4 py-3.5 text-center text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase">Aksi</th>
                        @elseif($canCheckReceived)
                        <th class="px-4 py-3.5 text-center text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase">Diterima</th>
                        @endif
                    </tr>
                </thead>
                <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700" id="itemsTableBody">
                    @foreach($allItems as $item)
                    <tr class="hover:bg-blue-50/50 dark:hover:bg-gray-700/80 transition-colors duration-200" 
                        id="item-{{ $item['type'] }}-{{ $item['id'] }}" 
                        data-type="{{ $item['type'] }}" 
                        data-id="{{ $item['id'] }}"
                        data-item-id="{{ $item['item_id'] }}"
                        data-name="{{ $item['name'] }}">
                        <td class="px-4 py-3.5">
                            <span class="font-medium text-gray-900 dark:text-white text-sm">{{ $item['name'] }}</span>
                            <div class="flex items-center gap-2 mt-0.5">
                                @if($item['is_admin_suggested'])
                                <span class="text-xs text-blue-600"><i class="fas fa-user-shield mr-0.5"></i>Admin</span>
                @endif
                                @if($item['revised_at'])
                                <span class="text-xs text-amber-600"><i class="fas fa-edit mr-0.5"></i>Direvisi</span>
                @endif
            </div>
                        </td>
                        <td class="px-4 py-3.5 text-center">
                            @if($item['type'] === 'material')
                            <span class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300">
                                <i class="fas fa-cube text-xs"></i> Bahan
                            </span>
                            @else
                            <span class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300">
                                <i class="fas fa-cog text-xs"></i> Sparepart
                            </span>
                            @endif
                        </td>
                        <td class="px-4 py-3.5 text-center font-medium text-gray-900 dark:text-white text-sm">{{ $item['quantity'] }}</td>
                        <td class="px-4 py-3.5 text-center text-gray-600 dark:text-gray-400 text-sm">{{ $item['unit'] }}</td>
                        <td class="px-4 py-3.5 text-right text-gray-600 dark:text-gray-400 text-sm">Rp {{ number_format($item['unit_cost'], 0, ',', '.') }}</td>
                        <td class="px-4 py-3.5 text-right font-semibold text-gray-900 dark:text-white text-sm">Rp {{ number_format($item['total_cost'], 0, ',', '.') }}</td>
                        <td class="px-4 py-3.5 text-center">
                            <div class="flex flex-col items-center gap-1">
                                <span class="text-sm font-medium text-gray-900 dark:text-white">{{ $item['stock'] }}</span>
                                <span class="text-xs text-gray-500">Butuh: {{ $item['total_needed'] }}</span>
                            </div>
                        </td>
                        <td class="px-4 py-3.5 text-center">
                            <span class="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-semibold rounded-md {{ $item['stock_status_class'] }}">
                                @if($item['stock_status'] === 'available')
                                <i class="fas fa-check-circle text-xs"></i>
                                @elseif($item['stock_status'] === 'insufficient')
                                <i class="fas fa-exclamation-triangle text-xs"></i>
                                @else
                                <i class="fas fa-times-circle text-xs"></i>
                                @endif
                                {{ $item['stock_status_label'] }}
                            </span>
                            @if($item['stock_status'] !== 'available')
                            <div class="mt-1 text-[10px] text-gray-500">
                                @if($item['stock_status'] === 'insufficient')
                                Kurang: {{ $item['total_needed'] - $item['stock'] }} {{ $item['unit'] }}
                                @else
                                Stok: 0
                                @endif
                            </div>
                            @endif
                        </td>
                        @if($canEdit)
                        <td class="px-4 py-3.5 text-center">
                            <div class="flex items-center justify-center gap-1">
                                @if($item['is_admin_suggested'])
                                <button type="button" onclick="reviseItem('{{ $item['type'] }}', {{ $item['id'] }})" 
                                        class="p-1.5 text-amber-600 hover:bg-amber-50 rounded" title="Revisi">
                                    <i class="fas fa-edit text-sm"></i>
                                </button>
                                @endif
                                <button type="button" onclick="deleteItem('{{ $item['type'] }}', {{ $item['id'] }})" 
                                        class="p-1.5 text-red-600 hover:bg-red-50 rounded" title="Hapus">
                                    <i class="fas fa-trash text-sm"></i>
                                </button>
                            </div>
                        </td>
                        @elseif($canCheckReceived)
                        <td class="px-4 py-3.5 text-center">
                            @if($item['stock_ok'])
                            <button type="button" 
                                    onclick="toggleItemReceived('{{ $item['type'] }}', {{ $item['id'] }}, '{{ $item['name'] }}')"
                                    class="item-check-btn w-5 h-5 rounded border-2 flex items-center justify-center transition-all duration-200 {{ $item['is_received'] ? 'bg-blue-500 border-blue-500' : 'bg-white border-gray-300 hover:border-blue-400' }}"
                                    data-type="{{ $item['type'] }}"
                                    data-id="{{ $item['id'] }}"
                                    data-name="{{ $item['name'] }}"
                                    data-received="{{ $item['is_received'] ? 'true' : 'false' }}">
                                @if($item['is_received'])
                                <i class="fas fa-check text-white text-xs"></i>
                                @endif
                </button>
                @else
                            <span class="w-5 h-5 rounded border-2 border-gray-200 bg-gray-100 flex items-center justify-center cursor-not-allowed" title="Stok tidak mencukupi">
                                <i class="fas fa-minus text-gray-300 text-xs"></i>
                                        </span>
                                    @endif
                                </td>
                                @endif
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
    </div>

        <!-- Alert untuk item tidak tersedia -->
        @php $unavailableItems = $allItems->where('stock_ok', false); @endphp
        @if($unavailableItems->count() > 0 && $canCheckReceived)
        <div class="px-5 py-3 bg-amber-50 dark:bg-amber-900/20 border-t border-amber-200 dark:border-amber-800">
            <div class="flex items-start gap-3">
                <div class="w-8 h-8 bg-amber-100 rounded-full flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-exclamation-triangle text-amber-600 text-sm"></i>
                </div>
                <div class="flex-1">
                    <p class="text-sm font-medium text-amber-800 dark:text-amber-200">
                        {{ $unavailableItems->count() }} item stok tidak mencukupi
                    </p>
                    <p class="text-xs text-amber-700 dark:text-amber-300 mt-0.5">
                        Item dengan stok kurang tidak dapat di-checklist. Hubungi Admin untuk melakukan pembelian.
                    </p>
                    <div class="flex flex-wrap gap-2 mt-2">
                        @foreach($unavailableItems->take(5) as $item)
                        <span class="inline-flex items-center gap-1 px-2 py-0.5 text-xs bg-amber-100 text-amber-800 rounded">
                            <i class="fas fa-{{ $item['type'] === 'material' ? 'cube' : 'cog' }}"></i>
                            {{ $item['name'] }} (stok: {{ $item['stock'] }})
                </span>
                        @endforeach
                        @if($unavailableItems->count() > 5)
                        <span class="text-xs text-amber-600">+{{ $unavailableItems->count() - 5 }} lainnya</span>
                        @endif
        </div>
                    </div>
                    </div>
                </div>
        @endif

        <!-- Footer Summary -->
        <div class="px-5 py-3.5 bg-gray-50 dark:bg-gray-700/50 border-t border-gray-200 dark:border-gray-600">
            <div class="flex items-center justify-between text-sm">
                <div class="flex flex-wrap items-center gap-3">
                    <span class="inline-flex items-center gap-1.5 text-emerald-700 dark:text-emerald-300">
                        <i class="fas fa-cube text-xs"></i> Bahan: Rp {{ number_format($production->total_material_cost ?? 0, 0, ',', '.') }}
                    </span>
                    <span class="inline-flex items-center gap-1.5 text-blue-700 dark:text-blue-300">
                        <i class="fas fa-cog text-xs"></i> Sparepart: Rp {{ number_format($production->total_sparepart_cost ?? 0, 0, ',', '.') }}
                    </span>
                </div>
                <div class="font-bold text-gray-900 dark:text-white">
                    Total: <span id="totalDirectCost">Rp {{ number_format($totalCost, 0, ',', '.') }}</span>
                </div>
            </div>
        </div>
        @else
        <div class="p-12 text-center" id="emptyState">
            <div class="w-16 h-16 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mx-auto mb-4">
                <i class="fas fa-inbox text-2xl text-gray-400 dark:text-gray-500"></i>
            </div>
            <p class="text-gray-500 dark:text-gray-400 font-medium">Belum ada bahan atau sparepart ditambahkan</p>
            <p class="text-sm text-gray-400 dark:text-gray-500 mt-1">Klik "Tambah Item" untuk menambahkan</p>
        </div>
        @endif
    </div>

    <!-- Request Item Baru Section -->
    @if($production->planning_status === 'planning' || ($production->planning_status === 'approved' && in_array($production->status, ['menunggu', 'dalam_proses'])))
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 mb-6 overflow-hidden">
        <div class="px-5 py-4 border-b border-gray-200 dark:border-gray-700 bg-amber-50 dark:bg-amber-900/20">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="p-2 bg-amber-100 dark:bg-amber-900/40 rounded-lg">
                        <i class="fas fa-plus-circle text-amber-600 dark:text-amber-400 text-sm"></i>
                    </div>
                    <div>
                        <h3 class="text-base font-semibold text-gray-900 dark:text-white">Request Item Baru</h3>
                        <p class="text-xs text-gray-500 dark:text-gray-400">Butuh bahan/sparepart yang tidak ada di sistem? Request ke Admin</p>
                    </div>
                </div>
                <button onclick="openRequestItemModal()" class="bg-orange-500 hover:bg-orange-600 text-white font-medium px-6 py-2.5 rounded-lg transition-colors duration-200 flex items-center gap-2">
                    <i class="fas fa-paper-plane"></i>
                    <span>Request Item</span>
                </button>
            </div>
        </div>
        
        <!-- Daftar Request -->
        @if($production->itemRequests && $production->itemRequests->count() > 0)
        <div class="p-5">
            <h4 class="text-sm font-semibold text-gray-900 dark:text-white mb-3">Request Anda:</h4>
            <div class="space-y-2">
                @foreach($production->itemRequests as $request)
                <div class="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-200 dark:border-gray-600">
                    <div class="flex items-center gap-3 flex-1">
                        <span class="w-8 h-8 rounded-full flex items-center justify-center {{ $request->item_type === 'material' ? 'bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400' : 'bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-400' }}">
                            <i class="fas fa-{{ $request->item_type === 'material' ? 'cube' : 'cog' }} text-sm"></i>
                        </span>
                        <div class="flex-1">
                            <p class="font-medium text-gray-900 dark:text-white text-sm">{{ $request->item_name_display }}</p>
                            <p class="text-xs text-gray-500 dark:text-gray-400">{{ $request->quantity }} {{ $request->unit }} • {{ Str::limit($request->reason, 40) }}</p>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <span class="px-2 py-1 text-xs font-medium rounded-full {{ $request->status_badge_class }}">
                            @if($request->status === 'pending')
                            <i class="fas fa-clock mr-0.5"></i> {{ $request->status_label }}
                            @elseif($request->status === 'approved')
                            <i class="fas fa-check-circle mr-0.5"></i> {{ $request->status_label }}
                            @elseif($request->status === 'rejected')
                            <i class="fas fa-times-circle mr-0.5"></i> {{ $request->status_label }}
                            @elseif($request->status === 'purchased')
                            <i class="fas fa-shopping-cart mr-0.5"></i> {{ $request->status_label }}
                            @elseif($request->status === 'sent')
                            <i class="fas fa-paper-plane mr-0.5 animate-pulse"></i> {{ $request->status_label }}
                            @elseif($request->status === 'received')
                            <i class="fas fa-check-double mr-0.5"></i> {{ $request->status_label }}
                            @endif
                        </span>
                        @if(in_array($request->status, ['sent', 'purchased']) && in_array($production->status, ['menunggu', 'dalam_proses']))
                        <form action="{{ route('teknisi.productions.confirm-item-request', [$production, $request->id]) }}" method="POST" class="inline">
                            @csrf
                            <button type="submit" class="bg-green-500 hover:bg-green-600 text-white text-xs font-medium px-3 py-1.5 rounded-lg transition-colors duration-200 flex items-center gap-1 shadow-md" title="Konfirmasi item sudah diterima">
                                <i class="fas fa-check-double"></i> 
                                <span>Diterima</span>
                            </button>
                        </form>
                        @endif
                    </div>
                </div>
                @endforeach
            </div>
        </div>
        @endif
        </div>
    @endif

    {{-- ============================================== --}}
    {{-- TABEL USULAN PERTAMA, KEDUA, KETIGA --}}
    {{-- ============================================== --}}
    @php
        $proposalGroups = $production->itemRequests->groupBy('proposal_number')->sortKeys();
    @endphp
    
    @if($proposalGroups->count() > 0)
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 mb-6 overflow-hidden">
        <div class="px-5 py-4 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-indigo-600 to-indigo-700">
            <div class="flex items-center gap-3">
                <div class="p-2 bg-white/20 rounded-lg">
                    <i class="fas fa-list-ol text-white text-sm"></i>
                </div>
                <div>
                    <h3 class="text-base font-semibold text-white">Usulan Bahan & Sparepart</h3>
                    <p class="text-xs text-indigo-100">Dikelompokkan berdasarkan usulan pertama, kedua, ketiga</p>
                </div>
            </div>
        </div>

        <div class="p-5 space-y-6">
            @foreach($proposalGroups as $proposalNumber => $requests)
            <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
                <div class="px-4 py-3 bg-gray-50 dark:bg-gray-700/50 border-b border-gray-200 dark:border-gray-700">
                    <h4 class="text-sm font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                        <span class="w-6 h-6 rounded-full bg-indigo-100 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-300 flex items-center justify-center text-xs font-bold">
                            {{ $proposalNumber ?? '1' }}
                        </span>
                        Usulan {{ $proposalNumber == 1 ? 'Pertama' : ($proposalNumber == 2 ? 'Kedua' : ($proposalNumber == 3 ? 'Ketiga' : 'Ke-' . $proposalNumber)) }}
                        <span class="ml-auto text-xs font-normal text-gray-500">
                            {{ $requests->count() }} item
                        </span>
                    </h4>
                </div>
                
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50 dark:bg-gray-700/50">
                            <tr class="text-xs uppercase">
                                <th class="px-4 py-2 text-left font-semibold text-gray-600 dark:text-gray-300">Item</th>
                                <th class="px-4 py-2 text-center font-semibold text-gray-600 dark:text-gray-300">Tipe</th>
                                <th class="px-4 py-2 text-center font-semibold text-gray-600 dark:text-gray-300">Jumlah</th>
                                <th class="px-4 py-2 text-center font-semibold text-gray-600 dark:text-gray-300">Satuan</th>
                                <th class="px-4 py-2 text-left font-semibold text-gray-600 dark:text-gray-300">Alasan</th>
                                <th class="px-4 py-2 text-center font-semibold text-gray-600 dark:text-gray-300">Status</th>
                                <th class="px-4 py-2 text-center font-semibold text-gray-600 dark:text-gray-300">Tanggal</th>
                                <th class="px-4 py-2 text-center font-semibold text-gray-600 dark:text-gray-300">Aksi</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200 dark:divide-gray-700 bg-white dark:bg-gray-800">
                            @foreach($requests as $request)
                            <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/30">
                                <td class="px-4 py-3">
                                    <div class="font-medium text-gray-900 dark:text-white text-sm">{{ $request->item_name_display }}</div>
                                    @if($request->is_new_item)
                                    <span class="text-xs text-blue-600"><i class="fas fa-star mr-0.5"></i>Item Baru</span>
                                    @endif
                                </td>
                                <td class="px-4 py-3 text-center">
                                    @if($request->item_type === 'material')
                                    <span class="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full bg-emerald-100 text-emerald-700">
                                        <i class="fas fa-cube"></i> Bahan
                                    </span>
                                    @else
                                    <span class="inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full bg-blue-100 text-blue-700">
                                        <i class="fas fa-cog"></i> Sparepart
                                    </span>
                                    @endif
                                </td>
                                <td class="px-4 py-3 text-center font-medium text-gray-900 dark:text-white">{{ $request->quantity }}</td>
                                <td class="px-4 py-3 text-center text-gray-600 dark:text-gray-400">{{ $request->unit }}</td>
                                <td class="px-4 py-3 text-sm text-gray-600 dark:text-gray-400">{{ Str::limit($request->reason, 50) }}</td>
                                <td class="px-4 py-3 text-center">
                                    <span class="inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-full {{ $request->status_badge_class }}">
                                        @if($request->status === 'pending')
                                        <i class="fas fa-clock text-[10px]"></i>
                                        @elseif($request->status === 'approved')
                                        <i class="fas fa-check-circle text-[10px]"></i>
                                        @elseif($request->status === 'rejected')
                                        <i class="fas fa-times-circle text-[10px]"></i>
                                        @elseif($request->status === 'purchased')
                                        <i class="fas fa-shopping-cart text-[10px]"></i>
                                        @elseif($request->status === 'sent')
                                        <i class="fas fa-paper-plane text-[10px] animate-pulse"></i>
                                        @elseif($request->status === 'received')
                                        <i class="fas fa-check-double text-[10px]"></i>
                                        @endif
                                        {{ $request->status_label }}
                                    </span>
                                    @if(in_array($request->status, ['sent', 'purchased']) && in_array($production->status, ['menunggu', 'dalam_proses']))
                                    <div class="mt-2">
                                        <form action="{{ route('teknisi.productions.confirm-item-request', [$production, $request->id]) }}" method="POST" class="inline">
                                            @csrf
                                            <button type="submit" class="w-full bg-green-500 hover:bg-green-600 text-white text-xs font-medium px-3 py-1.5 rounded-lg transition-colors duration-200 flex items-center justify-center gap-1 shadow-md" title="Konfirmasi item sudah diterima">
                                                <i class="fas fa-check-double"></i> 
                                                <span>Konfirmasi Diterima</span>
                                            </button>
                                        </form>
                                    </div>
                                    @endif
                                </td>
                                <td class="px-4 py-3 text-center text-xs text-gray-500">
                                    {{ $request->requested_at->format('d/m/Y H:i') }}
                                </td>
                                <td class="px-4 py-3 text-center">
                                    @if(in_array($request->status, ['sent', 'purchased']) && in_array($production->status, ['menunggu', 'dalam_proses']))
                                    <form action="{{ route('teknisi.productions.confirm-item-request', [$production, $request->id]) }}" method="POST" class="inline">
                                        @csrf
                                        <button type="submit" class="px-3 py-1.5 bg-green-500 hover:bg-green-600 text-white text-xs font-medium rounded-lg transition-colors duration-200 flex items-center gap-1 shadow-md" title="Konfirmasi item sudah diterima">
                                            <i class="fas fa-check-double text-xs"></i> 
                                            <span>Diterima</span>
                                        </button>
                                    </form>
                                    @elseif($request->status === 'received')
                                    <span class="px-2 py-1 text-xs font-medium rounded-full bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300">
                                        <i class="fas fa-check-circle text-xs"></i> Sudah Dikonfirmasi
                                    </span>
                                    @else
                                    <span class="text-xs text-gray-400">-</span>
                                    @endif
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
            @endforeach
        </div>
    </div>
    @endif

    <!-- Upah Jasa Section -->
    @if($production->planning_status === 'planning' || in_array($production->status, ['dalam_proses', 'selesai']))
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 mb-6 p-5" id="labor-cost-section">
        <div class="flex items-center gap-2 mb-4">
            <div class="p-2 bg-orange-100 dark:bg-orange-900/40 rounded-lg">
                <i class="fas fa-hand-holding-usd text-orange-600 dark:text-orange-400 text-sm"></i>
            </div>
            <h3 class="text-base font-semibold text-gray-900 dark:text-white">Upah Jasa</h3>
        </div>
        <form method="POST" action="{{ route('teknisi.productions.labor-cost', $production) }}" id="laborCostForm">
                @csrf
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                    <label class="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">Upah Jasa (Rp) <span class="text-red-500">*</span></label>
                    <input type="number" name="labor_cost" step="1000" min="0" required 
                               value="{{ $production->labor_cost ?? ($production->product->service_fee ?? '') }}"
                           class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-blue-500"
                           placeholder="Masukkan upah jasa">
                    @if($production->product->service_fee)
                    <p class="mt-1 text-xs text-gray-500">Default: Rp {{ number_format($production->product->service_fee, 0, ',', '.') }}</p>
                        @endif
                    </div>
                    <div>
                    <label class="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">Catatan (Opsional)</label>
                    <input type="text" name="notes" value="{{ $production->notes ?? '' }}"
                           class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-blue-500"
                           placeholder="Catatan perubahan">
                    </div>
                </div>
            <div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white font-medium px-6 py-2.5 rounded-lg transition-colors duration-200 flex items-center gap-2">
                    <i class="fas fa-save"></i>
                    <span>{{ $production->labor_cost ? 'Update Upah' : 'Simpan Upah' }}</span>
                </button>
            </div>
            </form>
    </div>
    @endif
    
    <!-- Cost Summary -->
    @php
        $laborTotal = $production->labor_cost ?? 0;
        $actualTotal = $directTotal + $laborTotal;
    @endphp
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
        @if($laborTotal > 0)
        <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="p-2 bg-orange-100 dark:bg-orange-900/40 rounded-lg">
                        <i class="fas fa-users text-orange-600 dark:text-orange-400 text-sm"></i>
                    </div>
                    <div>
                        <h3 class="text-sm font-semibold text-gray-900 dark:text-white">Biaya Tenaga Kerja</h3>
                        <p class="text-xs text-gray-500 dark:text-gray-400">Upah untuk {{ $production->quantity ?? 1 }} unit</p>
                    </div>
                </div>
                <div class="text-right">
                    <p class="text-lg font-bold text-orange-600 dark:text-orange-400">Rp {{ number_format($laborTotal, 0, ',', '.') }}</p>
                    <p class="text-xs text-gray-500 dark:text-gray-400">Per unit: Rp {{ number_format($laborTotal / max($production->quantity ?? 1, 1), 0, ',', '.') }}</p>
                </div>
            </div>
        </div>
        @endif

        <!-- Total Cost Summary -->
        <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="p-2 bg-indigo-100 dark:bg-indigo-900/40 rounded-lg">
                        <i class="fas fa-calculator text-indigo-600 dark:text-indigo-400 text-sm"></i>
                    </div>
                    <div>
                        <h3 class="text-sm font-semibold text-gray-900 dark:text-white">Total Biaya Produksi</h3>
                        <p class="text-xs text-gray-500 dark:text-gray-400">
                            Langsung: Rp {{ number_format($directTotal, 0, ',', '.') }}
                            @if($laborTotal > 0)
                                · Labor: Rp {{ number_format($laborTotal, 0, ',', '.') }}
                            @endif
                        </p>
                    </div>
                </div>
                <div class="text-right">
                    <p class="text-lg font-bold text-indigo-600 dark:text-indigo-400" id="totalActualCost">Rp {{ number_format($actualTotal, 0, ',', '.') }}</p>
                    <p class="text-xs text-gray-500 dark:text-gray-400">Per unit: Rp {{ number_format($actualTotal / max($production->quantity ?? 1, 1), 0, ',', '.') }}</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Action Buttons -->
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-5">
        <div class="flex flex-wrap items-center gap-3">
            @if($production->planning_status === 'planning')
            <button onclick="openSubmitModal()" class="bg-blue-500 hover:bg-blue-600 text-white font-medium px-6 py-2.5 rounded-lg transition-colors duration-200 flex items-center gap-2">
                <i class="fas fa-paper-plane"></i>
                <span>Submit Planning</span>
            </button>
            @elseif($production->planning_status === 'pending_approval')
            <span class="px-4 py-2.5 bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 rounded-lg text-sm font-medium flex items-center gap-2">
                <i class="fas fa-clock"></i>
                <span>Menunggu Approval</span>
            </span>
            @elseif($production->planning_status === 'approved' && $production->status === 'menunggu')
                @php
                    $materialsReady = $production->productionMaterials->count() == 0 || $production->materials_status === 'received';
                    $sparepartsReady = $production->productionSpareparts->count() == 0 || $production->spareparts_status === 'received';
                    $allReady = $materialsReady && $sparepartsReady;
                @endphp
                @if($allReady)
                <form method="POST" action="{{ route('teknisi.productions.start', $production) }}" class="inline" id="startProductionForm">
                    @csrf
                    <button type="button" onclick="startProduction()" class="bg-green-500 hover:bg-green-600 text-white font-medium px-6 py-2.5 rounded-lg transition-colors duration-200 flex items-center gap-2">
                        <i class="fas fa-play"></i>
                        <span>Mulai Produksi</span>
                    </button>
                </form>
                @else
                <span class="px-4 py-2.5 bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 rounded-lg text-sm font-medium flex items-center gap-2">
                    <i class="fas fa-info-circle"></i>
                    <span>Tunggu konfirmasi bahan diterima</span>
                </span>
                @endif
            @elseif($production->status === 'dalam_proses' && $production->completion_status !== 'pending_approval')
            <button onclick="openCompletionModal()" class="bg-purple-500 hover:bg-purple-600 text-white font-medium px-6 py-2.5 rounded-lg transition-colors duration-200 flex items-center gap-2">
                <i class="fas fa-check"></i>
                <span>Submit Completion</span>
            </button>
            @elseif($production->completion_status === 'pending_approval')
            <span class="px-4 py-2.5 bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 rounded-lg text-sm font-medium flex items-center gap-2">
                <i class="fas fa-clock"></i>
                <span>Menunggu Approval Completion</span>
            </span>
            @endif
            
            <a href="{{ route('teknisi.productions.index') }}" class="text-gray-600 dark:text-gray-300 border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 font-medium px-6 py-2.5 rounded-lg transition-colors duration-200 flex items-center gap-2">
                <i class="fas fa-arrow-left"></i>
                <span>Kembali</span>
            </a>
        </div>
    </div>
</div>

<!-- Add Item Modal (Unified) -->
<div id="addItemModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 hidden">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-lg w-full overflow-hidden">
            <div class="px-6 py-4 bg-slate-700 text-white">
                <div class="flex justify-between items-center">
                    <h3 class="text-lg font-semibold flex items-center gap-2">
                        <i class="fas fa-plus-circle"></i> Tambah Item
                            </h3>
                    <button onclick="closeAddItemModal()" class="text-white/80 hover:text-white p-1">
                        <i class="fas fa-times"></i>
                    </button>
                        </div>
                    </div>
            <form id="addItemForm" class="p-6">
                @csrf
                <div class="space-y-4">
                    <!-- Item Type Selection -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Tipe Item <span class="text-red-500">*</span></label>
                        <div class="grid grid-cols-2 gap-3">
                            <label id="labelMaterial" class="item-type-label flex items-center justify-center p-4 border-2 rounded-xl cursor-pointer transition-all duration-200 border-emerald-500 bg-emerald-50 shadow-md" onclick="selectItemType('material')">
                                <input type="radio" name="item_type" value="material" class="sr-only" checked>
                                <div class="flex flex-col items-center gap-2">
                                    <div id="iconMaterial" class="w-12 h-12 rounded-full flex items-center justify-center" style="background-color: #10b981;">
                                        <i class="fas fa-cube" style="color: #ffffff; font-size: 1.25rem;"></i>
                    </div>
                                    <span class="font-semibold text-emerald-700">Bahan</span>
                </div>
                            </label>
                            <label id="labelSparepart" class="item-type-label flex items-center justify-center p-4 border-2 rounded-xl cursor-pointer transition-all duration-200 border-gray-200 bg-white hover:border-blue-300 hover:bg-blue-50/50" onclick="selectItemType('sparepart')">
                                <input type="radio" name="item_type" value="sparepart" class="sr-only">
                                <div class="flex flex-col items-center gap-2">
                                    <div id="iconSparepart" class="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center">
                                        <i class="fas fa-cog text-gray-400 text-xl"></i>
            </div>
                                    <span class="font-semibold text-gray-600">Sparepart</span>
                            </div>
                            </label>
                        </div>
                        </div>

                    <!-- Item Select -->
                        <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Pilih Item <span class="text-red-500">*</span></label>
                        <select name="item_id" id="itemSelect" required class="w-full px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-slate-500">
                            <option value="">-- Pilih Item --</option>
                            </select>
                        </div>

                    <!-- Quantity & Unit -->
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Jumlah <span class="text-red-500">*</span></label>
                            <input type="number" name="quantity" id="itemQuantity" step="1" min="1" required 
                                   class="w-full px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-slate-500" placeholder="0">
                            </div>
                            <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Satuan <span class="text-red-500">*</span></label>
                            <input type="text" name="unit" id="itemUnit" required 
                                   class="w-full px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-slate-500" placeholder="kg, pcs, meter">
                            </div>
                        </div>

                    <!-- Unit Cost -->
                        <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Harga per Unit (Rp) <span class="text-red-500">*</span></label>
                        <input type="text" name="unit_cost" id="itemUnitCost" required 
                               class="w-full px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-slate-500" placeholder="Rp 0">
                        </div>

                    <div id="addItemError" class="hidden bg-red-50 border border-red-200 text-red-700 p-3 rounded-lg text-sm"></div>
                </div>

                <div class="flex justify-end gap-3 mt-6 pt-4 border-t border-gray-200">
                    <button type="button" onclick="closeAddItemModal()" class="px-5 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-semibold transition-colors border border-gray-300">Batal</button>
                    <button type="submit" id="addItemSubmitBtn" class="px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-semibold transition-colors shadow-md">
                        <span id="addItemSubmitText"><i class="fas fa-plus mr-1"></i> Tambah Item</span>
                        <span id="addItemSubmitLoader" class="hidden"><i class="fas fa-spinner fa-spin mr-1"></i> Memproses...</span>
                            </button>
                    </div>
                </form>
                    </div>
    </div>
</div>

<!-- Submit Planning Modal -->
<div id="submitModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 hidden">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg max-w-md w-full overflow-hidden">
            <div class="px-6 py-4 bg-blue-600 text-white">
                <div class="flex justify-between items-center">
                    <h3 class="text-lg font-semibold"><i class="fas fa-paper-plane mr-2"></i>Submit Planning</h3>
                    <button onclick="closeSubmitModal()" class="text-white/80 hover:text-white"><i class="fas fa-times"></i></button>
                        </div>
                        </div>
            <div class="p-6">
                <div class="mb-4 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                    <h4 class="font-semibold text-gray-900 dark:text-white mb-2">Ringkasan</h4>
                    <div class="space-y-1 text-sm text-gray-600 dark:text-gray-300">
                        <p><i class="fas fa-cube mr-1"></i> Bahan: <span id="modalMaterialCount">{{ $production->productionMaterials->count() }}</span> item</p>
                        <p><i class="fas fa-cog mr-1"></i> Sparepart: <span id="modalSparepartCount">{{ $production->productionSpareparts->count() }}</span> item</p>
                        <p class="font-semibold text-gray-900 dark:text-white"><i class="fas fa-dollar-sign mr-1"></i> Total: <span id="modalTotalCost">Rp {{ number_format($totalCost, 0, ',', '.') }}</span></p>
                    </div>
                    </div>
                <form method="POST" action="{{ route('teknisi.productions.submit', $production) }}">
                    @csrf
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Catatan (Opsional)</label>
                        <textarea name="notes" rows="3" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white" placeholder="Catatan untuk supervisor..."></textarea>
                </div>
                    <div class="flex justify-end gap-3">
                        <button type="button" onclick="closeSubmitModal()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg font-medium">Batal</button>
                        <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium"><i class="fas fa-paper-plane mr-1"></i> Submit</button>
            </div>
                </form>
                            </div>
                        </div>
                        </div>
                            </div>

<!-- Completion Modal -->
<div id="completionModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 hidden">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg max-w-md w-full overflow-hidden">
            <div class="px-6 py-4 bg-purple-600 text-white">
                <div class="flex justify-between items-center">
                    <h3 class="text-lg font-semibold"><i class="fas fa-check-circle mr-2"></i>Submit Completion</h3>
                    <button onclick="closeCompletionModal()" class="text-white/80 hover:text-white"><i class="fas fa-times"></i></button>
                            </div>
                        </div>
            <div class="p-6">
                @if(!$production->labor_cost || $production->labor_cost <= 0)
                <div class="mb-4 p-3 bg-amber-50 border border-amber-200 rounded-lg">
                    <p class="text-sm text-amber-800"><i class="fas fa-exclamation-triangle mr-1"></i> Labor cost belum diisi. Disarankan untuk mengisi terlebih dahulu.</p>
                        </div>
                @endif
                <form method="POST" action="{{ route('teknisi.productions.submit-completion', $production) }}">
                    @csrf
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Catatan (Opsional)</label>
                        <textarea name="notes" rows="3" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white" placeholder="Catatan tambahan..."></textarea>
                        </div>
                    <div class="flex justify-end gap-3">
                        <button type="button" onclick="closeCompletionModal()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg font-medium">Batal</button>
                        <button type="submit" class="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg font-medium"><i class="fas fa-paper-plane mr-1"></i> Submit</button>
                    </div>
                </form>
                    </div>
        </div>
    </div>
</div>

<!-- Request Item Baru Modal -->
<div id="requestItemModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 hidden">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-2xl w-full overflow-hidden">
            <div class="px-6 py-3 bg-orange-500 text-white">
                <div class="flex justify-between items-center">
                    <h3 class="text-base font-semibold flex items-center gap-2">
                        <i class="fas fa-plus-circle"></i> Request Item Baru
                    </h3>
                    <button onclick="closeRequestItemModal()" class="text-white/80 hover:text-white p-1">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <form method="POST" action="{{ route('teknisi.productions.request-item', $production) }}" class="p-5" id="requestItemForm">
                @csrf
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- Left Column -->
                    <div class="space-y-4">
                        <!-- Item Type -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Tipe Item <span class="text-red-500">*</span></label>
                            <div class="grid grid-cols-2 gap-2">
                                <label id="reqLabelMaterial" onclick="selectRequestType('material')" 
                                       class="req-type-label flex items-center justify-center p-3 border-2 rounded-lg cursor-pointer transition-all border-emerald-500 bg-white shadow-sm">
                                    <input type="radio" name="item_type" value="material" class="sr-only" checked>
                                    <div class="flex items-center gap-2">
                                        <div id="reqIconMaterial" class="w-8 h-8 rounded-full flex items-center justify-center" style="background-color: #10b981;">
                                            <i class="fas fa-cube" style="color: white; font-size: 0.875rem;"></i>
                        </div>
                                        <span class="font-semibold text-emerald-600">Bahan</span>
                        </div>
                                </label>
                                <label id="reqLabelSparepart" onclick="selectRequestType('sparepart')" 
                                       class="req-type-label flex items-center justify-center p-3 border-2 rounded-lg cursor-pointer transition-all border-gray-200 bg-white hover:border-blue-400 hover:bg-blue-50 group">
                                    <input type="radio" name="item_type" value="sparepart" class="sr-only">
                                    <div class="flex items-center gap-2">
                                        <div id="reqIconSparepart" class="w-8 h-8 rounded-full flex items-center justify-center bg-gray-200 group-hover:bg-blue-500 transition-colors">
                                            <i class="fas fa-cog text-gray-500 group-hover:text-white text-sm transition-colors"></i>
                        </div>
                                        <span class="font-semibold text-gray-600 group-hover:text-blue-700 transition-colors">Sparepart</span>
                                    </div>
                                </label>
                    </div>
                </div>

                        <!-- Pilih Item dari Sistem atau Item Baru -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Sumber Item <span class="text-red-500">*</span></label>
                            <div class="grid grid-cols-2 gap-2">
                                <label onclick="toggleRequestItemSource('existing')" 
                                       class="flex items-center justify-center p-2.5 border-2 rounded-lg cursor-pointer transition-all border-blue-500 bg-blue-50 shadow-sm">
                                    <input type="radio" name="item_source" value="existing" class="sr-only" checked id="itemSourceExisting">
                                    <span class="text-xs font-semibold text-blue-700">Dari Sistem</span>
                                </label>
                                <label onclick="toggleRequestItemSource('new')" 
                                       class="flex items-center justify-center p-2.5 border-2 rounded-lg cursor-pointer transition-all border-gray-200 bg-white hover:border-orange-400 hover:bg-orange-50">
                                    <input type="radio" name="item_source" value="new" class="sr-only" id="itemSourceNew">
                                    <span class="text-xs font-semibold text-gray-600">Item Baru</span>
                                </label>
                            </div>
                        </div>

                        <!-- Pilih Item dari Sistem (Existing) -->
                        <div id="existingItemSection">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Pilih Item <span class="text-red-500">*</span></label>
                            <select name="existing_item_id" id="existingItemSelect" 
                                   class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-orange-500 text-sm">
                                <option value="">-- Pilih Item --</option>
                            </select>
                            <input type="hidden" name="material_id" id="hiddenMaterialId">
                            <input type="hidden" name="sparepart_id" id="hiddenSparepartId">
                        </div>

                        <!-- Input Item Baru -->
                        <div id="newItemSection" class="hidden">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Nama Item Baru <span class="text-red-500">*</span></label>
                            <input type="text" name="item_name" id="newItemName"
                                   class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-orange-500 text-sm" 
                                   placeholder="Contoh: Bearing SKF 6205">
                        </div>

                        <!-- Quantity & Unit -->
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Jumlah Tambahan <span class="text-red-500">*</span></label>
                                <input type="number" name="quantity" id="requestQuantity" step="0.01" min="0.01" required 
                                       class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-orange-500 text-sm" 
                                       placeholder="0">
                                <p class="text-xs text-gray-500 mt-1" id="quantityHelper">Jumlah tambahan yang dibutuhkan</p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Satuan <span class="text-red-500">*</span></label>
                                <input type="text" name="unit" id="requestUnit" required 
                                       class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-orange-500 text-sm" 
                                       placeholder="pcs, kg, meter">
                            </div>
                        </div>
                    </div>

                    <!-- Right Column -->
                    <div class="space-y-4">
                        <!-- Info Box (Dynamic) -->
                        <div id="requestInfoBox" class="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                            <p class="text-xs text-blue-800">
                                <i class="fas fa-info-circle mr-1"></i>
                                <span id="infoBoxText">Pilih item dari sistem untuk menambah jumlah kebutuhan. Admin akan memproses request ini.</span>
                            </p>
                        </div>

                        <!-- Estimated Price -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Estimasi Harga/Unit (Opsional)</label>
                            <input type="number" name="estimated_price" step="1000" min="0" 
                                   class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-orange-500 text-sm" 
                                   placeholder="Rp 0">
                        </div>

                        <!-- Reason -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Alasan Request <span class="text-red-500">*</span></label>
                            <textarea name="reason" rows="3" required
                                      class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-orange-500 text-sm" 
                                      placeholder="Jelaskan mengapa item ini dibutuhkan..."></textarea>
                        </div>
                    </div>
            </div>

                <div class="flex justify-end gap-3 mt-5 pt-4 border-t border-gray-200">
                    <button type="button" onclick="closeRequestItemModal()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors border border-gray-300 text-sm">Batal</button>
                    <button type="submit" class="px-5 py-2 bg-orange-500 hover:bg-orange-600 text-white rounded-lg font-medium transition-colors shadow-md text-sm">
                        <i class="fas fa-paper-plane mr-1"></i> Kirim Request
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@php
    $materialsJson = $materials->map(function($m) {
        return ['id' => $m->id, 'name' => $m->name, 'unit' => $m->unit, 'price' => $m->price, 'stock' => $m->stock];
    })->values();
    $sparepartsJson = $spareparts->map(function($s) {
        return ['id' => $s->id, 'name' => $s->name, 'unit' => $s->unit, 'price' => $s->price, 'stock' => $s->stock];
    })->values();
    $usedMaterialIds = $production->productionMaterials->pluck('material_id')->values();
    $usedSparepartIds = $production->productionSpareparts->pluck('sparepart_id')->values();
    @endphp
    
@push('scripts')
<script>
const productionId = {{ $production->id }};
const canEdit = {{ $production->planning_status === 'planning' ? 'true' : 'false' }};
const orderQty = {{ $production->quantity ?? 1 }};
const laborCost = {{ $production->labor_cost ?? 0 }};

// Data untuk dropdown
const materialsData = @json($materialsJson);
const sparepartsData = @json($sparepartsJson);

// Track used items - konversi array ke Set dengan benar
let usedMaterials = new Set(@json($usedMaterialIds).map(id => parseInt(id)));
let usedSpareparts = new Set(@json($usedSparepartIds).map(id => parseInt(id)));

// Format helpers
function formatRupiah(num) {
    if (!num && num !== 0) return 'Rp 0';
    // Konversi ke integer (bulatkan jika ada desimal)
    let number = typeof num === 'string' ? parseFloat(num) : num;
    number = Math.round(number);
    if (isNaN(number)) return 'Rp 0';
    return 'Rp ' + number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
}

function unformatRupiah(str) {
    if (!str) return 0;
    // Hapus "Rp", spasi, dan titik pemisah ribuan
    const cleaned = str.toString().replace(/[Rp\s.]/g, '');
    return parseInt(cleaned) || 0;
}

function formatNumber(num) {
    return new Intl.NumberFormat('id-ID').format(num || 0);
}

// Toast notification clean & minimal
function showToast(message, type = 'success') {
    const styles = {
        success: { border: '#10b981', bg: '#ecfdf5', text: '#065f46', icon: 'check-circle', iconColor: '#10b981' },
        error: { border: '#ef4444', bg: '#fef2f2', text: '#991b1b', icon: 'times-circle', iconColor: '#ef4444' },
        warning: { border: '#f59e0b', bg: '#fffbeb', text: '#92400e', icon: 'exclamation-triangle', iconColor: '#f59e0b' },
        info: { border: '#3b82f6', bg: '#eff6ff', text: '#1e40af', icon: 'info-circle', iconColor: '#3b82f6' }
    };
    const s = styles[type] || styles.success;
    
    const toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed; top: 20px; right: 20px; z-index: 9999;
        display: flex; align-items: center; gap: 12px;
        padding: 14px 20px; border-radius: 12px;
        background: ${s.bg}; border-left: 4px solid ${s.border};
        box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        transform: translateX(120%); transition: transform 0.3s ease;
    `;
    toast.innerHTML = `
        <i class="fas fa-${s.icon}" style="color: ${s.iconColor}; font-size: 18px;"></i>
        <span style="color: ${s.text}; font-weight: 500; font-size: 14px;">${message}</span>
        <button onclick="this.parentElement.remove()" style="margin-left: 8px; color: ${s.text}; opacity: 0.5; cursor: pointer; background: none; border: none;">
            <i class="fas fa-times"></i>
        </button>
    `;
    document.body.appendChild(toast);
    
    requestAnimationFrame(() => { toast.style.transform = 'translateX(0)'; });
    setTimeout(() => {
        toast.style.transform = 'translateX(120%)';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// Confirm dialog untuk delete - clean style dengan warna merah
function showConfirmDialog(title, message, type = 'danger') {
    return new Promise((resolve) => {
        const overlay = document.createElement('div');
        overlay.style.cssText = `
            position: fixed; inset: 0; z-index: 9999;
            background: rgba(0,0,0,0.4); backdrop-filter: blur(4px);
            display: flex; align-items: center; justify-content: center; padding: 16px;
        `;
        overlay.innerHTML = `
            <div id="confirmBox" style="
                background: white; border-radius: 16px; max-width: 360px; width: 100%;
                box-shadow: 0 20px 60px rgba(0,0,0,0.2);
                transform: scale(0.9); opacity: 0; transition: all 0.2s ease;
            ">
                <div style="padding: 28px; text-align: center;">
                    <div style="
                        width: 56px; height: 56px; margin: 0 auto 16px;
                        background: #fef2f2; border-radius: 50%;
                        display: flex; align-items: center; justify-content: center;
                    ">
                        <i class="fas fa-trash-alt" style="color: #ef4444; font-size: 22px;"></i>
                </div>
                    <h3 style="font-size: 18px; font-weight: 700; color: #111827; margin-bottom: 8px;">${title}</h3>
                    <p style="font-size: 14px; color: #6b7280; line-height: 1.5;">${message}</p>
                    </div>
                <div style="display: flex; border-top: 1px solid #f3f4f6;">
                    <button id="confirmCancel" style="
                        flex: 1; padding: 14px; font-size: 14px; font-weight: 600;
                        color: #374151; background: none; border: none; cursor: pointer;
                        transition: background 0.2s;
                    " onmouseover="this.style.background='#f9fafb'" onmouseout="this.style.background='none'">Batal</button>
                    <button id="confirmOk" style="
                        flex: 1; padding: 14px; font-size: 14px; font-weight: 600;
                        color: white; background: #ef4444; border: none; cursor: pointer;
                        border-radius: 0 0 16px 0; transition: background 0.2s;
                    " onmouseover="this.style.background='#dc2626'" onmouseout="this.style.background='#ef4444'">Ya, Hapus</button>
                    </div>
        </div>
    `;
        document.body.appendChild(overlay);
        
        requestAnimationFrame(() => {
            const box = overlay.querySelector('#confirmBox');
            box.style.transform = 'scale(1)';
            box.style.opacity = '1';
        });
        
        const cleanup = (result) => {
            const box = overlay.querySelector('#confirmBox');
            box.style.transform = 'scale(0.9)';
            box.style.opacity = '0';
            setTimeout(() => { overlay.remove(); resolve(result); }, 200);
        };
        
        overlay.querySelector('#confirmCancel').onclick = () => cleanup(false);
        overlay.querySelector('#confirmOk').onclick = () => cleanup(true);
        overlay.onclick = (e) => { if (e.target === overlay) cleanup(false); };
    });
}

// Legacy notification (untuk kompatibilitas)
function showNotification(message, type = 'success') {
    showToast(message, type);
}

// Modal functions
function openAddItemModal() {
    document.getElementById('addItemModal').classList.remove('hidden');
    document.getElementById('addItemForm').reset();
    document.getElementById('addItemError').classList.add('hidden');
    // Reset ke material sebagai default
    selectItemType('material');
    updateItemOptions();
}

// Select item type dengan visual feedback
function selectItemType(type) {
    const labelMaterial = document.getElementById('labelMaterial');
    const labelSparepart = document.getElementById('labelSparepart');
    const iconMaterial = document.getElementById('iconMaterial');
    const iconSparepart = document.getElementById('iconSparepart');
    const radioMaterial = document.querySelector('input[name="item_type"][value="material"]');
    const radioSparepart = document.querySelector('input[name="item_type"][value="sparepart"]');
    
    if (type === 'material') {
        radioMaterial.checked = true;
        // Active state untuk Material
        labelMaterial.className = 'item-type-label flex items-center justify-center p-4 border-2 rounded-xl cursor-pointer transition-all duration-200 border-emerald-500 bg-emerald-50 shadow-md';
        iconMaterial.className = 'w-12 h-12 rounded-full flex items-center justify-center';
        iconMaterial.style.backgroundColor = '#10b981';
        iconMaterial.querySelector('i').className = 'fas fa-cube';
        iconMaterial.querySelector('i').style.color = '#ffffff';
        labelMaterial.querySelector('span').className = 'font-semibold text-emerald-700';
        // Inactive state untuk Sparepart
        labelSparepart.className = 'item-type-label flex items-center justify-center p-4 border-2 rounded-xl cursor-pointer transition-all duration-200 border-gray-200 bg-white hover:border-blue-300 hover:bg-blue-50/50';
        iconSparepart.className = 'w-12 h-12 rounded-full flex items-center justify-center';
        iconSparepart.style.backgroundColor = '#f3f4f6';
        iconSparepart.querySelector('i').className = 'fas fa-cog';
        iconSparepart.querySelector('i').style.color = '#9ca3af';
        labelSparepart.querySelector('span').className = 'font-semibold text-gray-600';
    } else {
        radioSparepart.checked = true;
        // Active state untuk Sparepart
        labelSparepart.className = 'item-type-label flex items-center justify-center p-4 border-2 rounded-xl cursor-pointer transition-all duration-200 border-blue-500 bg-blue-50 shadow-md';
        iconSparepart.className = 'w-12 h-12 rounded-full flex items-center justify-center';
        iconSparepart.style.backgroundColor = '#3b82f6';
        iconSparepart.querySelector('i').className = 'fas fa-cog';
        iconSparepart.querySelector('i').style.color = '#ffffff';
        labelSparepart.querySelector('span').className = 'font-semibold text-blue-700';
        // Inactive state untuk Material
        labelMaterial.className = 'item-type-label flex items-center justify-center p-4 border-2 rounded-xl cursor-pointer transition-all duration-200 border-gray-200 bg-white hover:border-emerald-300 hover:bg-emerald-50/50';
        iconMaterial.className = 'w-12 h-12 rounded-full flex items-center justify-center';
        iconMaterial.style.backgroundColor = '#f3f4f6';
        iconMaterial.querySelector('i').className = 'fas fa-cube';
        iconMaterial.querySelector('i').style.color = '#9ca3af';
        labelMaterial.querySelector('span').className = 'font-semibold text-gray-600';
    }
    
    updateItemOptions();
}

function closeAddItemModal() {
    document.getElementById('addItemModal').classList.add('hidden');
}

function openSubmitModal() {
    updateModalSummary();
    document.getElementById('submitModal').classList.remove('hidden');
}

function closeSubmitModal() {
    document.getElementById('submitModal').classList.add('hidden');
}

function openCompletionModal() {
    document.getElementById('completionModal').classList.remove('hidden');
}

function closeCompletionModal() {
    document.getElementById('completionModal').classList.add('hidden');
}

function openRequestItemModal() {
    document.getElementById('requestItemModal').classList.remove('hidden');
    selectRequestType('material'); // Default ke material
}

function closeRequestItemModal() {
    document.getElementById('requestItemModal').classList.add('hidden');
}

function selectRequestType(type) {
    const labelMaterial = document.getElementById('reqLabelMaterial');
    const labelSparepart = document.getElementById('reqLabelSparepart');
    const iconMaterial = document.getElementById('reqIconMaterial');
    const iconSparepart = document.getElementById('reqIconSparepart');
    const radioMaterial = document.querySelector('#requestItemModal input[value="material"]');
    const radioSparepart = document.querySelector('#requestItemModal input[value="sparepart"]');
    
    if (type === 'material') {
        radioMaterial.checked = true;
        // Active - Material (hijau)
        labelMaterial.className = 'req-type-label flex items-center justify-center p-3 border-2 rounded-lg cursor-pointer transition-all border-emerald-500 bg-white shadow-sm';
        iconMaterial.className = 'w-8 h-8 rounded-full flex items-center justify-center';
        iconMaterial.style.backgroundColor = '#10b981';
        iconMaterial.innerHTML = '<i class="fas fa-cube" style="color: white; font-size: 0.875rem;"></i>';
        labelMaterial.querySelector('span').className = 'font-semibold text-emerald-600';
        // Inactive - Sparepart
        labelSparepart.className = 'req-type-label flex items-center justify-center p-3 border-2 rounded-lg cursor-pointer transition-all border-gray-200 bg-white hover:border-blue-400 hover:bg-blue-50 group';
        iconSparepart.className = 'w-8 h-8 rounded-full flex items-center justify-center bg-gray-200 group-hover:bg-blue-500 transition-colors';
        iconSparepart.style.backgroundColor = '';
        iconSparepart.innerHTML = '<i class="fas fa-cog text-gray-500 group-hover:text-white text-sm"></i>';
        labelSparepart.querySelector('span').className = 'font-semibold text-gray-600 group-hover:text-blue-600';
    } else {
        radioSparepart.checked = true;
        // Active - Sparepart (biru)
        labelSparepart.className = 'req-type-label flex items-center justify-center p-3 border-2 rounded-lg cursor-pointer transition-all border-blue-500 bg-white shadow-sm';
        iconSparepart.className = 'w-8 h-8 rounded-full flex items-center justify-center';
        iconSparepart.style.backgroundColor = '#3b82f6';
        iconSparepart.innerHTML = '<i class="fas fa-cog" style="color: white; font-size: 0.875rem;"></i>';
        labelSparepart.querySelector('span').className = 'font-semibold text-blue-600';
        // Inactive - Material
        labelMaterial.className = 'req-type-label flex items-center justify-center p-3 border-2 rounded-lg cursor-pointer transition-all border-gray-200 bg-white hover:border-emerald-400 hover:bg-emerald-50 group';
        iconMaterial.className = 'w-8 h-8 rounded-full flex items-center justify-center bg-gray-200 group-hover:bg-emerald-500 transition-colors';
        iconMaterial.style.backgroundColor = '';
        iconMaterial.innerHTML = '<i class="fas fa-cube text-gray-500 group-hover:text-white text-sm"></i>';
        labelMaterial.querySelector('span').className = 'font-semibold text-gray-600 group-hover:text-emerald-600';
    }
    
    // Update dropdown items
    updateRequestItemOptions();
}

// Toggle antara item existing dan item baru
function toggleRequestItemSource(source) {
    const existingSection = document.getElementById('existingItemSection');
    const newItemSection = document.getElementById('newItemSection');
    const existingSelect = document.getElementById('existingItemSelect');
    const newItemName = document.getElementById('newItemName');
    const infoBox = document.getElementById('requestInfoBox');
    const infoBoxText = document.getElementById('infoBoxText');
    
    if (source === 'existing') {
        existingSection.classList.remove('hidden');
        newItemSection.classList.add('hidden');
        existingSelect.required = true;
        newItemName.required = false;
        newItemName.value = '';
        infoBox.className = 'p-3 bg-blue-50 border border-blue-200 rounded-lg';
        infoBoxText.innerHTML = '<i class="fas fa-info-circle mr-1"></i> Pilih item dari sistem untuk menambah jumlah kebutuhan. Admin akan memproses request ini.';
    } else {
        existingSection.classList.add('hidden');
        newItemSection.classList.remove('hidden');
        existingSelect.required = false;
        newItemName.required = true;
        existingSelect.value = '';
        document.getElementById('hiddenMaterialId').value = '';
        document.getElementById('hiddenSparepartId').value = '';
        infoBox.className = 'p-3 bg-orange-50 border border-orange-200 rounded-lg';
        infoBoxText.innerHTML = '<i class="fas fa-info-circle mr-1"></i> Request item yang <strong>tidak ada di sistem</strong>. Admin akan memproses dan menambahkan ke stok.';
    }
}

// Update dropdown items berdasarkan tipe
function updateRequestItemOptions() {
    const itemType = document.querySelector('#requestItemModal input[name="item_type"]:checked').value;
    const select = document.getElementById('existingItemSelect');
    const data = itemType === 'material' ? materialsData : sparepartsData;
    
    select.innerHTML = '<option value="">-- Pilih Item --</option>';
    data.forEach(item => {
        const opt = document.createElement('option');
        opt.value = item.id;
        opt.textContent = `${item.name} (Stok: ${item.stock} ${item.unit || ''})`;
        opt.dataset.unit = item.unit || '';
        opt.dataset.price = item.price || 0;
        select.appendChild(opt);
    });
    
    // Reset hidden fields
    document.getElementById('hiddenMaterialId').value = '';
    document.getElementById('hiddenSparepartId').value = '';
    document.getElementById('requestUnit').value = '';
}

// Handle change pada existing item select
document.addEventListener('DOMContentLoaded', function() {
    const existingSelect = document.getElementById('existingItemSelect');
    if (existingSelect) {
        existingSelect.addEventListener('change', function() {
            const opt = this.options[this.selectedIndex];
            if (opt && opt.value) {
                const itemType = document.querySelector('#requestItemModal input[name="item_type"]:checked').value;
                const unitInput = document.getElementById('requestUnit');
                
                if (itemType === 'material') {
                    document.getElementById('hiddenMaterialId').value = opt.value;
                    document.getElementById('hiddenSparepartId').value = '';
                } else {
                    document.getElementById('hiddenSparepartId').value = opt.value;
                    document.getElementById('hiddenMaterialId').value = '';
                }
                
                if (unitInput) {
                    unitInput.value = opt.dataset.unit || '';
                }
            }
        });
    }
    
    // Handle form submit untuk validasi
    const requestForm = document.getElementById('requestItemForm');
    if (requestForm) {
        requestForm.addEventListener('submit', function(e) {
            const itemSource = document.querySelector('input[name="item_source"]:checked').value;
            const existingSelect = document.getElementById('existingItemSelect');
            const newItemName = document.getElementById('newItemName');
            
            if (itemSource === 'existing' && !existingSelect.value) {
                e.preventDefault();
                alert('Pilih item dari sistem atau pilih "Item Baru"');
                return false;
            }
            
            if (itemSource === 'new' && !newItemName.value.trim()) {
                e.preventDefault();
                alert('Masukkan nama item baru');
                return false;
            }
        });
    }
});

// Update item dropdown based on type
function updateItemOptions() {
    const type = document.querySelector('input[name="item_type"]:checked').value;
    const select = document.getElementById('itemSelect');
    const data = type === 'material' ? materialsData : sparepartsData;
    const used = type === 'material' ? usedMaterials : usedSpareparts;
    
    select.innerHTML = '<option value="">-- Pilih Item --</option>';
    data.forEach(item => {
        if (!used.has(item.id)) {
            const opt = document.createElement('option');
            opt.value = item.id;
            opt.textContent = `${item.name} (Stok: ${item.stock} ${item.unit || ''})`;
            opt.dataset.unit = item.unit || '';
            opt.dataset.price = item.price || 0;
            select.appendChild(opt);
        }
    });
    
    // Reset fields
    document.getElementById('itemUnit').value = '';
    document.getElementById('itemUnitCost').value = '';
}

// Auto-fill on select change
document.getElementById('itemSelect').addEventListener('change', function() {
    const opt = this.options[this.selectedIndex];
    if (opt && opt.value) {
        document.getElementById('itemUnit').value = opt.dataset.unit || '';
        document.getElementById('itemUnitCost').value = formatRupiah(opt.dataset.price || 0);
    }
});

// Format rupiah on input
document.getElementById('itemUnitCost').addEventListener('input', function() {
    this.value = formatRupiah(unformatRupiah(this.value));
});

// Add item form submit
document.getElementById('addItemForm').addEventListener('submit', async function(e) {
        e.preventDefault();
    
    const type = document.querySelector('input[name="item_type"]:checked').value;
    const itemId = document.getElementById('itemSelect').value;
    const quantity = document.getElementById('itemQuantity').value;
    const unit = document.getElementById('itemUnit').value;
    const unitCost = unformatRupiah(document.getElementById('itemUnitCost').value);
    
    if (!itemId || !quantity || !unit || !unitCost) {
        document.getElementById('addItemError').textContent = 'Semua field harus diisi';
        document.getElementById('addItemError').classList.remove('hidden');
        return;
    }
    
    const btn = document.getElementById('addItemSubmitBtn');
    btn.disabled = true;
    document.getElementById('addItemSubmitText').classList.add('hidden');
    document.getElementById('addItemSubmitLoader').classList.remove('hidden');
    
    try {
            const formData = new FormData();
        formData.append('_token', '{{ csrf_token() }}');
        formData.append(type === 'material' ? 'material_id' : 'sparepart_id', itemId);
        formData.append('quantity', quantity);
        formData.append('unit', unit);
        formData.append('unit_cost', unitCost);
        
        const url = type === 'material' 
            ? `/teknisi/productions/${productionId}/materials`
            : `/teknisi/productions/${productionId}/spareparts`;
        
        const response = await fetch(url, {
                method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
                body: formData
            });
            
        const data = await response.json();
            
            if (!response.ok || data.error) {
                throw new Error(data.error || data.message || 'Terjadi kesalahan');
            }
            
        // Add to table
        const item = data.item;
        addItemToTable(type, item);
        
        // Update used items
        if (type === 'material') {
            usedMaterials.add(parseInt(itemId));
    } else {
            usedSpareparts.add(parseInt(itemId));
        }
        
        // Update totals
        if (data.totals) updateTotals(data.totals);
        
        const typeName = type === 'material' ? 'Bahan' : 'Sparepart';
        showToast(`${typeName} berhasil ditambahkan`, 'success');
        closeAddItemModal();
        
    } catch (error) {
        document.getElementById('addItemError').textContent = error.message;
        document.getElementById('addItemError').classList.remove('hidden');
        showToast(error.message, 'error');
    } finally {
        btn.disabled = false;
        document.getElementById('addItemSubmitText').classList.remove('hidden');
        document.getElementById('addItemSubmitLoader').classList.add('hidden');
    }
});

// Add item to table
function addItemToTable(type, item) {
    const tbody = document.getElementById('itemsTableBody');
    const emptyState = document.getElementById('emptyState');
    
    if (emptyState) {
        emptyState.remove();
    }
    
    // Jika tbody tidak ada, reload halaman untuk mendapatkan struktur tabel
    if (!tbody) {
        location.reload();
        return;
    }
    
    const typeLabel = type === 'material' ? 'Bahan' : 'Sparepart';
    const typeColor = type === 'material' ? 'emerald' : 'blue';
    const typeIcon = type === 'material' ? 'cube' : 'cog';
    const itemId = type === 'material' ? item.material_id : item.sparepart_id;
    
    // Pastikan nilai numerik
    const unitCost = parseFloat(item.unit_cost) || 0;
    const totalCost = parseFloat(item.total_cost) || 0;
    const stock = item.stock !== undefined && item.stock !== null ? item.stock : '-';
    
    const tr = document.createElement('tr');
    tr.id = `item-${type}-${item.id}`;
    tr.className = 'hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors';
    tr.dataset.type = type;
    tr.dataset.id = item.id;
    tr.dataset.itemId = itemId;
    
    // Urutan kolom: Nama Item, Tipe, Jumlah, Satuan, Harga/Unit, Total, Stok, Aksi
    tr.innerHTML = `
        <td class="px-4 py-3">
            <div class="font-medium text-gray-900 dark:text-white">${item.name}</div>
        </td>
        <td class="px-4 py-3 text-center">
            <span class="inline-flex items-center gap-1.5 px-2.5 py-1 text-[11px] font-semibold rounded-full bg-${typeColor}-100 text-${typeColor}-700 border border-${typeColor}-300">
                <i class="fas fa-${typeIcon} text-${typeColor}-500"></i> ${typeLabel}
            </span>
        </td>
        <td class="px-4 py-3 text-center font-medium text-gray-900 dark:text-white">${item.quantity}</td>
        <td class="px-4 py-3 text-center text-gray-600 dark:text-gray-400">${item.unit}</td>
        <td class="px-4 py-3 text-right text-gray-600 dark:text-gray-400">Rp ${formatNumber(unitCost)}</td>
        <td class="px-4 py-3 text-right font-semibold text-gray-900 dark:text-white">Rp ${formatNumber(totalCost)}</td>
        <td class="px-4 py-3 text-center">
            <span class="px-2 py-0.5 text-xs font-medium rounded-full ${stock !== '-' && stock > 0 ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}">${stock}</span>
        </td>
        ${canEdit ? `
        <td class="px-4 py-3 text-center">
            <button type="button" onclick="deleteItem('${type}', ${item.id})" class="p-1.5 text-red-600 hover:bg-red-50 rounded" title="Hapus">
                <i class="fas fa-trash text-sm"></i>
            </button>
        </td>
        ` : ''}
    `;
    
    tbody.appendChild(tr);
}

// Delete item dengan konfirmasi modern
async function deleteItem(type, id) {
    const typeName = type === 'material' ? 'bahan' : 'sparepart';
    
    // Konfirmasi dengan SweetAlert jika tersedia, fallback ke modal custom
    const confirmed = await showConfirmDialog(
        'Hapus Item?',
        `Apakah Anda yakin ingin menghapus ${typeName} ini dari planning?`,
        'warning'
    );
    
    if (!confirmed) return;
    
    try {
        const url = type === 'material'
            ? `/teknisi/productions/${productionId}/materials/${id}`
            : `/teknisi/productions/${productionId}/spareparts/${id}`;
        
        const response = await fetch(url, {
        method: 'DELETE',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': '{{ csrf_token() }}' }
        });
        
        const data = await response.json();
        
        if (!response.ok || data.error) {
            throw new Error(data.error || 'Gagal menghapus');
        }
        
        // Remove from table
        const row = document.getElementById(`item-${type}-${id}`);
        const itemId = row?.dataset.itemId;
        if (row) row.remove();
        
        // Update used items
        if (itemId) {
            if (type === 'material') {
                usedMaterials.delete(parseInt(itemId));
            } else {
                usedSpareparts.delete(parseInt(itemId));
            }
        }
        
        // Update totals
        if (data.totals) updateTotals(data.totals);
        
        showToast('Item berhasil dihapus', 'success');
        
        // Check if table is empty
        const tbody = document.getElementById('itemsTableBody');
        if (tbody && tbody.children.length === 0) {
            location.reload();
        }
        
            } catch (error) {
        showToast(error.message, 'error');
    }
}

// Revise item
function reviseItem(type, id) {
    // TODO: Implement revise modal
    alert('Fitur revisi akan segera tersedia');
}

// Toggle item received dengan notifikasi informatif
async function toggleItemReceived(type, id, itemName) {
    const btn = document.querySelector(`.item-check-btn[data-type="${type}"][data-id="${id}"]`);
    if (!btn) return;
    
    const wasReceived = btn.dataset.received === 'true';
    const typeName = type === 'material' ? 'Bahan' : 'Sparepart';
    
    // Disable button sementara
    btn.disabled = true;
    btn.classList.add('opacity-50');
    
    try {
        const url = type === 'material'
            ? `/teknisi/productions/${productionId}/materials/${id}/toggle-received`
            : `/teknisi/productions/${productionId}/spareparts/${id}/toggle-received`;
        
        const response = await fetch(url, {
                    method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': '{{ csrf_token() }}' }
        });
        
        const data = await response.json();
                
                if (!response.ok || data.error) {
            throw new Error(data.error || 'Gagal update status');
        }
        
        // Toggle visual state
        const nowReceived = !wasReceived;
        btn.dataset.received = nowReceived ? 'true' : 'false';
        
        if (nowReceived) {
            btn.className = 'item-check-btn w-5 h-5 rounded border-2 flex items-center justify-center transition-all duration-200 bg-blue-500 border-blue-500';
            btn.innerHTML = '<i class="fas fa-check text-white text-xs"></i>';
            showToast(`✓ ${typeName} "${itemName}" sudah diterima`, 'success');
        } else {
            btn.className = 'item-check-btn w-5 h-5 rounded border-2 flex items-center justify-center transition-all duration-200 bg-white border-gray-300 hover:border-blue-400';
            btn.innerHTML = '';
            showToast(`${typeName} "${itemName}" ditandai belum diterima`, 'warning');
        }
        
        // Update counter
        updateReceivedCounter();
        
            } catch (error) {
        showToast(error.message, 'error');
    } finally {
        btn.disabled = false;
        btn.classList.remove('opacity-50');
    }
}

// Update received counter dan tombol konfirmasi
function updateReceivedCounter() {
    const buttons = document.querySelectorAll('.item-check-btn');
    const total = buttons.length;
    const received = Array.from(buttons).filter(btn => btn.dataset.received === 'true').length;
    
    const counterEl = document.getElementById('receivedCounter');
    if (counterEl) {
        counterEl.textContent = `${received}/${total} diterima`;
    }
    
    // Update pulse indicator
    const pulseEl = counterEl?.previousElementSibling;
    if (pulseEl) {
        if (received === total && total > 0) {
            pulseEl.className = 'w-2 h-2 rounded-full bg-emerald-500 animate-pulse';
        } else {
            pulseEl.className = 'w-2 h-2 rounded-full bg-amber-500 animate-pulse';
        }
    }
    
    // Update tombol konfirmasi
    const confirmBtn = document.getElementById('confirmAllBtn');
    if (confirmBtn) {
        if (received === total && total > 0) {
            confirmBtn.classList.remove('opacity-70');
            confirmBtn.disabled = false;
        } else {
            confirmBtn.classList.add('opacity-70');
        }
    }
}

// Confirm all items dengan dialog modern
async function confirmAllItems() {
    const confirmed = await showConfirmDialogGeneric(
        'Konfirmasi Penerimaan',
        'Apakah semua bahan dan sparepart sudah diterima dengan lengkap?',
        'success'
    );
    if (confirmed) {
        showToast('Memproses konfirmasi...', 'info');
        document.getElementById('confirmAllForm').submit();
    }
}

// Generic confirm dialog (untuk berbagai keperluan)
function showConfirmDialogGeneric(title, message, type = 'warning') {
    return new Promise((resolve) => {
        const colors = {
            success: { bg: '#ecfdf5', icon: 'check-circle', iconColor: '#10b981', btn: '#10b981', btnHover: '#059669' },
            warning: { bg: '#fffbeb', icon: 'exclamation-triangle', iconColor: '#f59e0b', btn: '#f59e0b', btnHover: '#d97706' },
            danger: { bg: '#fef2f2', icon: 'trash-alt', iconColor: '#ef4444', btn: '#ef4444', btnHover: '#dc2626' },
            info: { bg: '#eff6ff', icon: 'info-circle', iconColor: '#3b82f6', btn: '#3b82f6', btnHover: '#2563eb' }
        };
        const c = colors[type] || colors.warning;
        
        const overlay = document.createElement('div');
        overlay.style.cssText = `position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);display:flex;align-items:center;justify-content:center;padding:16px;`;
        overlay.innerHTML = `
            <div id="dialogBox" style="background:white;border-radius:16px;max-width:360px;width:100%;box-shadow:0 20px 60px rgba(0,0,0,0.2);transform:scale(0.9);opacity:0;transition:all 0.2s ease;">
                <div style="padding:28px;text-align:center;">
                    <div style="width:56px;height:56px;margin:0 auto 16px;background:${c.bg};border-radius:50%;display:flex;align-items:center;justify-content:center;">
                        <i class="fas fa-${c.icon}" style="color:${c.iconColor};font-size:22px;"></i>
                    </div>
                    <h3 style="font-size:18px;font-weight:700;color:#111827;margin-bottom:8px;">${title}</h3>
                    <p style="font-size:14px;color:#6b7280;line-height:1.5;">${message}</p>
                </div>
                <div style="display:flex;border-top:1px solid #f3f4f6;">
                    <button id="dlgCancel" style="flex:1;padding:14px;font-size:14px;font-weight:600;color:#374151;background:none;border:none;cursor:pointer;" onmouseover="this.style.background='#f9fafb'" onmouseout="this.style.background='none'">Batal</button>
                    <button id="dlgOk" style="flex:1;padding:14px;font-size:14px;font-weight:600;color:white;background:${c.btn};border:none;cursor:pointer;border-radius:0 0 16px 0;" onmouseover="this.style.background='${c.btnHover}'" onmouseout="this.style.background='${c.btn}'">Ya, Lanjutkan</button>
            </div>
            </div>
        `;
        document.body.appendChild(overlay);
        requestAnimationFrame(() => { const box = overlay.querySelector('#dialogBox'); box.style.transform = 'scale(1)'; box.style.opacity = '1'; });
        const cleanup = (result) => { const box = overlay.querySelector('#dialogBox'); box.style.transform = 'scale(0.9)'; box.style.opacity = '0'; setTimeout(() => { overlay.remove(); resolve(result); }, 200); };
        overlay.querySelector('#dlgCancel').onclick = () => cleanup(false);
        overlay.querySelector('#dlgOk').onclick = () => cleanup(true);
        overlay.onclick = (e) => { if (e.target === overlay) cleanup(false); };
    });
}

// Start production dengan dialog modern
async function startProduction() {
    const confirmed = await showConfirmDialogGeneric(
        'Mulai Produksi?',
        'Stok bahan dan sparepart akan dikurangi sesuai kebutuhan. Pastikan semua item sudah diterima.',
        'info'
    );
    if (confirmed) {
        showToast('Memulai produksi...', 'info');
        document.getElementById('startProductionForm').submit();
    }
}

// Update totals display
function updateTotals(totals) {
    const materialTotal = parseFloat(totals.total_material_cost) || 0;
    const sparepartTotal = parseFloat(totals.total_sparepart_cost) || 0;
    const directTotal = materialTotal + sparepartTotal;
    const actualTotal = directTotal + laborCost;
    
    const elMaterial = document.getElementById('totalMaterialCost');
    const elSparepart = document.getElementById('totalSparepartCost');
    const elDirect = document.getElementById('totalDirectCost');
    const elActual = document.getElementById('totalActualCost');
    const elBreakdown = document.getElementById('costBreakdown');
    const elPerUnit = document.getElementById('costPerUnit');
    
    if (elMaterial) elMaterial.textContent = 'Rp ' + formatNumber(materialTotal);
    if (elSparepart) elSparepart.textContent = 'Rp ' + formatNumber(sparepartTotal);
    if (elDirect) elDirect.textContent = 'Rp ' + formatNumber(directTotal);
    if (elActual) elActual.textContent = 'Rp ' + formatNumber(actualTotal);
    if (elBreakdown) elBreakdown.textContent = `Langsung: Rp ${formatNumber(directTotal)} • Labor: Rp ${formatNumber(laborCost)}`;
    if (elPerUnit && orderQty > 0) elPerUnit.textContent = 'Rp ' + formatNumber(actualTotal / orderQty);
}

// Update modal summary
function updateModalSummary() {
    const tbody = document.getElementById('itemsTableBody');
    let materialCount = 0, sparepartCount = 0, total = 0;
    
    if (tbody) {
        tbody.querySelectorAll('tr').forEach(tr => {
            if (tr.dataset.type === 'material') materialCount++;
            else sparepartCount++;
        });
    }
    
    document.getElementById('modalMaterialCount').textContent = materialCount;
    document.getElementById('modalSparepartCount').textContent = sparepartCount;
    document.getElementById('modalTotalCost').textContent = document.getElementById('totalDirectCost')?.textContent || 'Rp 0';
}

// CSS Animation
const style = document.createElement('style');
style.textContent = `
    @keyframes slide-in { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
    .animate-slide-in { animation: slide-in 0.3s ease-out; }
`;
document.head.appendChild(style);
</script>
@endpush
