@extends('layouts.app')

@section('title', 'Attendance Management')

@section('content')
<div class="space-y-6" x-data="{ correction: null }">
    <header class="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div><p class="text-xs font-bold uppercase tracking-[.18em] text-emerald-600">Employees & HR</p><h1 class="mt-1 text-3xl font-bold text-slate-950">Attendance control</h1><p class="mt-1 text-sm text-slate-500">Manual, web, manager, import, biometric and API-ready records with preserved correction history.</p></div>
        <div class="flex gap-2"><a href="{{ route('app.shifts.index') }}" class="rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-bold text-slate-700">Manage shifts</a><a href="{{ route('app.leave.index') }}" class="rounded-xl bg-emerald-600 px-4 py-2.5 text-sm font-bold text-white">Leave center</a></div>
    </header>

    @if(auth()->user()->employee_id)
    <section class="flex flex-col gap-3 rounded-2xl border border-emerald-200 bg-emerald-50 p-4 sm:flex-row sm:items-center sm:justify-between">
        <div><h2 class="font-bold text-slate-950">My attendance today</h2><p class="text-xs text-slate-600">Authenticated web punches are time-stamped and retained in the audit log.</p></div>
        <form method="POST" action="{{ route('app.attendance.punch') }}" class="flex gap-2">@csrf<button name="action" value="check_in" class="rounded-xl bg-emerald-600 px-4 py-2.5 text-xs font-bold text-white">Check in now</button><button name="action" value="check_out" class="rounded-xl border border-emerald-300 bg-white px-4 py-2.5 text-xs font-bold text-emerald-800">Check out now</button></form>
    </section>
    @endif

    <section class="grid gap-3 sm:grid-cols-2 xl:grid-cols-7">
        @foreach([['Total employees',$stats['total'],'slate'],['Present',$stats['present'],'emerald'],['Absent',$stats['absent'],'rose'],['Late',$stats['late'],'amber'],['On leave',$stats['on_leave'],'sky'],['Not checked in',$stats['not_checked_in'],'amber'],['Overtime',intdiv($stats['overtime_minutes'],60).'h '.($stats['overtime_minutes']%60).'m','violet']] as [$label,$value,$tone])
        <div class="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm"><p class="text-xs font-semibold text-slate-500">{{ $label }}</p><p class="mt-2 text-2xl font-bold text-{{ $tone }}-600">{{ $value }}</p></div>
        @endforeach
    </section>

    @if(auth()->check() && auth()->user()->hasPermission('attendance.manage'))
    <section class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
        <div class="flex items-center justify-between"><div><h2 class="text-lg font-bold text-slate-950">Record attendance</h2><p class="text-xs text-slate-500">Scheduled time and payroll metrics are calculated from the assigned shift.</p></div><span class="rounded-full bg-emerald-50 px-3 py-1 text-xs font-bold text-emerald-700">{{ $stats['overtime_minutes'] }} OT minutes today</span></div>
        <form method="POST" action="{{ route('app.attendance.store') }}" class="mt-4 grid gap-3 lg:grid-cols-4">
            @csrf
            <label class="text-xs font-semibold text-slate-700">Employee<select name="employee_id" required class="erp-input mt-1"><option value="">Choose employee</option>@foreach($employees as $employee)<option value="{{ $employee->id }}">{{ $employee->employee_code }} · {{ $employee->full_name }}</option>@endforeach</select></label>
            <label class="text-xs font-semibold text-slate-700">Date<input type="date" name="attendance_date" value="{{ today()->format('Y-m-d') }}" required class="erp-input mt-1"></label>
            <label class="text-xs font-semibold text-slate-700">Shift override<select name="shift_id" class="erp-input mt-1"><option value="">Use assigned shift</option>@foreach($shifts as $shift)<option value="{{ $shift->id }}">{{ $shift->name }}</option>@endforeach</select></label>
            <label class="text-xs font-semibold text-slate-700">Status<select name="status" class="erp-input mt-1">@foreach(['present','absent','late','early_leave','half_day','on_leave','holiday','weekly_off','work_from_home','business_visit'] as $status)<option value="{{ $status }}">{{ ucfirst(str_replace('_',' ',$status)) }}</option>@endforeach</select></label>
            <label class="text-xs font-semibold text-slate-700">Check in<input type="datetime-local" name="actual_check_in" class="erp-input mt-1"></label>
            <label class="text-xs font-semibold text-slate-700">Check out<input type="datetime-local" name="actual_check_out" class="erp-input mt-1"></label>
            <label class="text-xs font-semibold text-slate-700">Source<select name="source" class="erp-input mt-1">@foreach(['manual','web','manager','import','biometric','api'] as $source)<option value="{{ $source }}">{{ ucfirst($source) }}</option>@endforeach</select></label>
            <button class="self-end rounded-xl bg-emerald-600 px-4 py-3 text-sm font-bold text-white">Save attendance</button>
            <textarea name="notes" rows="2" class="erp-input lg:col-span-4" placeholder="Notes or source reference"></textarea>
        </form>
        <div class="mt-5 border-t border-slate-200 pt-5">
            <div class="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between"><div><h3 class="font-bold text-slate-950">Import attendance CSV</h3><p class="text-xs text-slate-500">Required headers: employee_code, attendance_date. Optional: check_in, check_out, status, notes. Maximum 1,000 rows.</p></div><form method="POST" action="{{ route('app.attendance.import') }}" enctype="multipart/form-data" class="flex flex-col gap-2 sm:flex-row">@csrf<input type="file" name="attendance_file" accept=".csv,text/csv" required class="erp-input"><button class="rounded-xl bg-slate-900 px-4 py-2.5 text-xs font-bold text-white">Validate & import</button></form></div>
            @if(session('attendance_import_errors'))<div class="mt-3 rounded-xl border border-amber-200 bg-amber-50 p-3 text-xs text-amber-900"><strong>Rows needing attention</strong><ul class="mt-2 list-disc pl-5">@foreach(session('attendance_import_errors') as $importError)<li>{{ $importError }}</li>@endforeach</ul></div>@endif
        </div>
    </section>
    @endif

    @if($corrections->isNotEmpty())
    <section class="rounded-2xl border border-amber-200 bg-amber-50/60 p-5">
        <h2 class="font-bold text-amber-950">Pending attendance corrections</h2>
        <div class="mt-3 grid gap-3 lg:grid-cols-2">@foreach($corrections as $correction)<article class="rounded-xl border border-amber-200 bg-white p-4"><div class="flex justify-between gap-3"><div><p class="font-bold text-slate-900">{{ $correction->employee->full_name }}</p><p class="text-xs text-slate-500">{{ $correction->attendanceRecord->attendance_date->format('d M Y') }} · {{ $correction->reason }}</p></div><span class="text-xs font-bold text-amber-700">Requested</span></div>@if(auth()->check() && auth()->user()->hasPermission('attendance.approve'))<form method="POST" action="{{ route('app.attendance.corrections.review', $correction) }}" class="mt-3 flex gap-2">@csrf<input name="review_comment" class="erp-input flex-1" placeholder="Review comment"><button name="decision" value="approved" class="rounded-lg bg-emerald-600 px-3 text-xs font-bold text-white">Approve</button><button name="decision" value="rejected" class="rounded-lg bg-rose-600 px-3 text-xs font-bold text-white">Reject</button></form>@endif</article>@endforeach</div>
    </section>
    @endif

    <section class="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
        <form method="GET" class="flex flex-col gap-3 border-b border-slate-200 bg-slate-50 p-4 md:flex-row md:items-end">
            <label class="text-xs font-semibold text-slate-700">Reference date<input type="date" name="date" value="{{ $date->format('Y-m-d') }}" class="erp-input mt-1"></label>
            <label class="text-xs font-semibold text-slate-700">View<select name="view" class="erp-input mt-1">@foreach(['daily','weekly','monthly','calendar'] as $option)<option value="{{ $option }}" @selected($view===$option)>{{ ucfirst($option) }}</option>@endforeach</select></label>
            <label class="text-xs font-semibold text-slate-700">Employee<select name="employee_id" class="erp-input mt-1"><option value="">All employees</option>@foreach($employees as $employee)<option value="{{ $employee->id }}" @selected(request('employee_id')==$employee->id)>{{ $employee->full_name }}</option>@endforeach</select></label>
            <label class="text-xs font-semibold text-slate-700">Status<select name="status" class="erp-input mt-1"><option value="">All statuses</option>@foreach(['present','absent','late','on_leave','half_day','work_from_home'] as $status)<option value="{{ $status }}" @selected(request('status')===$status)>{{ ucfirst(str_replace('_',' ',$status)) }}</option>@endforeach</select></label>
            <button class="rounded-xl bg-slate-900 px-4 py-2.5 text-xs font-bold text-white">Apply filters</button>
        </form>
        @if($view === 'calendar')
        <div class="border-b border-slate-200 p-4"><div class="mb-3 grid grid-cols-7 text-center text-[10px] font-bold uppercase tracking-wider text-slate-400">@foreach(['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] as $weekday)<span>{{ $weekday }}</span>@endforeach</div><div class="grid grid-cols-7 gap-1">@for($blank = 1; $blank < $date->copy()->startOfMonth()->dayOfWeekIso; $blank++)<span class="min-h-20 rounded-lg bg-slate-50"></span>@endfor @foreach($calendarDays as $calendarDay) @php($dayRecords = $calendarSummary->get($calendarDay->toDateString(), collect()))<article class="min-h-20 rounded-lg border border-slate-200 bg-white p-2"><strong class="text-xs text-slate-900">{{ $calendarDay->day }}</strong><p class="mt-2 text-[10px] font-bold text-emerald-700">{{ $dayRecords->whereIn('status',['present','late','early_leave','half_day','work_from_home','business_visit'])->count() }} present</p><p class="text-[10px] text-rose-700">{{ $dayRecords->where('status','absent')->count() }} absent</p><p class="text-[9px] text-slate-400">{{ $dayRecords->count() }} records</p></article>@endforeach</div></div>
        @endif
        <div class="overflow-x-auto"><table class="erp-table"><thead><tr><th>Employee</th><th>Date / shift</th><th>Check in</th><th>Check out</th><th>Worked</th><th>Late</th><th>Early</th><th>OT</th><th>Status</th><th>Action</th></tr></thead><tbody>
        @forelse($records as $record)<tr><td><a href="{{ route('app.employees.show',$record->employee) }}" class="font-bold text-slate-900 hover:text-emerald-700">{{ $record->employee->full_name }}</a><small>{{ $record->employee->employee_code }} · {{ $record->employee->branch?->name }}</small></td><td><strong>{{ $record->attendance_date->format('d M Y') }}</strong><small>{{ $record->shift?->name ?? 'No shift' }}</small></td><td>{{ $record->actual_check_in?->format('H:i') ?? '—' }}</td><td>{{ $record->actual_check_out?->format('H:i') ?? '—' }}</td><td>{{ intdiv($record->worked_minutes,60) }}h {{ $record->worked_minutes%60 }}m</td><td class="text-amber-700">{{ $record->late_minutes }}m</td><td class="text-rose-700">{{ $record->early_leave_minutes }}m</td><td class="text-emerald-700">{{ $record->overtime_minutes }}m</td><td><span class="rounded-full bg-slate-100 px-2.5 py-1 text-[10px] font-bold uppercase">{{ str_replace('_',' ',$record->status) }}</span></td><td><button type="button" @click="correction = correction === {{ $record->id }} ? null : {{ $record->id }}" class="text-xs font-bold text-emerald-700">Correction</button></td></tr>
        <tr x-show="correction === {{ $record->id }}" x-cloak><td colspan="10"><form method="POST" action="{{ route('app.attendance.corrections.store',$record) }}" class="grid gap-2 rounded-xl bg-slate-50 p-3 md:grid-cols-4">@csrf<input type="datetime-local" name="requested_check_in" value="{{ $record->actual_check_in?->format('Y-m-d\TH:i') }}" class="erp-input"><input type="datetime-local" name="requested_check_out" value="{{ $record->actual_check_out?->format('Y-m-d\TH:i') }}" class="erp-input"><input name="reason" required minlength="5" placeholder="Reason for correction" class="erp-input"><button class="rounded-xl bg-slate-900 text-xs font-bold text-white">Submit correction</button></form></td></tr>
        @empty<tr><td colspan="10" class="py-14 text-center"><strong>No attendance records</strong><small>Use Record Attendance or change the date and filters.</small></td></tr>@endforelse
        </tbody></table></div><div class="border-t border-slate-200 p-4">{{ $records->links() }}</div>
    </section>
</div>
@endsection
