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

@section('content')
@php
    $isFactoryEmployee = auth()->user()->role?->name === 'factory_employee';
@endphp
<script>
    window.__timesheetJobTaskMap  = @json($jobTaskMap ?? []);
    window.__timesheetAllTaskTypes = @json($allTaskTypesJson ?? []);
</script>
<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' }},
    isFactoryEmployee: {{ $isFactoryEmployee ? 'true' : 'false' }},
    jobTaskMap: window.__timesheetJobTaskMap,
    allTaskTypes: window.__timesheetAllTaskTypes,
    get filteredTaskTypes() {
        if (!this.isFactoryEmployee) return this.allTaskTypes;
        if (!this.jobId) return [];
        const allowed = this.jobTaskMap[this.jobId] || [];
        return this.allTaskTypes.filter(t => allowed.includes(t.id));
    },
    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>
       
    </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>
@if(!$isFactoryEmployee)
<!-- 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>
@endif
@if(!$isFactoryEmployee)
<!-- 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-warning"><i class="fas fa-pause"></i> Pause 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">
            @foreach(auth()->user()->role?->name === 'trades' ? ['job_id'] : ['task_type_id','job_id'] as $field)
                @error($field)<div>{{ $message }}</div>@enderror
            @endforeach
        </div>
        @endif
        @if(!$isFactoryEmployee)
        <form method="POST" action="{{ route('timesheet.start') }}"
              class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end"
              data-timer-form>
            @csrf

            @if($isFactoryEmployee)
            {{-- ── Job selector (first for factory_employee so task list can react) ── --}}
            <!-- <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; taskId = ''">
                    <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> -->

            {{-- Task type: filtered based on selected job --}}
            <!-- <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"
                        :disabled="!jobId">
                    <option value="">— Select task —</option>
                    <template x-for="t in filteredTaskTypes" :key="t.id">
                        <option :value="t.id" x-text="t.name"></option>
                    </template>
                </select>
                <p x-show="taskErr" class="text-xs text-red-400 mt-1">Please select a task type.</p>
                <p x-show="jobId && filteredTaskTypes.length === 0" class="text-xs text-amber-400 mt-1">
                    No tasks assigned for this job. Contact your processor.
                </p>
            </div> -->

            @else
            {{-- Non-factory-employee: original layout --}}
            <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>
            <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>
            @endif

            @if(auth()->user()->role?->name === 'trades')
            {{-- Trades --}}
            <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>
            @endif

            <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>
        @endif

        @if($isFactoryEmployee && $jobs->isEmpty())
        <div class="mt-4 p-4 rounded-lg bg-amber-900/20 border border-amber-700 text-sm text-amber-300">
            <i class="fas fa-info-circle mr-2"></i>
            No jobs are currently assigned to you. Please contact your processor to assign tasks for a job.
        </div>
        @endif
    </div>
</div>
@endif

