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

@section('content')
<div x-data="{
    running: {{ $running ? 'true' : 'false' }},
    elapsed: '{{ $running ? $running->elapsed : '0m' }}',
    startedAt: {{ $running ? "'" . $running->started_at->toISOString() . "'" : 'null' }},
    taskId: '',
    jobId: '',
    taskErr: false,
    jobErr: false,
    isTradesUser: {{ in_array(auth()->user()->role?->name, ['trades']) ? 'true' : 'false' }},
    tick() {
        if (!this.startedAt) return;
        const diff = Math.floor((Date.now() - new Date(this.startedAt)) / 1000);
        const h = Math.floor(diff/3600), m = Math.floor((diff%3600)/60), s = diff%60;
        this.elapsed = (h>0?h+'h ':'')+m+'m '+s+'s';
    },
    tryStart() {
        this.taskErr = !this.isTradesUser && !this.taskId;
        this.jobErr  = !this.jobId;
        if (this.taskErr || this.jobErr) return;
        this.running = true;
        $el.querySelector('form[data-timer-form]').submit();
    }
}" x-init="if(running) setInterval(()=>tick(), 1000)">

<div class="flex items-center justify-between mb-6">
    <div>
        <h1 class="mb-1">My Timesheet</h1>
        <p>Track your working hours and view your time entries</p>
    </div>
    <div class="flex gap-3">
        @if(in_array(auth()->user()->role?->name, ['office_admin','project_manager']))
        <a href="{{ route('timesheet.admin') }}" class="btn btn-secondary"><i class="fas fa-users"></i> All Staff</a>
        @endif
    </div>
</div>

<!-- Weekly Summary -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
    <div class="stat-card">
        <div class="text-xs text-slate-400 mb-1">This Week Hours</div>
        <div class="text-2xl font-bold text-white">{{ number_format($weeklyHours, 1) }}h</div>
        <div class="text-xs text-slate-500 mt-1">{{ Carbon\Carbon::now()->startOfWeek()->format('M j') }} – {{ Carbon\Carbon::now()->endOfWeek()->format('M j') }}</div>
    </div>
    @if(auth()->user()->hourly_rate)
    <div class="stat-card">
        <div class="text-xs text-slate-400 mb-1">This Week Earnings</div>
        <div class="text-2xl font-bold text-green-400">${{ number_format($weeklyEarnings, 2) }}</div>
        <div class="text-xs text-slate-500 mt-1">@ ${{ number_format(auth()->user()->hourly_rate, 2) }}/hr</div>
    </div>
    <div class="stat-card">
        <div class="text-xs text-slate-400 mb-1">Hourly Rate</div>
        <div class="text-2xl font-bold text-blue-400">${{ number_format(auth()->user()->hourly_rate, 2) }}</div>
        <div class="text-xs text-slate-500 mt-1">per hour</div>
    </div>
    @else
    <div class="stat-card col-span-2">
        <div class="text-xs text-slate-400 mb-1">Rate</div>
        <div class="text-sm text-slate-500">No hourly rate set — contact admin</div>
    </div>
    @endif
</div>

