<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\{SiswaMagang, Attendance, Holiday};
use Carbon\Carbon;
use RealRashid\SweetAlert\Facades\Alert;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class RFIDController extends Controller
{
    /**
     * Halaman RFID Masuk (view)
     */
    public function rfidMasuk()
    {
        $todayAttendance = Attendance::with('user.siswa')
            ->whereDate('date', Carbon::today('Asia/Jakarta'))
            ->whereNotNull('check_in_time')
            ->orderBy('check_in_time', 'desc')
            ->paginate(2);

        return view('admin.rfid.masuk', compact('todayAttendance'));
    }

    /**
     * Halaman RFID Pulang (view)
     */
    public function rfidPulang()
    {
        $todayAttendance = Attendance::with('user.siswa')
            ->whereDate('date', Carbon::today('Asia/Jakarta'))
            ->whereNotNull('check_out_time')
            ->orderBy('check_out_time', 'desc')
            ->paginate(2);

        return view('admin.rfid.pulang', compact('todayAttendance'));
    }

    /**
     * Proses presensi masuk (bisa AJAX atau non-AJAX)
     */
    public function processMasuk(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'rfid_number' => 'required|string'
        ]);

        // Jika request mengharapkan JSON (AJAX), kembalikan error 422
        if ($validator->fails()) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validasi gagal',
                    'errors' => $validator->errors()
                ], 422);
            }

            // fallback non-AJAX
            Alert::error('Gagal', $validator->errors()->first());
            return back()->withInput();
        }

        try {
            $rfid = $request->input('rfid_number');
            $siswa = SiswaMagang::where('rfid_number', $rfid)->first();

            if (!$siswa) {
                $msg = 'RFID tidak terdaftar! Silakan daftarkan RFID ini di Data Siswa Magang.';
                if ($request->expectsJson()) {
                    return response()->json(['success' => false, 'message' => $msg], 400);
                }
                Alert::error('Gagal', $msg);
                return back();
            }

            if (!$siswa->user) {
                $msg = 'Siswa belum memiliki akun user!';
                if ($request->expectsJson()) {
                    return response()->json(['success' => false, 'message' => $msg], 400);
                }
                Alert::error('Gagal', $msg);
                return back();
            }

            // cek hari libur dengan timezone Asia/Jakarta
            $today = Carbon::today('Asia/Jakarta');
            if (Holiday::isHoliday($today)) {
                $msg = 'Hari ini adalah hari libur, presensi tidak dapat dilakukan';
                if ($request->expectsJson()) {
                    return response()->json(['success' => false, 'message' => $msg], 400);
                }
                Alert::warning('Libur', $msg);
                return back();
            }

            $now = Carbon::now('Asia/Jakarta');

            // create atau ambil record attendance untuk user + date
            $attendance = Attendance::firstOrCreate(
                ['user_id' => $siswa->user->id, 'date' => $today->toDateString()],
                ['status' => 'hadir']
            );

            if ($attendance->check_in_time) {
                $msg = $siswa->nama_siswa . ' sudah melakukan presensi masuk hari ini';
                if ($request->expectsJson()) {
                    return response()->json(['success' => false, 'message' => $msg], 409);
                }
                Alert::info('Info', $msg);
                return back();
            }

            $attendance->update([
                'status' => 'hadir',
                'check_in_time' => $now
            ]);

            $successData = [
                'nama' => $siswa->nama_siswa,
                'waktu' => $now->format('H:i:s'),
                'status' => 'Masuk'
            ];

            $msg = 'Presensi masuk berhasil untuk ' . $siswa->nama_siswa . ' pada ' . $now->format('H:i:s');

            if ($request->expectsJson()) {
                return response()->json(['success' => true, 'message' => $msg, 'data' => $successData], 200);
            }

            // fallback non-AJAX: gunakan SweetAlert flash dari RealRashid
            Alert::success('Berhasil', $msg);
            return back();

        } catch (\Throwable $e) {
            Log::error('RFID Masuk Error: '.$e->getMessage(), ['trace' => $e->getTraceAsString()]);
            $msg = 'Terjadi kesalahan sistem, coba lagi nanti.';
            if ($request->expectsJson()) {
                return response()->json(['success' => false, 'message' => $msg], 500);
            }
            Alert::error('Error', $msg);
            return back();
        }
    }

    /**
     * Proses presensi pulang (bisa AJAX atau non-AJAX)
     */
    public function processPulang(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'rfid_number' => 'required|string'
        ]);

        if ($validator->fails()) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validasi gagal',
                    'errors' => $validator->errors()
                ], 422);
            }

            Alert::error('Gagal', $validator->errors()->first());
            return back()->withInput();
        }

        try {
            $rfid = $request->input('rfid_number');
            $siswa = SiswaMagang::where('rfid_number', $rfid)->first();

            if (!$siswa) {
                $msg = 'RFID tidak terdaftar! Silakan daftarkan RFID ini di Data Siswa Magang.';
                if ($request->expectsJson()) {
                    return response()->json(['success' => false, 'message' => $msg], 400);
                }
                Alert::error('Gagal', $msg);
                return back();
            }

            if (!$siswa->user) {
                $msg = 'Siswa belum memiliki akun user!';
                if ($request->expectsJson()) {
                    return response()->json(['success' => false, 'message' => $msg], 400);
                }
                Alert::error('Gagal', $msg);
                return back();
            }

            $today = Carbon::today('Asia/Jakarta');
            $now = Carbon::now('Asia/Jakarta');

            $attendance = Attendance::where('user_id', $siswa->user->id)
                                   ->whereDate('date', $today->toDateString())
                                   ->first();

            if (!$attendance || !$attendance->check_in_time) {
                $msg = $siswa->nama_siswa . ' belum melakukan presensi masuk hari ini';
                if ($request->expectsJson()) {
                    return response()->json(['success' => false, 'message' => $msg], 409);
                }
                Alert::info('Info', $msg);
                return back();
            }

            if ($attendance->check_out_time) {
                $msg = $siswa->nama_siswa . ' sudah melakukan presensi pulang hari ini';
                if ($request->expectsJson()) {
                    return response()->json(['success' => false, 'message' => $msg], 409);
                }
                Alert::info('Info', $msg);
                return back();
            }

            // aturan minimal jam pulang (misal 16:00)
            $minimumCheckoutTime = Carbon::today('Asia/Jakarta')->setHour(16)->setMinute(0)->setSecond(0);
            if ($now->lt($minimumCheckoutTime)) {
                $msg = 'Presensi pulang hanya bisa dilakukan mulai jam 16:00';
                if ($request->expectsJson()) {
                    return response()->json(['success' => false, 'message' => $msg], 400);
                }
                Alert::warning('Belum Waktu', $msg);
                return back();
            }

            $attendance->update(['check_out_time' => $now]);

            $successData = [
                'nama' => $siswa->nama_siswa,
                'waktu' => $now->format('H:i:s'),
                'status' => 'Pulang'
            ];

            $msg = 'Presensi pulang berhasil untuk ' . $siswa->nama_siswa . ' pada ' . $now->format('H:i:s');

            if ($request->expectsJson()) {
                return response()->json(['success' => true, 'message' => $msg, 'data' => $successData], 200);
            }

            Alert::success('Berhasil', $msg);
            return back();

        } catch (\Throwable $e) {
            Log::error('RFID Pulang Error: '.$e->getMessage(), ['trace' => $e->getTraceAsString()]);
            $msg = 'Terjadi kesalahan sistem, coba lagi nanti.';
            if ($request->expectsJson()) {
                return response()->json(['success' => false, 'message' => $msg], 500);
            }
            Alert::error('Error', $msg);
            return back();
        }
    }
}