<?php
namespace App\Http\Controllers;

use App\Models\Attendance;
use App\Models\Employee;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;

class AttendanceController extends Controller
{
    public function index(): View { return view('attendance.index', ['attendances' => Attendance::with('employee')->latest()->paginate(12)]); }

    public function create(): View
    {
        $today = today()->toDateString();
        $employees = Employee::where('status', 'active')->with(['attendances' => fn ($query) => $query->whereDate('attendance_date', $today)])->orderBy('full_name')->get();
        return view('attendance.create', compact('employees'));
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate(['employee_id'=>'required|exists:employees,id','attendance_date'=>'required|date','latitude'=>'required|numeric','longitude'=>'required|numeric','location_name'=>'required','photo_data'=>'required|string']);
        $date = Carbon::parse($data['attendance_date'])->toDateString();
        $attendance = Attendance::where('employee_id', $data['employee_id'])->whereDate('attendance_date', $date)->first();
        $photoPath = $this->storePhoto($data['photo_data']);

        if (!$attendance) {
            Attendance::create(['employee_id'=>$data['employee_id'], 'attendance_date'=>$date, 'check_in'=>now(), 'photo_path'=>$photoPath, 'latitude'=>$data['latitude'], 'longitude'=>$data['longitude'], 'location_name'=>$data['location_name'], 'status'=>now()->format('H:i:s') > '08:00:00' ? 'late' : 'present']);
            return redirect()->route('attendance.index')->with('success', 'Absen masuk berhasil disimpan.');
        }

        if ($attendance->check_in && !$attendance->check_out) {
            $attendance->update(['check_out'=>now(), 'checkout_photo_path'=>$photoPath, 'checkout_latitude'=>$data['latitude'], 'checkout_longitude'=>$data['longitude'], 'checkout_location_name'=>$data['location_name']]);
            return redirect()->route('attendance.index')->with('success', 'Absen pulang berhasil disimpan.');
        }

        return redirect()->route('attendance.index')->with('warning', 'Absensi hari ini sudah lengkap. Tidak perlu absen lagi.');
    }

    private function storePhoto(string $photoData): string
    {
        if (!preg_match('/^data:image\/(jpeg|png);base64,(.+)$/', $photoData, $matches)) abort(422, 'Format foto tidak valid.');
        $filename = 'attendance/' . Str::uuid() . '.' . $matches[1];
        \Storage::disk('public')->put($filename, base64_decode(str_replace(' ', '+', $matches[2])));
        return $filename;
    }

    public function update(Request $request, Attendance $attendance): RedirectResponse { $attendance->update($request->validate(['check_out'=>'nullable|date','status'=>'required|in:present,late,absent,leave','notes'=>'nullable'])); return back()->with('success', 'Absensi diperbarui.'); }
    public function destroy(Attendance $attendance): RedirectResponse { $attendance->delete(); return back()->with('success', 'Data absensi dihapus.'); }
}