<!-- Timer Panel -->
<div class="card p-5 mb-6">
    <h3 class="mb-4"><i class="fas fa-stopwatch mr-2 text-blue-400"></i>Timer</h3>

    <div x-show="running" class="flex items-center gap-6 mb-4 p-4 rounded-xl bg-green-900/20 border border-green-700">
        <div class="w-3 h-3 rounded-full bg-green-400 animate-pulse"></div>
        <div>
            <div class="text-green-300 font-semibold text-lg" x-text="elapsed">{{ $running?->elapsed ?? '0m' }}</div>
            <div class="text-green-500 text-xs">Timer running
                @if($running?->taskType) — {{ $running->taskType->name }} @endif
                @if($running?->job) — {{ $running->job->job_number }} @endif
            </div>
        </div>
        <form method="POST" action="{{ route('timesheet.stop') }}" class="ml-auto">
            @csrf
            <button type="submit" class="btn btn-danger"><i class="fas fa-stop"></i> Stop Timer</button>
        </form>
    </div>

    <div x-show="!running">
        @if((auth()->user()->role?->name !== 'trades' && $errors->has('task_type_id')) || $errors->has('job_id'))
        <div class="mb-3 p-3 rounded-lg bg-red-900/30 border border-red-700 text-sm text-red-300">
            <i class="fas fa-exclamation-circle mr-1"></i>
            @foreach(auth()->user()->role?->name === 'trades' ? ['job_id'] : ['task_type_id','job_id'] as $field)
                @error($field)<div>{{ $message }}</div>@enderror
            @endforeach
        </div>
        @endif
        <form method="POST" action="{{ route('timesheet.start') }}" class="grid grid-cols-1 {{ auth()->user()->role?->name === 'trades' ? 'md:grid-cols-3' : 'md:grid-cols-4' }} gap-3" data-timer-form>
            @csrf
            @if(auth()->user()->role?->name !== 'trades')
            <div>
                <label class="flex items-center gap-1">Task Type <span class="text-red-400">*</span></label>
                <select name="task_type_id" class="input" x-model="taskId"
                        :class="taskErr ? 'border-red-500' : ''"
                        @change="taskErr = !taskId">
                    <option value="">— Select task —</option>
                    @foreach($taskTypes->groupBy('task_category') as $category => $tasks)
                    <optgroup label="{{ ucfirst($category) }} Tasks">
                        @foreach($tasks as $task)
                        <option value="{{ $task->id }}" {{ old('task_type_id') == $task->id ? 'selected' : '' }}>{{ $task->name }}</option>
                        @endforeach
                    </optgroup>
                    @endforeach
                </select>
                <p x-show="taskErr" class="text-xs text-red-400 mt-1">Please select a task type.</p>
            </div>
            @endif
            <div>
                <label class="flex items-center gap-1">Job <span class="text-red-400">*</span></label>
                <select name="job_id" class="input" x-model="jobId"
                        :class="jobErr ? 'border-red-500' : ''"
                        @change="jobErr = !jobId">
                    <option value="">— Select job —</option>
                    @foreach($jobs as $job)
                    <option value="{{ $job->id }}" {{ old('job_id') == $job->id ? 'selected' : '' }}>{{ $job->job_number }} — {{ $job->contact?->first_name }} {{ $job->contact?->last_name }}</option>
                    @endforeach
                </select>
                <p x-show="jobErr" class="text-xs text-red-400 mt-1">Please select a job.</p>
            </div>
            <div>
                <label>Notes (optional)</label>
                <input type="text" name="notes" class="input" placeholder="e.g. Upper cabinet run" value="{{ old('notes') }}">
            </div>
            <div class="flex items-end">
                <button type="button" class="btn btn-primary w-full" @click="tryStart()">
                    <i class="fas fa-play"></i> Start Timer
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Time Entries -->
<div class="card overflow-hidden">
    <div class="p-5 border-b border-slate-700">
        <h3>Recent Time Entries</h3>
    </div>
    <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">Date</th>
                <th class="px-5 py-3 text-left">Task</th>
                <th class="px-5 py-3 text-left">Job</th>
                <th class="px-5 py-3 text-left">Duration</th>
                @if(auth()->user()->hourly_rate)
                <th class="px-5 py-3 text-left">Amount</th>
                @endif
                <th class="px-5 py-3 text-left">Status</th>
                <th class="px-5 py-3 text-left">Notes</th>
                <th class="px-5 py-3"></th>
            </tr></thead>
            <tbody>
                @forelse($entries as $entry)
                <tr class="table-row">
                    <td class="px-5 py-3 text-sm text-slate-300">{{ $entry->started_at->format('d M Y H:i') }}</td>
                    <td class="px-5 py-3 text-sm text-white">{{ $entry->taskType?->name ?? '—' }}</td>
                    <td class="px-5 py-3 text-sm text-slate-300">{{ $entry->job?->job_number ?? '—' }}</td>
                    <td class="px-5 py-3 text-sm font-mono text-blue-300">{{ $entry->elapsed }}</td>
                    @if(auth()->user()->hourly_rate)
                    <td class="px-5 py-3 text-sm text-green-400">${{ number_format($entry->duration_hours * auth()->user()->hourly_rate, 2) }}</td>
                    @endif
                    <td class="px-5 py-3">
                        <span class="badge {{ $entry->status === 'running' ? 'badge-green' : 'badge-blue' }}">{{ ucfirst($entry->status) }}</span>
                    </td>
                    <td class="px-5 py-3 text-sm text-slate-400">{{ $entry->notes ?? '—' }}</td>
                    <td class="px-5 py-3">
                        @if($entry->status !== 'running' && !$entry->invoiced_in)
                        <form method="POST" action="{{ route('timesheet.destroy', $entry) }}" onsubmit="return confirm('Delete this entry?')">
                            @csrf @method('DELETE')
                            <button type="submit" class="text-slate-500 hover:text-red-400 text-xs"><i class="fas fa-trash"></i></button>
                        </form>
                        @endif
                    </td>
                </tr>
                @empty
                <tr><td colspan="8" class="px-5 py-8 text-center text-slate-500">No time entries yet. Start your first timer above.</td></tr>
                @endforelse
            </tbody>
        </table>
    </div>
    @if($entries->hasPages())
    <div class="p-4 border-t border-slate-700">{{ $entries->links() }}</div>
    @endif
</div>

<!-- Invoice CTA -->
@php $directRoles = ['factory_employee', 'processor', 'lead_installer']; @endphp
@if(auth()->user()->hourly_rate && !in_array(auth()->user()->role?->name, $directRoles))
<div class="mt-4 card p-4" x-data="{ showReqModal: false }">
    <div class="flex items-center justify-between">
        <div>
            <div class="text-sm text-white font-medium">Ready to be invoiced?</div>
            <div class="text-xs text-slate-400">Request invoice approval to notify admin &amp; accounts for your time entries.</div>
        </div>
        <div class="flex gap-2">
            <button @click="showReqModal = true" class="btn btn-primary text-sm">
                <i class="fas fa-paper-plane"></i> Request Approval
            </button>
            <a href="{{ route('staff-invoices.index') }}" class="btn btn-secondary text-sm">
                <i class="fas fa-file-invoice-dollar"></i> My Invoices
            </a>
        </div>
    </div>

    <!-- Inline request modal -->
    <div x-show="showReqModal" 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 your pay period. Admin &amp; accounts 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="{{ \Carbon\Carbon::now()->startOfWeek()->toDateString() }}">
                        </div>
                        <div>
                            <label>Period End</label>
                            <input type="date" name="period_end" class="input" required
                                   value="{{ \Carbon\Carbon::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="showReqModal=false" class="btn btn-secondary flex-1">Cancel</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
@endif

</div>
@endsection
