<?php

namespace App\Http\Controllers\Guru;

use App\Http\Controllers\Controller;
use App\Models\TeacherAttendance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class AbsenMandiriController extends Controller
{
    public function index()
    {
        $teacher = Auth::user()->teacher;

        if (!$teacher) {
            return redirect()->route('guru.dashboard')
                ->with('error', 'Data guru tidak ditemukan. Hubungi administrator.');
        }

        // Cek apakah sudah absen hari ini
        $absenHariIni = TeacherAttendance::where('teacher_id', $teacher->id)
            ->whereDate('date', today())
            ->first();

        // Riwayat absen 7 hari terakhir
        $riwayat = TeacherAttendance::where('teacher_id', $teacher->id)
            ->whereDate('date', '>=', now()->subDays(6))
            ->orderByDesc('date')
            ->get();

        return view('guru.absen.mandiri', compact('teacher', 'absenHariIni', 'riwayat'));
    }

    public function store(Request $request)
    {
        $teacher = Auth::user()->teacher;

        if (!$teacher) {
            return back()->with('error', 'Data guru tidak ditemukan.');
        }

        $request->validate([
            'photo_data'       => 'required|string',   // base64 dari kamera
            'latitude'         => 'required|numeric',
            'longitude'        => 'required|numeric',
            'location_address' => 'nullable|string|max:500',
            'status'           => 'required|in:hadir,sakit,izin,dinas_luar',
            'notes'            => 'nullable|string|max:500',
        ]);

        // Simpan foto dari base64
        $photoPath = null;
        $base64    = $request->photo_data;

        // Hapus header data:image/jpeg;base64,
        if (str_contains($base64, ',')) {
            $base64 = explode(',', $base64)[1];
        }

        $imageData = base64_decode($base64);
        if ($imageData !== false && strlen($imageData) > 0) {
            $folder    = 'absensi/' . now()->format('Y/m');
            $filename  = 'guru_' . $teacher->id . '_' . now()->format('Ymd_His') . '.jpg';
            $path      = $folder . '/' . $filename;

            Storage::disk('public')->makeDirectory($folder);
            Storage::disk('public')->put($path, $imageData);
            $photoPath = $path;
        }

        // Simpan atau update absensi hari ini
        TeacherAttendance::updateOrCreate(
            [
                'teacher_id' => $teacher->id,
                'date'       => today(),
            ],
            [
                'status'           => $request->status,
                'notes'            => $request->notes,
                'photo_path'       => $photoPath,
                'latitude'         => $request->latitude,
                'longitude'        => $request->longitude,
                'location_address' => $request->location_address,
                'check_in_time'    => now()->format('H:i:s'),
            ]
        );

        return back()->with('success', 'Absensi berhasil dicatat pada ' . now()->format('H:i') . ' WIB.');
    }
}
