<?php

namespace App\Controllers;

use App\Controllers\Base\AttendanceDailyStudentController as BaseController;
use App\Resources\AttendanceDailyStudentResource;
use Wibiesana\Padi\Core\Database;

class AttendanceDailyStudentController extends BaseController
{
    /**
     * Get all attendance daily students with filters
     * GET /attendance-daily-student
     */
    public function index()
    {
        $page = max(1, (int)$this->request->query('page', 1));
        $requestedPerPage = (int)$this->request->query('per-page', 10);
        $perPage = $requestedPerPage === 0 ? 1000 : min(2000, max(1, $requestedPerPage));

        $filters = [
            'date' => $this->request->query('date'),
            'start_date' => $this->request->query('start_date'),
            'end_date' => $this->request->query('end_date'),
            'class_id' => $this->request->query('class_id'),
            'semester_id' => $this->request->query('semester_id'),
            'student_id' => $this->request->query('student_id'),
            'status' => $this->request->query('status'),
            'search' => $this->request->query('search')
        ];

        // Permission Check for Student with 'absensi' role
        $user = \Wibiesana\Padi\Core\Auth::user();
        if ($user && ($user->role === 'student' || (int)$user->role === 4)) {
            // Check if they have 'absensi' role
            $hasAbsensiRole = \App\Models\UserRole::findQuery()
                ->innerJoin('role', 'user_role.role_id = role.id')
                ->where(['user_role.user_id' => $user->user_id])
                ->andWhere(['role.name' => 'absensi'])
                ->exists();

            if ($hasAbsensiRole) {
                // Get their class
                $member = \App\Models\ClassroomMember::findQuery()->where(['student_id' => $user->user_id])->one();
                if ($member) {
                    $filters['class_id'] = $member['class_id'];
                } else {
                    return $this->response->json(['data' => [], 'meta' => ['total' => 0]]);
                }
            } else if ($user->role === 'student') {
                // Regular student can only see their own attendance
                $filters['student_id'] = $user->user_id;
            }
        }

        $result = $this->model->filterPaginate($filters, $page, $perPage);
        return AttendanceDailyStudentResource::collection($result);
    }