{{-- ── Factory Employee: Assigned Tasks (Manufacture Tab) ── --}}
@if($isFactoryEmployee && isset($assignments) && $assignments->count() > 0)
<div class="card mb-6">
    <div class="p-5 border-b border-slate-700 flex items-center justify-between">
        <h3><i class="fas fa-industry mr-2 text-yellow-400"></i>My Assigned Tasks</h3>
        <span class="text-xs text-slate-500">Job-wise task overview with progress</span>
        @if(!$statuscompleted)
        <a href="{{ route('timesheet.timesheetemployeecompleted') }}" class="btn btn-warning text-xs">
            Previous Completed Tasks
        </a>@endif
        @if($statuscompleted)
        <a href="{{ route('timesheet.index') }}" class="btn btn-warning text-xs">
            My Tasks
        </a>@endif
    </div>
    <div class="p-5 space-y-4">
        @foreach($assignments->groupBy('job_id') as $jobId => $jobAssignments)
        @php $jobObj = $jobAssignments->first()->job; @endphp
        <div class="rounded-xl 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-blue-900 flex items-center justify-center">
                    <i class="fas fa-briefcase text-blue-400 text-xs"></i>
                </div>
                <div>
                    <div class="text-sm font-bold text-white">{{ $jobObj?->job_number ?? 'J-?' }}</div>
                    <div class="text-xs text-slate-400">{{ $jobObj?->contact?->first_name }} {{ $jobObj?->contact?->last_name }}</div>
                </div>
            </div>
            <div class="space-y-3">
                @foreach($jobAssignments as $assignment)
                @php
                    $loggedMins = \App\Models\TimeEntry::where('user_id', $assignment->user_id)
                        ->where('job_id', $assignment->job_id)
                        ->where('task_type_id', $assignment->task_type_id)
                        ->whereIn('status', ['paused','completed'])
                        ->sum('duration_minutes');
                    // Also add current running timer if applicable
                    $runningMins = 0;
                    if ($running && $running->job_id == $assignment->job_id && $running->task_type_id == $assignment->task_type_id) {
                        $runningMins = $running->started_at->diffInMinutes(now());
                    }
                    $totalMins = $loggedMins + $runningMins;
                    $loggedHrs = round($totalMins / 60, 2);
                    $pct = ($assignment->allocated_hours > 0) ? min(100, round(($loggedHrs / $assignment->allocated_hours) * 100, 1)) : null;
                    $isRunningNow = $running && $running->job_id == $assignment->job_id && $running->task_type_id == $assignment->task_type_id;
                    $isPaused = isset($pausedEntries) && $pausedEntries->where('job_id', $assignment->job_id)->where('task_type_id', $assignment->task_type_id)->count() > 0 && !$isRunningNow;
                    $statusLabel = $assignment->task_status ?? 'pending';
                    $statusBadge = match($statusLabel) {
                        'completed'  => 'badge-green',
                        'in_progress'=> 'badge-blue',
                        'paused'     => 'badge-yellow',
                        default      => 'badge-gray',
                    };
                @endphp
                <div class="rounded-lg p-3" style="background:#1e293b;border:1px solid #2d3748;">
                    <div class="flex items-center gap-2 flex-wrap mb-2">
                        <i class="fas fa-tasks text-xs text-blue-400"></i>
                        <span class="text-sm font-medium text-white">{{ $assignment->taskType?->name ?? '—' }}</span>
                        <span class="badge {{ $statusBadge }} text-xs">{{ ucfirst(str_replace('_',' ', $statusLabel)) }}</span>
                        @if($isRunningNow)
                        <span class="flex items-center gap-1 text-xs text-green-400 ml-1">
                            <span class="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse inline-block"></span> Running
                        </span>
                        @endif
                        @if($assignment->allocated_hours)
                        <span class="text-xs text-slate-400 ml-auto">Allocated: <span class="text-white">{{ $assignment->allocated_hours }}h</span></span>
                        @endif
                    </div>

                    {{-- Progress bar --}}
                    @if($assignment->allocated_hours)
                    <div class="mb-3">
                        <div class="flex justify-between text-xs text-slate-400 mb-1">
                            <span>{{ $loggedHrs }}h logged{{ $isRunningNow ? ' (timer running)' : '' }}</span>
                            <span class="{{ $pct !== null && $pct >= 100 ? 'text-green-400 font-bold' : ($pct >= 60 ? 'text-yellow-400' : 'text-slate-400') }}">
                                {{ $pct !== null ? $pct.'%' : '—' }}
                            </span>
                        </div>
                        <div class="h-2 rounded-full bg-slate-700">
                            <div class="h-2 rounded-full transition-all {{ $pct !== null && $pct >= 100 ? 'bg-green-500' : ($pct >= 60 ? 'bg-yellow-500' : 'bg-blue-500') }}"
                                 style="width: {{ $pct ?? 0 }}%"></div>
                        </div>
                    </div>
                    @else
                    <div class="mb-3 text-xs text-slate-500">{{ $loggedHrs }}h logged — no allocated hours set</div>
                    @endif

                    {{-- Action buttons --}}
                    @if($assignment->task_status !== 'completed')
                    <div class="flex gap-2 flex-wrap">
                        @if(!$isRunningNow)
                        {{-- Resume / Start button --}}
                        <form method="POST" action="{{ route('timesheet.resume') }}">
                            @csrf
                            <input type="hidden" name="job_id" value="{{ $assignment->job_id }}">
                            <input type="hidden" name="task_type_id" value="{{ $assignment->task_type_id }}">
                            <button type="submit" class="btn btn-secondary text-xs">
                                <i class="fas fa-play text-green-400"></i>
                                {{ $isPaused ? 'Resume Timer' : 'Start Timer' }}
                            </button>
                        </form>
                        @else
                        {{-- Pause running timer --}}
                        <form method="POST" action="{{ route('timesheet.stop') }}">
                            @csrf
                            <button type="submit" class="btn btn-warning text-xs">
                                <i class="fas fa-pause"></i> Pause Timer
                            </button>
                        </form>
                        @endif

                        {{-- Complete Task button --}}
                        <form method="POST" action="{{ route('timesheet.complete-task') }}"
                              onsubmit="return confirm('Mark this task as completed? This will finalize all time entries and include them in the gross profit report.')">
                            @csrf
                            <input type="hidden" name="assignment_id" value="{{ $assignment->id }}">
                            <button type="submit" class="btn btn-success text-xs">
                                <i class="fas fa-check-circle"></i> Complete Task
                            </button>
                        </form>
                    </div>
                    @else
                    <div class="flex items-center gap-2 text-xs text-green-400">
                        <i class="fas fa-check-circle"></i> Task completed — hours included in gross profit report
                    </div>
                    @endif
                </div>
                @endforeach
            </div>
        </div>
        @endforeach
    </div>
