@extends('layouts.app')
@section('title', 'Processing — ' . $job->job_number)
@section('breadcrumb')<a href="{{ route('processing.index') }}" class="hover:text-white">Processing</a> <i class="fas fa-chevron-right text-xs mx-1 text-slate-600"></i> <span class="text-white">{{ $job->job_number }}</span>@endsection

@section('content')
<div class="space-y-5">
    <div class="card p-5">
        <div class="flex items-center justify-between">
            <div>
                <div class="flex items-center gap-3 mb-1">
                    <h1>{{ $job->job_number }} — Processing</h1>
                    <span class="badge badge-{{ $job->stageColor() }}">{{ $job->stageLabel() }}</span>
                </div>
                <p>{{ $job->contact?->full_name }} · {{ $job->site_address }}, {{ $job->site_suburb }}</p>
            </div>
        </div>
    </div>

    @if(session('success'))
    <div class="card p-3 border-green-600 bg-green-900/20 text-green-300 flex items-center gap-2 text-sm">
        <i class="fas fa-check-circle"></i> {{ session('success') }}
    </div>
    @endif
    @if(session('error'))
    <div class="card p-3 border-red-600 bg-red-900/20 text-red-300 flex items-center gap-2 text-sm">
        <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
    </div>
    @endif

    <!-- ═══════════════════════════════════════════════════════════════
         ASSIGN EMPLOYEE TASKS SECTION
         ════════════════════════════════════════════════════════════ -->
    <div x-data="{
            open: false,
            selectedTasks: [],
            toggleTask(id) {
                const idx = this.selectedTasks.indexOf(id);
                if (idx > -1) { this.selectedTasks.splice(idx, 1); }
                else { this.selectedTasks.push(id); }
            },
            isSelected(id) { return this.selectedTasks.includes(id); }
        }" class="card p-5">
        <div class="flex items-center justify-between">
            <div>
                <h3 class="flex items-center gap-2">
                    <i class="fas fa-user-hard-hat text-yellow-400 text-sm"></i> Factory Employee Task Assignments
                </h3>
                <p class="text-xs text-slate-500 mt-0.5">Assign employee tasks to factory employees for this job.</p>
            </div>
            <button @click="open = !open; if(!open) selectedTasks = []" class="btn btn-secondary text-xs" x-text="open ? 'Cancel' : '+ Assign Task'"></button>
        </div>

        {{-- Assign form --}}
        <div x-show="open" x-cloak class="mt-4 pt-4 border-t border-slate-700">
            <form method="POST" action="{{ route('processing.assign_employee_task', $job) }}" class="space-y-5">
                @csrf

                {{-- Employee select --}}
                <div>
                    <label class="block text-sm text-slate-400 mb-1">Factory Employee <span class="text-red-400">*</span></label>
                    <select name="user_id" class="input" required>
                        <option value="">— Select employee —</option>
                        @foreach($factoryEmployees as $emp)
                        <option value="{{ $emp->id }}">{{ $emp->name }}</option>
                        @endforeach
                    </select>
                </div>

                {{-- Task checkboxes --}}
                <div>
                    <label class="block text-sm text-slate-400 mb-2">
                        Task Type <span class="text-red-400">*</span>
                        <span class="text-slate-500 font-normal">(select at least one)</span>
                    </label>
                    <div class="rounded-lg border border-slate-600 p-4 grid grid-cols-2 gap-x-6 gap-y-3">
                        @foreach($employeeTaskTypes as $tt)
                        <label class="flex items-center gap-2 cursor-pointer select-none">
                            <input type="checkbox"
                                   name="task_type_ids[]"
                                   value="{{ $tt->id }}"
                                   @change="toggleTask({{ $tt->id }})"
                                   class="w-4 h-4 rounded border-slate-500 bg-slate-800 text-blue-500 accent-blue-500 cursor-pointer">
                            <span class="text-sm text-slate-300">{{ $tt->name }}</span>
                        </label>
                        @endforeach
                    </div>
                </div>

                {{-- Dynamic hours inputs — one per selected task --}}
                <template x-if="selectedTasks.length > 0">
                    <div class="space-y-3">
                        <p class="text-sm text-slate-400">Allocate Hours <span class="text-red-400">*</span> <span class="text-slate-500 font-normal">(fill in hours for each selected task)</span></p>
                        @foreach($employeeTaskTypes as $tt)
                        <div x-show="isSelected({{ $tt->id }})" x-cloak class="flex items-center gap-4">
                            <span class="text-sm text-slate-300 w-48 flex-shrink-0">{{ $tt->name }}</span>
                            <input type="number"
                                   name="allocated_hours[{{ $tt->id }}]"
                                   :required="isSelected({{ $tt->id }})"
                                   min="0.5" step="0.5"
                                   placeholder="e.g. 2.5"
                                   class="input w-40">
                        </div>
                        @endforeach
                    </div>
                </template>

                <div>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-user-plus mr-1"></i> Assign Task
                    </button>
                </div>
            </form>
        </div>

        {{-- Existing assignments grouped by employee --}}
        @if($job->employeeTaskAssignments->count() > 0)
        <div class="mt-4 space-y-3">
            @foreach($job->employeeTaskAssignments->groupBy('user_id') as $userId => $assignments)
            @php $emp = $assignments->first()->user; @endphp
            <div class="rounded-lg p-4" style="background:#0f172a;border:1px solid #1e293b;">
                <div class="flex items-center gap-3 mb-3">
                    <div class="w-8 h-8 rounded-full bg-yellow-900 flex items-center justify-center text-xs font-bold text-yellow-300">
                        {{ $emp?->initials ?? '?' }}
                    </div>
                    <div class="text-sm font-semibold text-white">{{ $emp?->name ?? 'Unknown' }}</div>
                    <span class="badge badge-gray text-xs">{{ $assignments->count() }} {{ Str::plural('task', $assignments->count()) }}</span>
                </div>
                <div class="flex flex-wrap gap-2">
                    @foreach($assignments as $assignment)
                    <div class="flex items-center gap-2 px-3 py-1.5 rounded-full"
                         style="background:#1e293b;border:1px solid #334155;">
                        <i class="fas fa-tasks text-xs text-blue-400"></i>
                        <span class="text-sm text-white">{{ $assignment->taskType?->name ?? '—' }}</span>
                        <form method="POST"
                              action="{{ route('processing.remove_employee_task', $assignment) }}"
                              class="inline"
                              onsubmit="return confirm('Remove this task assignment?')">
                            @csrf @method('DELETE')
                            <button type="submit"
                                    class="text-slate-500 hover:text-red-400 ml-1 text-xs"
                                    title="Remove">
                                <i class="fas fa-times"></i>
                            </button>
                        </form>
                    </div>
                    @endforeach
                </div>
            </div>
            @endforeach
        </div>
        @else
        <div class="mt-4 text-sm text-slate-500 text-center py-4">
            <i class="fas fa-user-clock text-slate-700 text-2xl block mb-2"></i>
            No employee tasks assigned yet for this job.
        </div>
        @endif
    </div>

    <!-- Add New Processing Order Form -->
    <div x-data="{ open: false }" class="card p-5">
        <div class="flex items-center justify-between">
            <h3 class="flex items-center gap-2"><i class="fas fa-plus-circle text-blue-400 text-sm"></i>New Processing Order</h3>
            <button @click="open = !open" class="btn btn-secondary text-xs" x-text="open ? 'Cancel' : '+ Add Order'"></button>
        </div>
        <div x-show="open" x-cloak class="mt-4">
            <form method="POST" action="{{ route('processing.store_order', $job) }}" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                @csrf
                <div class="md:col-span-2">
                    <label class="block text-sm text-slate-400 mb-1">Description *</label>
                    <input type="text" name="description" class="input" required placeholder="e.g. Cabinet carcasses, Doors, Benchtop...">
                </div>
                <div>
                    <label class="block text-sm text-slate-400 mb-1">Supplier</label>
                    <input type="text" name="supplier" class="input" placeholder="Supplier name">
                </div>
                <div>
                    <label class="block text-sm text-slate-400 mb-1">Order Date</label>
                    <input type="date" name="order_date" class="input" value="{{ date('Y-m-d') }}">
                </div>
                <div>
                    <label class="block text-sm text-slate-400 mb-1">ETA Date</label>
                    <input type="date" name="eta_date" class="input">
                </div>
                <div>
                    <label class="block text-sm text-slate-400 mb-1">Total Items</label>
                    <input type="number" name="total_items" class="input" min="0" placeholder="0">
                </div>
                <div class="md:col-span-2">
                    <label class="block text-sm text-slate-400 mb-1">Notes</label>
                    <textarea name="notes" class="input" rows="2" placeholder="Any additional notes..."></textarea>
                </div>
                <div class="md:col-span-2 flex justify-end">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-plus mr-1"></i>Create Processing Order</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Processing Orders -->
    <div class="space-y-4">
        @forelse($job->processingOrders as $order)
        <div class="card p-5">
            <div class="flex items-start justify-between mb-4">
                <div>
                    <div class="flex items-center gap-2 mb-1">
                        <span class="text-sm font-bold text-white">{{ $order->po_number }}</span>
                        <span class="badge badge-{{ $order->statusColor() }}">{{ ucwords(str_replace('_', ' ', $order->status)) }}</span>
                    </div>
                    <p class="text-sm">{{ $order->description }}</p>
                    <div class="flex gap-4 mt-2 text-xs text-slate-500">
                        <span><i class="fas fa-building mr-1"></i>{{ $order->supplier }}</span>
                        @if($order->order_date)
                        <span><i class="fas fa-calendar mr-1"></i>Ordered {{ $order->order_date->format('d M Y') }}</span>
                        @endif
                        @if($order->eta_date)
                        <span><i class="fas fa-truck mr-1"></i>ETA {{ $order->eta_date->format('d M Y') }}</span>
                        @endif
                    </div>
                </div>
                <div class="text-right">
                    <div class="text-2xl font-bold text-white">{{ $order->progress_pct }}%</div>
                    <div class="text-xs text-slate-500">{{ $order->completed_items }}/{{ $order->total_items }} items</div>
                </div>
            </div>
            <div class="progress-bar"><div class="progress-fill" style="width: {{ $order->progress_pct }}%"></div></div>
        </div>
        @empty
        <div class="card p-8 text-center text-slate-500">
            <i class="fas fa-box text-3xl mb-3 text-slate-700 block"></i>No processing orders yet.
        </div>
        @endforelse
    </div>

    <!-- Tasks -->
    @if($job->tasks && $job->tasks->count() > 0)
    <div class="card p-5">
        <h3 class="mb-4">Job Tasks</h3>
        <div class="space-y-2">
            @foreach($job->tasks as $task)
            <div class="flex items-center gap-3 py-2 border-b border-slate-700 last:border-0">
                <div class="w-2 h-2 rounded-full flex-shrink-0 {{ $task->priority === 'high' ? 'bg-red-400' : ($task->priority === 'medium' ? 'bg-yellow-400' : 'bg-slate-500') }}"></div>
                <div class="flex-1 min-w-0">
                    <div class="text-sm text-white">{{ $task->title }}</div>
                    <div class="text-xs text-slate-500">{{ $task->assignedTo?->name }} · Due {{ $task->due_date?->format('d M') }}</div>
                </div>
                <span class="badge badge-{{ $task->status === 'completed' ? 'green' : ($task->status === 'in_progress' ? 'blue' : 'gray') }}">
                    {{ ucwords(str_replace('_', ' ', $task->status)) }}
                </span>
            </div>
            @endforeach
        </div>
    </div>
    @endif
</div>
@endsection
