<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Student;
use App\Models\Attendance;
use App\Models\Schedule;
use App\Models\Device;
use Carbon\Carbon;

class AbsensiController extends Controller
{
    // 1. CEK STATUS ALAT (Dipanggil ESP32 tiap 5 detik)
    public function checkDeviceStatus(Request $request)
    {
        // Cari alat berdasarkan ID, kalau gak ada buat baru
        $device = Device::firstOrCreate(
            ['device_id' => $request->device_id],
            ['label' => 'New Device']
        );

        // Update biar kelihatan 'Online' di dashboard
        $device->update(['last_active' => now()]);

        return response()->json([
            'mode_registrasi' => (bool) $device->mode_registrasi,
            'nis_target' => $device->target_nis
        ]);
    }

    // 2. PROSES ABSENSI (Dipanggil saat Tap Kartu)
    public function recordAttendance(Request $request)
    {
        $uid = $request->uid;
        $timestamp = $request->timestamp; // Format: "2026-01-25 07:00:00"

        // A. Cek Kartu Terdaftar Gak?
        $student = Student::where('rfid_uid', $uid)->first();
        if (!$student) {
            return response()->json(['status' => 'error', 'message' => 'Kartu Tidak Dikenal']);
        }

        // B. Cek Hari & Jam
        $waktu = Carbon::parse($timestamp);
        $jamSekarang = $waktu->format('H:i:s');

        // Translate hari ke Bahasa Indonesia (sesuai database jadwal)
        $hariMap = [
            'Sunday' => 'minggu',
            'Monday' => 'senin',
            'Tuesday' => 'selasa',
            'Wednesday' => 'rabu',
            'Thursday' => 'kamis',
            'Friday' => 'jumat',
            'Saturday' => 'sabtu'
        ];
        $hariIni = $hariMap[$waktu->format('l')];

        // C. Cari Jadwal Aktif
        $schedule = Schedule::where('class', $student->class)
            ->where('day', $hariIni)
            ->where('start_time', '<=', $jamSekarang)
            ->where('end_time', '>=', $jamSekarang)
            ->first();

        if (!$schedule) {
            return response()->json(['status' => 'error', 'message' => 'Tidak Ada Jadwal']);
        }

        // D. Cek Apakah Sudah Absen Hari Ini?
        $cekAbsen = Attendance::where('student_id', $student->id)
            ->where('date', $waktu->format('Y-m-d'))
            ->where('schedule_id', $schedule->id)
            ->first();

        if ($cekAbsen) {
            return response()->json([
                'status' => 'success',
                'data' => ['nama' => $student->name, 'mapel' => $schedule->subject, 'type' => 'SUDAH'],
                'message' => 'Sudah Absen Tadi'
            ]);
        }

        // E. Simpan Absen Masuk
        Attendance::create([
            'student_id' => $student->id,
            'schedule_id' => $schedule->id,
            'date' => $waktu->format('Y-m-d'),
            'check_in' => $jamSekarang,
            'status' => 'HADIR'
        ]);

        return response()->json([
            'status' => 'success',
            'data' => ['nama' => $student->name, 'mapel' => $schedule->subject, 'type' => 'MASUK'],
            'message' => 'Berhasil Masuk'
        ]);
    }

    // 3. REGISTRASI KARTU BARU
    public function registerCard(Request $request)
    {
        $existing = Student::where('rfid_uid', $request->uid)->exists();
        if ($existing) {
            return response()->json(['status' => 'error', 'message' => 'Kartu Sudah Dipakai']);
        }

        $student = Student::where('nis', $request->nis)->first();
        if ($student) {
            $student->update(['rfid_uid' => $request->uid]);

            // Matikan mode registrasi
            Device::where('device_id', $request->device_id)->update(['mode_registrasi' => false, 'target_nis' => null]);

            return response()->json(['status' => 'success', 'message' => 'Kartu Terdaftar']);
        }

        return response()->json(['status' => 'error', 'message' => 'NIS Tidak Ditemukan']);
    }
}