</div>
@else
<div class="card mb-6">
    <div class="p-5 text-center text-slate-400">
        <i class="fas fa-info-circle mr-2"></i>
        No assigned tasks at the moment.

        <a href="{{ route('timesheet.timesheetemployeecompleted') }}" class="btn btn-warning text-xs">
            Previous Completed Tasks
        </a>

    </div>
</div>
@endif

{{-- ── Paused timers (non-employee users) ── --}}
@if(!$isFactoryEmployee && isset($pausedEntries) && $pausedEntries->count() > 0)
<div class="card mb-6">
    <div class="p-5 border-b border-slate-700">
        <h3><i class="fas fa-pause-circle mr-2 text-yellow-400"></i>Paused Timers</h3>
        <p class="text-xs text-slate-400 mt-0.5">These timers are paused. Resume to continue counting time.</p>
    </div>
    <div class="divide-y divide-slate-700/50">
        @foreach($pausedEntries as $paused)
        <div class="p-4 flex items-center gap-4">
            <div class="w-8 h-8 rounded-full bg-yellow-900 flex items-center justify-center flex-shrink-0">
                <i class="fas fa-pause text-yellow-400 text-xs"></i>
            </div>
            <div class="flex-1">
                <div class="text-sm font-medium text-white">{{ $paused->taskType?->name ?? '—' }}</div>
                <div class="text-xs text-slate-400">{{ $paused->job?->job_number ?? '—' }} · Paused {{ $paused->stopped_at?->diffForHumans() }}</div>
                <div class="text-xs text-yellow-400 mt-0.5">{{ $paused->elapsed }} recorded so far</div>
            </div>
            <form method="POST" action="{{ route('timesheet.resume') }}">
                @csrf
                <input type="hidden" name="job_id" value="{{ $paused->job_id }}">
                <input type="hidden" name="task_type_id" value="{{ $paused->task_type_id }}">
                <button type="submit" class="btn btn-secondary text-xs">
                    <i class="fas fa-play text-green-400"></i> Resume
                </button>
            </form>
        </div>
        @endforeach
    </div>
</div>
@endif
@if(!$isFactoryEmployee)
<!-- 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">
                        @php
                            $badge = match($entry->status) {
                                'running' => 'badge-green',
                                'paused'  => 'badge-yellow',
                                default   => 'badge-blue',
                            };
                        @endphp
                        <span class="badge {{ $badge }}">{{ 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>
@endif

<!-- 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>

    <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
