@extends('layouts.app')
@section('title', 'Staff Invoices')
@section('breadcrumb')<span class="text-white">Staff Invoices</span>@endsection

@section('content')
<div x-data="{ showGenModal: false, showRequestModal: false, genUserId: '', genStart: '', genEnd: '', isTradesUser: false }">

<div class="flex items-center justify-between mb-6">
    <div>
        <h1 class="mb-1">Staff Invoices</h1>
        <p>Time-based invoices for factory employees, processors and trades</p>
    </div>
    <div class="flex gap-2">
        <!-- @if(!$isAdminOrAccounts)
        <button @click="showRequestModal = true" class="btn btn-secondary">
            <i class="fas fa-paper-plane"></i> Request Approval
        </button>
        @endif -->
        @if($isAdminOrAccounts)
        <button @click="showGenModal = true" class="btn btn-primary">
            <i class="fas fa-plus"></i> Generate Invoice
        </button>
        @endif
    </div>
</div>

@if($pendingCount > 0)
<div class="card p-4 mb-4 border-yellow-600 bg-yellow-900/20 flex items-center gap-3">
    <i class="fas fa-clock text-yellow-400"></i>
    <span class="text-yellow-300"><strong>{{ $pendingCount }}</strong> invoice{{ $pendingCount > 1 ? 's' : '' }} pending approval</span>
</div>
@endif

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

<div class="card overflow-hidden">
    <div class="overflow-x-auto">
        <table class="w-full">
            <thead><tr class="text-xs text-slate-400 uppercase border-b border-slate-700">
                <th class="px-5 py-3 text-left">Invoice #</th>
                @if($isAdminOrAccounts)<th class="px-5 py-3 text-left">Staff Member</th>@endif
                <th class="px-5 py-3 text-left">Job</th>
                <th class="px-5 py-3 text-left">Period</th>
                <th class="px-5 py-3 text-left">Hours</th>
                <th class="px-5 py-3 text-left">Rate</th>
                <th class="px-5 py-3 text-left">Total</th>
                <th class="px-5 py-3 text-left">Status</th>
                <th class="px-5 py-3 text-left">Approved By</th>
                <th class="px-5 py-3"></th>
            </tr></thead>
            <tbody>
                @forelse($invoices as $inv)
                <tr class="table-row cursor-pointer" onclick="window.location='{{ route('staff-invoices.show', $inv) }}'">
                    <td class="px-5 py-3 text-sm font-mono text-blue-300">{{ $inv->invoice_number }}</td>
                    @if($isAdminOrAccounts)
                    <td class="px-5 py-3">
                        <div class="text-sm font-medium text-white">{{ $inv->user->name }}</div>
                        <div class="text-xs text-slate-400">{{ $inv->user->role?->display_name }}</div>
                    </td>
                    @endif
                    <td class="px-5 py-3">
                        @if($inv->job)
                        <span class="text-xs font-mono text-orange-300 bg-orange-900/20 px-2 py-0.5 rounded">{{ $inv->job->job_number }}</span>
                        @else
                        <span class="text-xs text-slate-600">—</span>
                        @endif
                    </td>
                    <td class="px-5 py-3 text-sm text-slate-300">{{ $inv->period_start->format('d M') }} – {{ $inv->period_end->format('d M Y') }}</td>
                    <td class="px-5 py-3 text-sm font-mono text-white">{{ number_format($inv->total_hours, 2) }}h</td>
                    <td class="px-5 py-3 text-sm text-slate-300">${{ number_format($inv->hourly_rate, 2) }}/hr</td>
                    <td class="px-5 py-3 text-sm font-bold text-green-400">${{ number_format($inv->total_amount, 2) }}</td>
                    <td class="px-5 py-3">
                        <span class="badge {{ $inv->status_badge }}">{{ ucfirst($inv->status) }}</span>
                    </td>
                    <td class="px-5 py-3 text-sm text-slate-400">{{ $inv->approver?->name ?? '—' }}</td>
                    <td class="px-5 py-3">
                        <a href="{{ route('staff-invoices.show', $inv) }}" class="text-slate-400 hover:text-white text-xs"><i class="fas fa-eye"></i></a>
                    </td>
                </tr>
                @empty
                <tr><td colspan="10" class="px-5 py-8 text-center text-slate-500">No invoices found.</td></tr>
                @endforelse
            </tbody>
        </table>
    </div>
    @if($invoices->hasPages())
    <div class="p-4 border-t border-slate-700">{{ $invoices->links() }}</div>
    @endif
</div>