    /**
     * Save batch attendance
     * POST /attendance-daily-students/batch
     */
    public function batchStore()
    {
        $payload = $this->request->all();
        $items = $payload['items'] ?? [];
        $date = $payload['attendance_date'] ?? date('Y-m-d');

        if (empty($items)) {
            return $this->response->json(['message' => 'No items provided'], 400);
        }

        $classId = $payload['class_id'] ?? null;
        if (!$classId) {
            return $this->response->json(['message' => 'Class ID is required'], 400);
        }

        // Permission Check
        $user = \Wibiesana\Padi\Core\Auth::user();
        if ($user && $user->role !== 'superadmin' && $user->role !== 'admin') {
            $isAuthorized = false;

            // Check if Teacher/Homeroom
            if ($user->role === 'teacher' || (int)$user->role === 2) {
                $classroom = \App\Models\Classroom::findQuery()->where([
                    'id' => $classId,
                    'teacher_id' => $user->user_id
                ])->one();
                if ($classroom) $isAuthorized = true;
            } 
            // Check if Student with 'absensi' role
            else if ($user->role === 'student' || (int)$user->role === 4) {
                // Check if they have 'absensi' role in user_role table
                $hasAbsensiRole = \App\Models\UserRole::findQuery()
                    ->innerJoin('role', 'user_role.role_id = role.id')
                    ->where(['user_role.user_id' => $user->user_id])
                    ->andWhere(['role.name' => 'absensi'])
                    ->exists();

                if ($hasAbsensiRole) {
                    // Check if they belong to this class
                    $isMember = \App\Models\ClassroomMember::findQuery()->where([
                        'student_id' => $user->user_id,
                        'class_id' => $classId
                    ])->exists();
                    if ($isMember) $isAuthorized = true;
                }
            }

            if (!$isAuthorized) {
                return $this->response->json(['message' => 'Unauthorized access to this class'], 403);
            }
        }

        try {
            return Database::transaction(function () use ($items, $date) {
                foreach ($items as $item) {
                    $studentId = $item['student_id'];
                    $status = $item['status'];
                    $note = $item['note'] ?? '';

                    $existing = $this->model->findQuery()->where([
                        'student_id' => $studentId,
                        'attendance_date' => $date
                    ])->one();

                    if ($existing) {
                        $this->model->update($existing['id'], [
                            'status' => $status,
                            'note' => $note,
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                    } else {
                        $this->model->create([
                            'student_id' => $studentId,
                            'attendance_date' => $date,
                            'status' => $status,
                            'note' => $note
                        ]);
                    }
                }
                return ['success' => true, 'message' => 'Batch attendance saved successfully'];
            });
        } catch (\Exception $e) {
            return $this->response->json(['message' => 'Failed to save batch attendance: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Store a single attendance record
     * POST /attendance-daily-student
     */
    public function store()
    {
        $data = $this->request->all();

        // Validate required fields
        if (empty($data['student_id']) || empty($data['attendance_date'])) {
            return $this->response->json(['message' => 'Student ID and Attendance Date are required'], 400);
        }

        // Check for existing record
        $existing = $this->model->findQuery()->where([
            'student_id' => $data['student_id'],
            'attendance_date' => $data['attendance_date']
        ])->one();

        if ($existing) {
            // Update existing record
            $updateData = [
                'status' => $data['status'] ?? $existing['status'],
                'note' => $data['note'] ?? $existing['note'],
                // Add check_in/out if needed
                /*'check_in_time' => $data['check_in_time'] ?? $existing['check_in_time'],
                 'check_out_time' => $data['check_out_time'] ?? $existing['check_out_time'],*/
                'updated_at' => date('Y-m-d H:i:s')
            ];

            $result = $this->model->update($existing['id'], $updateData);

            // Fetch updated resource to return consistent structure
            $updated = $this->model->findQuery()->where(['id' => $existing['id']])->one();
            if ($updated) {
                $temp = [$updated];
                $this->model->loadStudent($temp);
                $updated = $temp[0];
            }
            return new AttendanceDailyStudentResource($updated);
        } else {
            // Create new record
            $id = $this->model->create([
                'student_id' => $data['student_id'],
                'attendance_date' => $data['attendance_date'],
                'status' => $data['status'] ?? 1,
                'note' => $data['note'] ?? ''
            ]);

            $newRecord = $this->model->findQuery()->where(['id' => $id])->one();
            if ($newRecord) {
                $temp = [$newRecord];
                $this->model->loadStudent($temp);
                $newRecord = $temp[0];
            }
            return new AttendanceDailyStudentResource($newRecord);
        }
    }

    /**
     * Get attendance summary by date
     * GET /attendance-daily-student/summary
     */
    public function summary()
    {
        $filters = [
            'start_date' => $this->request->query('start_date'),
            'end_date' => $this->request->query('end_date'),
            'class_id' => $this->request->query('class_id')
        ];

        // Permission Check for Teacher
        $user = \Wibiesana\Padi\Core\Auth::user();
        if ($user && $user->role === 'teacher') {
            // Find teacher's classroom
            $classroom = \App\Models\Classroom::findQuery()->where([
                'teacher_id' => $user->user_id
            ])->one();
            
            if ($classroom) {
                $filters['class_id'] = $classroom['id'];
            } else {
                // If teacher has no classroom, return empty summary
                return $this->response->json(['data' => []]);
            }
        } else if ($user && ($user->role === 'student' || (int)$user->role === 4)) {
            // Check if they have 'absensi' role
            $hasAbsensiRole = \App\Models\UserRole::findQuery()
                ->innerJoin('role', 'user_role.role_id = role.id')
                ->where(['user_role.user_id' => $user->user_id])
                ->andWhere(['role.name' => 'absensi'])
                ->exists();

            if ($hasAbsensiRole) {
                $member = \App\Models\ClassroomMember::findQuery()->where(['student_id' => $user->user_id])->one();
                if ($member) {
                    $filters['class_id'] = $member['class_id'];
                } else {
                    return $this->response->json(['data' => []]);
                }
            } else {
                // Regular students don't see the summary
                return $this->response->json(['data' => []]);
            }
        }

        $result = $this->model->getSummary($filters);
        return $this->response->json(['data' => $result]);
    }

    /**
     * Get daily attendance info by QR token
     * GET /attendance-daily-student/qr-info?token=xxx
     */
    public function qrInfo()
    {
        $token = $this->request->query('token');
        if (empty($token)) {
            return $this->response->json(['success' => false, 'message' => 'Token is required'], 400);
        }

        $settingModel = new \App\Models\Setting();
        $setting = $settingModel->findBuilder()->where(['status' => 1])->one();
        $config = $setting ? json_decode($setting['setting'], true) : [];
        $savedToken = $config['daily_attendance_qr_token'] ?? null;

        if (!$savedToken || $token !== $savedToken) {
            return $this->response->json(['success' => false, 'message' => 'QR Code tidak valid'], 404);
        }

        return $this->response->json([
            'success' => true,
            'item' => [
                'type' => 'daily_attendance',
                'date' => date('Y-m-d'),
                'school_name' => $config['school_name'] ?? 'School'
            ],
        ]);
    }

    /**
     * Student daily self-attendance via QR token
     * POST /attendance-daily-student/self-attendance
     */
    public function selfAttendance()
    {
        $user = \Wibiesana\Padi\Core\Auth::user();
        $userId = is_array($user) ? ($user['id'] ?? $user['user_id'] ?? null) : ($user->id ?? $user->user_id ?? null);

        $validated = $this->validate([
            'qr_token' => 'required|string',
        ]);

        $settingModel = new \App\Models\Setting();
        $setting = $settingModel->findBuilder()->where(['status' => 1])->one();
        $config = $setting ? json_decode($setting['setting'], true) : [];
        $savedToken = $config['daily_attendance_qr_token'] ?? null;

        if (!$savedToken || $validated['qr_token'] !== $savedToken) {
            return $this->response->json(['success' => false, 'message' => 'QR Code tidak valid'], 404);
        }

        $today = date('Y-m-d');
        
        $mode = $config['student_attendance_mode'] ?? $config['daily_attendance_mode'] ?? 'presence_only';

        if ($mode === 'off') {
            return $this->response->json(['success' => false, 'message' => 'Fitur absensi harian sedang dinonaktifkan'], 403);
        }

        $today = date('Y-m-d');
        $now = date('Y-m-d H:i:s');
        
        // Check if already attended
        $existing = $this->model->findQuery()
            ->where(['student_id' => $userId])
            ->andWhere(['attendance_date' => $today])
            ->one();

        if ($mode === 'check_in_out') {
            if ($existing && !empty($existing['check_in_time']) && !empty($existing['check_out_time'])) {
                return $this->response->json([
                    'success' => true,
                    'message' => 'Anda sudah absen masuk & pulang hari ini',
                    'item' => $existing,
                ]);
            }

            if (!$existing) {
                $id = $this->model->create([
                    'student_id' => $userId,
                    'attendance_date' => $today,
                    'status' => 1,
                    'check_in_time' => $now,
                    'note' => 'Absen Masuk via QR'
                ]);
                $saved = $this->model->find($id);
                $msg = 'Absen MASUK berhasil dicatat';
            } else if (empty($existing['check_in_time'])) {
                $this->model->update($existing['id'], [
                    'status' => 1,
                    'check_in_time' => $now,
                    'updated_at' => $now
                ]);
                $saved = $this->model->find($existing['id']);
                $msg = 'Absen MASUK berhasil dicatat';
            } else {
                $this->model->update($existing['id'], [
                    'check_out_time' => $now,
                    'updated_at' => $now
                ]);
                $saved = $this->model->find($existing['id']);
                $msg = 'Absen PULANG berhasil dicatat';
            }

            return $this->response->json([
                'success' => true,
                'message' => $msg,
                'item' => $saved,
            ]);
        } else {
            if ($existing && (int)$existing['status'] === 1) { // 1 = Hadir
                return $this->response->json([
                    'success' => true,
                    'message' => 'Anda sudah tercatat hadir hari ini',
                    'item' => $existing,
                ]);
            }

            try {
                if ($existing) {
                    $this->model->update($existing['id'], [
                        'status' => 1,
                        'check_in_time' => $now,
                        'note' => 'Self-attendance via QR',
                        'updated_at' => $now
                    ]);
                    $saved = $this->model->find($existing['id']);
                } else {
                    $id = $this->model->create([
                        'student_id' => $userId,
                        'attendance_date' => $today,
                        'status' => 1,
                        'check_in_time' => $now,
                        'note' => 'Self-attendance via QR'
                    ]);
                    $saved = $this->model->find($id);
                }

                return $this->response->json([
                    'success' => true,
                    'message' => 'Absen harian berhasil dicatat',
                    'item' => $saved,
                ]);
            } catch (\Exception $e) {
                return $this->response->json(['message' => 'Gagal menyimpan absen: ' . $e->getMessage()], 500);
            }
        }
    }
    /**
     * Generate dynamic QR token for student
     * GET /attendance-daily-student/generate-token
     */
    public function generateToken()
    {
        $user = \Wibiesana\Padi\Core\Auth::user();
        if (!$user) return $this->response->json(['success' => false, 'message' => 'Unauthorized'], 401);

        $role = is_array($user) ? ($user['role'] ?? null) : ($user->role ?? null);
        $userId = is_array($user) ? ($user['id'] ?? $user['user_id'] ?? null) : ($user->id ?? $user->user_id ?? null);

        // Allow student (4), teacher (2), staff (3) or superadmin (1)
        // Note: Teachers and Staff also use this for their own attendance QR
        
        $settingModel = new \App\Models\Setting();
        $setting = $settingModel->findBuilder()->where(['status' => 1])->one();
        $config = $setting ? json_decode($setting['setting'], true) : [];
        
        $mode = 'presence_only';
        if ((int)$role === 4 || $role === 'student') {
            $mode = $config['student_attendance_mode'] ?? $config['daily_attendance_mode'] ?? 'presence_only';
        } else if ((int)$role === 2 || $role === 'teacher') {
            $mode = $config['teacher_attendance_mode'] ?? $config['daily_attendance_mode'] ?? 'presence_only';
        } else if ((int)$role === 3 || $role === 'staff') {
            $mode = $config['staff_attendance_mode'] ?? $config['daily_attendance_mode'] ?? 'presence_only';
        }

        if ($mode === 'off') {
            return $this->response->json(['success' => false, 'message' => 'Fitur absensi harian sedang dinonaktifkan'], 403);
        }

        $today = date('Y-m-d');
        
        // Map roles to models
        if ((int)$role === 4 || $role === 'student') {
            $existing = $this->model->findQuery()->where(['student_id' => $userId, 'attendance_date' => $today])->one();
        } else if ((int)$role === 2 || $role === 'teacher') {
            $existing = \App\Models\AttendanceDailyTeacher::findQuery()->where(['teacher_id' => $userId, 'attendance_date' => $today])->one();
        } else if ((int)$role === 3 || $role === 'staff') {
            $existing = \App\Models\AttendanceDailyStaff::findQuery()->where(['staff_id' => $userId, 'attendance_date' => $today])->one();
        } else {
            $existing = null;
        }

        if ($mode === 'check_in_out') {
            if ($existing && !empty($existing['check_in_time']) && !empty($existing['check_out_time'])) {
                return $this->response->json(['success' => false, 'message' => 'Anda sudah absen masuk & pulang hari ini'], 400);
            }
        } else {
            if ($existing && (int)$existing['status'] === 1) {
                return $this->response->json(['success' => false, 'message' => 'Anda sudah absen hari ini'], 400);
            }
        }

        $timestamp = time();
        $secret = \Wibiesana\Padi\Core\Env::get('QR_SECRET', 'padi_qr_secret_2026');
        
        // Window of 30 seconds
        $window = floor($timestamp / 30);
        
        $signature = hash_hmac('sha256', $role . '|' . $userId . '|' . $window, $secret);
        $token = base64_encode($role . '|' . $userId . '|' . $window . '|' . $signature);

        return $this->response->json([
            'success' => true,
            'token' => $token,
            'expires_in' => 30 - ($timestamp % 30)
        ]);
    }

    /**
     * Scan student QR token
     * POST /attendance-daily-student/scan-token
     */
    public function scanToken()
    {
        try {
            $payload = $this->request->all();
            $token = $payload['token'] ?? null;

        if (!$token) {
            return $this->response->json(['success' => false, 'message' => 'Token tidak ditemukan'], 400);
        }

        $decoded = base64_decode($token);
        if (!$decoded) {
            return $this->response->json(['success' => false, 'message' => 'Token tidak valid'], 400);
        }

        $parts = explode('|', $decoded);
        if (count($parts) !== 4) {
            return $this->response->json(['success' => false, 'message' => 'Format token tidak valid'], 400);
        }

        [$type, $userId, $tokenWindow, $signature] = $parts;
        $secret = \Wibiesana\Padi\Core\Env::get('QR_SECRET', 'padi_qr_secret_2026');
        
        // Verify signature
        $expectedSignature = hash_hmac('sha256', $type . '|' . $userId . '|' . $tokenWindow, $secret);
        if ($signature !== $expectedSignature) {
            return $this->response->json(['success' => false, 'message' => 'Tanda tangan token tidak valid'], 400);
        }

        // Verify window (allow current and previous for latency)
        $currentWindow = floor(time() / 30);
        if (abs($currentWindow - $tokenWindow) > 1) {
            return $this->response->json(['success' => false, 'message' => 'Token sudah kadaluwarsa'], 400);
        }

        $now = date('Y-m-d H:i:s');
        $lessonSessionId = $payload['lesson_session_id'] ?? null;
        $today = date('Y-m-d');
        $dayOfWeek = (int)date('N');
        $settingModel = new \App\Models\Setting();
        $setting = $settingModel->findBuilder()->where(['status' => 1])->one();
        $config = $setting ? json_decode($setting['setting'], true) : [];
        
        // 1. Check if today is an active day
        $activeDays = $config['active_days'] ?? [1, 2, 3, 4, 5];
        if (!in_array($dayOfWeek, $activeDays)) {
            return $this->response->json(['success' => false, 'message' => 'Hari ini bukan hari aktif sekolah'], 400);
        }

        $mode = $config['daily_attendance_mode'] ?? 'presence_only';
        if ($type === 'student') {
            $mode = $config['student_attendance_mode'] ?? $mode;
        } else if ($type === 'teacher') {
            $mode = $config['teacher_attendance_mode'] ?? $mode;
        } else if ($type === 'staff') {
            $mode = $config['staff_attendance_mode'] ?? $mode;
        }

        if ($mode === 'off') {
            return $this->response->json(['success' => false, 'message' => 'Fitur absensi harian sedang dinonaktifkan'], 403);
        }

        $currentTime = date('H:i');
        $startTime = $config['default_start_time'] ?? '07:00';
        $endTime = $config['default_end_time'] ?? '15:30';

        if ($type === 'student') {
            $studentModel = new \App\Models\Student();
            $person = $studentModel->find($userId);
            if (!$person) return $this->response->json(['success' => false, 'message' => 'Data siswa tidak ditemukan'], 404);

            // 1. Process Daily Attendance
            $existing = $this->model->findQuery()->where(['student_id' => $userId, 'attendance_date' => $today])->one();
            
            $msg = 'Berhasil mencatat kehadiran ' . $person['name'];

            if ($mode === 'check_in_out') {
                if ($existing && $existing['check_in_time'] && $existing['check_out_time'] && !$lessonSessionId) {
                    return $this->response->json(['success' => false, 'message' => $person['name'] . ' sudah absen masuk & pulang hari ini'], 400);
                }

                if (!$existing || empty($existing['check_in_time'])) {
                    if ($existing) {
                        $this->model->update($existing['id'], ['status' => 1, 'check_in_time' => $now, 'note' => 'Absen Masuk via Scan QR', 'updated_at' => $now]);
                    } else {
                        $this->model->create(['student_id' => $userId, 'attendance_date' => $today, 'status' => 1, 'check_in_time' => $now, 'note' => 'Absen Masuk via Scan QR']);
                    }
                    $msg = 'Berhasil absen MASUK: ' . $person['name'];
                } else if (empty($existing['check_out_time']) && !$lessonSessionId) {
                    // Check if early checkout
                    if ($currentTime < $endTime) {
                        return $this->response->json(['success' => false, 'message' => 'Belum waktunya absen pulang (Jam pulang: ' . $endTime . ')'], 400);
                    }
                    $this->model->update($existing['id'], ['check_out_time' => $now, 'note' => 'Absen Pulang via Scan QR', 'updated_at' => $now]);
                    $msg = 'Berhasil absen PULANG: ' . $person['name'];
                }
            } else {
                if ($existing && (int)$existing['status'] === 1 && !$lessonSessionId) {
                    return $this->response->json(['success' => false, 'message' => $person['name'] . ' sudah absen hari ini'], 400);
                }

                if (!$existing) {
                    $this->model->create(['student_id' => $userId, 'attendance_date' => $today, 'status' => 1, 'check_in_time' => $now, 'note' => 'Hadir via Scan QR']);
                } else {
                    $this->model->update($existing['id'], ['status' => 1, 'check_in_time' => $now, 'note' => 'Hadir via Scan QR', 'updated_at' => $now]);
                }
            }

            // 2. Process Lesson Attendance if requested
            if ($lessonSessionId) {
                $lessonModel = new \App\Models\LessonSession();
                $session = $lessonModel->find($lessonSessionId);
                if ($session) {
                    $atLessonModel = new \App\Models\AttendanceStudent();
                    $existingLesson = $atLessonModel->findQuery()
                        ->where(['lesson_session_id' => $lessonSessionId, 'student_id' => $userId])
                        ->one();
                    
                    if (!$existingLesson) {
                        $atLessonModel->create([
                            'lesson_session_id' => $lessonSessionId,
                            'student_id' => $userId,
                            'status' => 1, // Hadir
                            'note' => 'Hadir via Scan QR Guru'
                        ]);
                    }
                }
            }

            $returnItem = ['name' => $person['name'], 'nis' => $person['nis'], 'type' => 'student'];
        } else if ($type === 'teacher') {
            $teacherModel = new \App\Models\Teacher();
            $person = $teacherModel->find($userId);
            if (!$person) return $this->response->json(['success' => false, 'message' => 'Data guru tidak ditemukan'], 404);

            $atModel = new \App\Models\AttendanceDailyTeacher();
            $existing = $atModel->findQuery()->where(['teacher_id' => $userId, 'attendance_date' => $today])->one();
            
            $msg = 'Berhasil mencatat kehadiran ' . $person['name'];

            if ($mode === 'check_in_out') {
                if ($existing && $existing['check_in_time'] && $existing['check_out_time']) {
                    return $this->response->json(['success' => false, 'message' => $person['name'] . ' sudah absen masuk & pulang hari ini'], 400);
                }

                if (!$existing || empty($existing['check_in_time'])) {
                    if ($existing) {
                        $atModel->update($existing['id'], ['status' => 1, 'check_in_time' => $now, 'note' => 'Absen Masuk via Scan QR', 'updated_at' => $now]);
                    } else {
                        $atModel->create(['teacher_id' => $userId, 'attendance_date' => $today, 'status' => 1, 'check_in_time' => $now, 'note' => 'Absen Masuk via Scan QR']);
                    }
                    $msg = 'Berhasil absen MASUK: ' . $person['name'];
                } else {
                    // Check if early checkout
                    if ($currentTime < $endTime) {
                        return $this->response->json(['success' => false, 'message' => 'Belum waktunya absen pulang (Jam pulang: ' . $endTime . ')'], 400);
                    }
                    $atModel->update($existing['id'], ['check_out_time' => $now, 'note' => 'Absen Pulang via Scan QR', 'updated_at' => $now]);
                    $msg = 'Berhasil absen PULANG: ' . $person['name'];
                }
            } else {
                if ($existing && (int)$existing['status'] === 1) {
                    return $this->response->json(['success' => true, 'message' => $person['name'] . ' sudah tercatat hadir', 'item' => ['name' => $person['name'], 'nis' => $person['nip'], 'type' => 'teacher']]);
                }

                if ($existing) {
                    $atModel->update($existing['id'], ['status' => 1, 'check_in_time' => $now, 'note' => 'Hadir via Scan QR', 'updated_at' => $now]);
                } else {
                    $atModel->create(['teacher_id' => $userId, 'attendance_date' => $today, 'status' => 1, 'check_in_time' => $now, 'note' => 'Hadir via Scan QR']);
                }
            }
            $returnItem = ['name' => $person['name'], 'nis' => $person['nip'], 'type' => 'teacher'];
        } else if ($type === 'staff') {
            $staffModel = new \App\Models\Staff();
            $person = $staffModel->find($userId);
            if (!$person) return $this->response->json(['success' => false, 'message' => 'Data staff tidak ditemukan'], 404);

            $asModel = new \App\Models\AttendanceDailyStaff();
            $existing = $asModel->findQuery()->where(['staff_id' => $userId, 'attendance_date' => $today])->one();
            
            $msg = 'Berhasil mencatat kehadiran ' . $person['name'];

            if ($mode === 'check_in_out') {
                if ($existing && $existing['check_in_time'] && $existing['check_out_time']) {
                    return $this->response->json(['success' => false, 'message' => $person['name'] . ' sudah absen masuk & pulang hari ini'], 400);
                }

                if (!$existing || empty($existing['check_in_time'])) {
                    if ($existing) {
                        $asModel->update($existing['id'], ['status' => 1, 'check_in_time' => $now, 'note' => 'Absen Masuk via Scan QR', 'updated_at' => $now]);
                    } else {
                        $asModel->create(['staff_id' => $userId, 'attendance_date' => $today, 'status' => 1, 'check_in_time' => $now, 'note' => 'Absen Masuk via Scan QR']);
                    }
                    $msg = 'Berhasil absen MASUK: ' . $person['name'];
                } else {
                    // Check if early checkout
                    if ($currentTime < $endTime) {
                        return $this->response->json(['success' => false, 'message' => 'Belum waktunya absen pulang (Jam pulang: ' . $endTime . ')'], 400);
                    }
                    $asModel->update($existing['id'], ['check_out_time' => $now, 'note' => 'Absen Pulang via Scan QR', 'updated_at' => $now]);
                    $msg = 'Berhasil absen PULANG: ' . $person['name'];
                }
            } else {
                if ($existing && (int)$existing['status'] === 1) {
                    return $this->response->json(['success' => true, 'message' => $person['name'] . ' sudah tercatat hadir', 'item' => ['name' => $person['name'], 'nis' => $person['nip'] ?? $person['nik'] ?? 'STAFF', 'type' => 'staff']]);
                }

                if ($existing) {
                    $asModel->update($existing['id'], ['status' => 1, 'check_in_time' => $now, 'note' => 'Hadir via Scan QR', 'updated_at' => $now]);
                } else {
                    $asModel->create(['staff_id' => $userId, 'attendance_date' => $today, 'status' => 1, 'check_in_time' => $now, 'note' => 'Hadir via Scan QR']);
                }
            }
            $returnItem = ['name' => $person['name'], 'nis' => $person['nip'] ?? $person['nik'] ?? 'STAFF', 'type' => 'staff'];
        } else {
            return $this->response->json(['success' => false, 'message' => 'Tipe token tidak dikenal'], 400);
        }

        return $this->response->json([
            'success' => true,
            'message' => $msg,
            'item' => $returnItem,
        ]);
        } catch (\Exception $e) {
            return $this->response->json(['success' => false, 'message' => 'Gagal mencatat: ' . $e->getMessage()], 500);
        }
    }
}
