<?php

namespace App\Controllers\View;
use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Models\StudentModel;

use CodeIgniter\I18n\Time;

class RFIDController extends BaseController
{
    public function process()
    {
        $rfidTag = $this->request->getPost('rfid');

        // Load the user model
        $userModel = new UserModel();

        // Find the user by RFID tag
        $user = $userModel->where('rfid_tag', $rfidTag)->first();

        if ($user) {
            // Log the scan (optional: store in a 'scan_log' table)
            $db = \Config\Database::connect();
            $db->table('scan_log')->insert([
            'user_id' => $user->id,
            'card_id' => $rfidTag,
            'scan_time' => Time::now(),
            ]);

            // Redirect with success message
            return redirect()->to('/rfid/log')->with('message', 'RFID recognized: ' . $user->name);
        } else {
            // Redirect with error message if RFID not found
            return redirect()->to('/')->with('error', 'RFID tag not recognized.');
        }
    }

    public function log()
    {
        $db = \Config\Database::connect();

        // Retrieve scan logs and join with users table to display user names
        $query = $db->table('scan_log')
        ->select('users.firstname as user_firstname, users.lastname as user_lastname, students.firstname as student_firstname, students.lastname as student_lastname, scan_log.card_id, scan_log.scan_time')
        ->join('users', 'users.id = scan_log.user_id', 'left')
        ->join('students', 'students.rfid_tag = scan_log.card_id', 'left') // Join students table by RFID tag
        ->orderBy('scan_time', 'DESC')
        ->get();

        // Fetch user and student data for display purposes
        $userModel = new UserModel();
        $studentModel = new StudentModel();

        // Optional: Fetch all users and students (if needed elsewhere in the view)
        $users = $userModel->findAll();
        $students = $studentModel->findAll();

        // Pass scan logs, users, and students data to the view
        $data['logs'] = $query->getResult();  // Logs with user and student info
        $data['users'] = $users;              // All users data
        $data['students'] = $students;        // All students data

        return view('/rfid/rfid_coming_soon', $data);
    }

    public function rfidComingSoon()
    {
        return view('rfid/rfid_coming_soon');
    }
}