<!-- Request Approval Modal (for hourly staff, period-based) -->
@if(!$isAdminOrAccounts)
<div x-show="showRequestModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60" style="display:none">
    <div class="card p-6 w-full max-w-md mx-4">
        <h3 class="mb-2">Request Invoice Approval</h3>
        <p class="text-sm text-slate-400 mb-4">Select the pay period for your uninvoiced time entries. An admin or accounts officer will be notified to generate and approve your invoice.</p>
        <form method="POST" action="{{ route('staff-invoices.request-approval') }}">
            @csrf
            <div class="space-y-4">
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label>Period Start</label>
                        <input type="date" name="period_start" class="input" required
                               value="{{ now()->startOfWeek()->toDateString() }}">
                    </div>
                    <div>
                        <label>Period End</label>
                        <input type="date" name="period_end" class="input" required
                               value="{{ now()->toDateString() }}">
                    </div>
                </div>
                <div>
                    <label>Notes (optional)</label>
                    <textarea name="notes" class="input" rows="2" placeholder="Any notes for admin..."></textarea>
                </div>
                <div class="flex gap-3">
                    <button type="submit" class="btn btn-primary flex-1">
                        <i class="fas fa-paper-plane"></i> Send Request
                    </button>
                    <button type="button" @click="showRequestModal=false" class="btn btn-secondary flex-1">Cancel</button>
                </div>
            </div>
        </form>
    </div>
</div>
@endif

<!-- Generate Invoice Modal (admin/accounts) -->
@if($isAdminOrAccounts)
<div x-show="showGenModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60" style="display:none">
    <div class="card p-6 w-full max-w-lg mx-4">
        <h3 class="mb-4">Generate Staff Invoice</h3>
        <form method="POST" action="{{ route('staff-invoices.generate') }}">
            @csrf
            <div class="space-y-4">
                {{-- Staff Member --}}
                <div>
                    <label>Staff Member <span class="text-red-400">*</span></label>
                    @php
                        $hourlyStaff = \App\Models\User::with('role')->where('role_id',9)->whereNotNull('hourly_rate')->orderBy('name')->get();
                    @endphp
                    <select name="user_id" class="input" required
                            x-model="genUserId"
                            @change="isTradesUser = ($el.options[$el.selectedIndex].dataset.role === 'trades')">
                        <option value="">— Select staff —</option>
                        @foreach($hourlyStaff as $u)
                        <option value="{{ $u->id }}" data-role="{{ $u->role?->name }}"
                                {{ old('user_id') == $u->id ? 'selected' : '' }}>
                            {{ $u->name }} ({{ $u->role?->display_name }}) — ${{ number_format($u->hourly_rate, 2) }}/hr
                        </option>
                        @endforeach
                    </select>
                </div>

                {{-- Job selector — shown for trades users to generate per-job invoices --}}
                <div x-show="isTradesUser" x-transition>
                    <label class="flex items-center gap-2">
                        Job (Trades — select for job-specific invoice)
                        <span class="text-xs text-orange-400 bg-orange-900/20 px-2 py-0.5 rounded">Trades</span>
                    </label>
                    <select name="job_id" class="input">
                        <option value="">— Select job (required for trades invoice) —</option>
                        @foreach(\App\Models\Job::with('contact')->orderBy('job_number')->get() as $j)
                        <option value="{{ $j->id }}">{{ $j->job_number }}{{ $j->contact ? ' — ' . $j->contact->first_name . ' ' . $j->contact->last_name : '' }}</option>
                        @endforeach
                    </select>
                    <p class="text-xs text-slate-500 mt-1">
                        For trades: select a job to generate a job-specific invoice. All completed, uninvoiced entries for that job will be included.
                    </p>
                </div>

                {{-- Date range — required for non-trades; optional for trades if job selected --}}
                <div>
                    <label>
                        Period
                        <span x-show="isTradesUser" class="text-xs text-slate-500 ml-1">(optional when job is selected — auto-filled from entries)</span>
                        <span x-show="!isTradesUser" class="text-red-400">*</span>
                    </label>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="text-xs text-slate-500">Start</label>
                            <input type="date" name="period_start" class="input" :required="!isTradesUser">
                        </div>
                        <div>
                            <label class="text-xs text-slate-500">End</label>
                            <input type="date" name="period_end" class="input" :required="!isTradesUser">
                        </div>
                    </div>
                </div>

                <p class="text-xs text-slate-500">
                    All completed, uninvoiced time entries matching the selected criteria will be included.
                    Once generated, the invoice will be in <strong>pending</strong> status until approved.
                </p>
                <div class="flex gap-3">
                    <button type="submit" class="btn btn-primary flex-1">Generate Invoice</button>
                    <button type="button" @click="showGenModal=false" class="btn btn-secondary flex-1">Cancel</button>
                </div>
            </div>
        </form>
    </div>
</div>
@endif

</div>
@endsection
