<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Rats\Zkteco\Lib\ZKTeco;
use App\Models\FingerDevices;
use App\Models\AttendanceInfo;
use App\Models\EmployeeInfo;



class MachineController extends Controller
{
    //

        /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function device_ip()
    {
        
 
        $device = FingerDevices::whereNull('deleted_at');
        
                
        if ($device) {
            $deviceip = $device->ip;
        } else {
            // If no matching device is found, set a default IP address
            $deviceip = '192.168.0.4';
        }
    
        return $deviceip;
        
    }

    // public function device_data_user()
    // {
    //     $deviceip = $this->device_ip();
    //     $zk = new ZKTeco($deviceip,4370);
    //     $zk->connect(); 
    //     $zk->disableDevice();  
    //     $users = $zk->getUser();
    //     return view('admin/devicedata',compact(
    //         'deviceip','users',
    //     ));
    // }


    public function device_data_user()
    {
        // Get all activated devices
        $devices = FingerDevices::whereNull('deleted_at')->get();
        
        // Array to store attendance data for all devices
        $UserData = [];
        
        foreach ($devices as $device) {
            $deviceip = $device->ip;
            $devicename = $device->name;
            
            $zk = new ZKTeco($deviceip, 4370);
            $zk->connect(); 
            $zk->disableDevice();  
            
            // Get attendance data for the current device
            $users = $zk->getUser();
            
            // Store attendance data along with device IP
            $UserData[] = [
                'deviceip' => $deviceip,
                'users' => $users,
                'devicename' => $devicename
    
            ];
        }
    
        // Pass the users data to the view
        return view('admin/devicedata', compact('UserData'));
    }
    


    // public function device_data_attendance()
    // {
    //     $deviceip = $this->device_ip();
    //     $zk = new ZKTeco($deviceip,4370);
    //     $zk->connect(); 
    //     $zk->disableDevice();  
    //     $attendances = $zk->getAttendance();
    //     $deviceserialNumber = $zk->serialNumber();
    //     // $deviceserialNumber=  substr(strstr($zk->serialNumber(), '='), 1);

    //     return view('admin/attendances',compact(
    //         'deviceip','attendances'
    //     ));
    // }

    public function device_data_attendance()
{
    // Get all activated devices
    $devices = FingerDevices::whereNull('deleted_at')->get();
    
    // Array to store attendance data for all devices
    $attendanceData = [];
    
    foreach ($devices as $device) {
        $deviceip = $device->ip;
        $devicename = $device->name;
        
        $zk = new ZKTeco($deviceip, 4370);
        $zk->connect(); 
        $zk->disableDevice();  
        
        // Get attendance data for the current device
        $attendances = $zk->getAttendance();
        
        // Store attendance data along with device IP
        $attendanceData[] = [
            'deviceip' => $deviceip,
            'attendances' => $attendances,
            'devicename' => $devicename

        ];
    }

    // Pass the attendance data to the view
    return view('admin/attendances', compact('attendanceData'));
}



    // public function sync_attendance()
    // {
    //     $deviceip = $this->device_ip();
    //     $zk = new ZKTeco($deviceip, 4370);
    //     $zk->connect(); 
    //     $zk->disableDevice();  
    
    //     $attendances = $zk->getAttendance();
    //     $deviceserialNumber = substr(strstr($zk->serialNumber(), '='), 1);
    
    //     // Check if there are any existing records in the database
    //     $existingRecordCount = AttendanceInfo::count();
    
    //     // Get the last attendance number from the database if there are existing records
    //     $lastAttendanceNumber = $existingRecordCount > 0 ? AttendanceInfo::latest('attendance_number')->value('attendance_number') : null;
    
    //     // Count the number of new records added
    //     $newRecordsCount = 0;
    
    //     // Check if the last attendance number is the same as the device's last data
    //     $lastDeviceAttendanceNumber = null;
    //     if (!empty($attendances)) {
    //         $lastDeviceAttendanceNumber = end($attendances)['uid'];
    //     }
        
    
    //     if ($lastAttendanceNumber !== null && $lastAttendanceNumber >= $lastDeviceAttendanceNumber) {
    //         // If the last attendance number in the database is greater or equal to the device's last data
    //         // Show a modal indicating that the data is already up to date
    //         flash()->info('Info', 'Attendance data is already up to date!');
    
    //         return redirect()->route('finger_device.index')->with('modal_open', true);
    //     }
    
    //     // Loop through each attendance record and save it to the database if it's not a duplicate
    //     foreach ($attendances as $attendance) {
    //         // Check if attendance_number already exists in the database
    //         if ($lastAttendanceNumber !== null && $attendance['uid'] <= $lastAttendanceNumber)
    //             continue; // Skip this record as it's already synced
    //         }
            
    //         // Create a new record in the database
    //         AttendanceInfo::create([
    //             'id_number' => $attendance['id'],
    //             'attendance_number' => $attendance['uid'],
    //             'state' => $attendance['state'],
    //             'attendance_date_time' => $attendance['timestamp'], // Assuming timestamp is UNIX timestamp
    //             'type' => $attendance['type'],
    //             'device_serial_number' => $deviceserialNumber
    //         ]);
            
    //         $newRecordsCount++;
    //     }
    
    //     flash()->success('Success', 'Successfully synced '.$newRecordsCount.' device data to the system!');
    
    //     return redirect()->route('finger_device.index')->with('modal_open', true);
    // }
    
    
    // public function sync_employee_info()
    // {
    //     $deviceip = $this->device_ip();
    //     $zk = new ZKTeco($deviceip, 4370);
    //     $zk->connect(); 
    //     $zk->disableDevice();  
    
    //     // Retrieve the serial number of the device
    //     $deviceSerialNumber = substr(strstr($zk->serialNumber(), '='), 1);
        
    //     // Retrieve the employee data from the device
    //     $users = $zk->getUser();
    
    //     // Count the number of new records added
    //     $newRecordsCount = 0;
        
    //     // Loop through each employee record and save it to the database if it's not a duplicate
    //     foreach ($users as $user) {
    //         // Check if the record already exists based on user_id and device_serial_number
    //         $existingRecord = EmployeeInfo::where('user_id', $user['userid'])
    //                                       ->where('device_serial_number', $deviceSerialNumber)
    //                                       ->exists();
            
    //         // If the record already exists, skip syncing and continue to the next record
    //         if ($existingRecord) {
    //             continue;
    //         }
            
    //         // Create a new record in the database
    //         EmployeeInfo::create([
    //             'uid' => $user['uid'],
    //             'user_id' => $user['userid'],
    //             'name' => $user['name'],
    //             'role' => $user['role'],
    //             'password' => $user['password'], // Assuming timestamp is UNIX timestamp
    //             'card_no' => $user['cardno'],
    //             'device_serial_number' => $deviceSerialNumber
    //         ]);
            
    //         $newRecordsCount++;
    //     }
    
    //     if ($newRecordsCount > 0) {
    //         flash()->success('Success', 'Successfully synced '.$newRecordsCount.'  new employee data to the system!');
    //     } else {
    //         flash()->info('Info', 'No new users data to sync!');
    //     }
        
    //     return redirect()->route('finger_device.index')->with('modal_open', true);
    // }
    


    public function device_setip(Request $request)
    {
        session()->put('dip', $request->deviceip);
        return redirect()->back();
    }
    public function index()
    {
        $deviceip = $this->device_ip();
        return view('welcome',compact('deviceip'));
    }
    public function test_sound()
    {
        $deviceip = $this->device_ip();
        $zk = new ZKTeco($deviceip,4370);
        $zk->connect(); 
        $zk->disableDevice();  
        $zk->testVoice(); 
        return redirect()->back()->with('success_message','Playing sound on device.');
    }

    public function device_information()
    {
        $deviceip = $this->device_ip();
        $zk = new ZKTeco($deviceip,4370);
        $zk->connect(); 
        $zk->disableDevice();  
        $deviceVersion = $zk->version();
        $deviceOSVersion = $zk->osVersion();
        $devicePlatform = $zk->platform();
        $devicefmVersion = $zk->fmVersion();
        $deviceworkCode = $zk->workCode();
        $devicessr = $zk->ssr();
        $devicepinWidth = $zk->pinWidth();
        $deviceserialNumber = $zk->serialNumber();
        $devicedeviceName = $zk->deviceName();
        $devicegetTime = $zk->getTime();
        return view('device-information',compact(
            'deviceip','deviceVersion','deviceOSVersion','devicePlatform','devicefmVersion','deviceworkCode',
            'devicessr','devicepinWidth','deviceserialNumber','devicedeviceName','devicegetTime',
        ));
    }




    
    public function device_data_clear_attendance()
    {
        $deviceip = $this->device_ip();

        $zk = new ZKTeco($deviceip,4370);
        $zk->connect(); 
        $zk->disableDevice();  
        $zk->clearAttendance();

        return redirect()->back()->with('success_message','Attendance cleared successfully.');
    }

    public function device_restart()
    {
        $deviceip = $this->device_ip();

        $zk = new ZKTeco($deviceip,4370);
        $zk->connect(); 
        $zk->disableDevice();  
        $zk->restart();

        return redirect()->back()->with('success_message','Device restart successfully.');
    }

    public function device_shutdown()
    {
        $deviceip = $this->device_ip();

        $zk = new ZKTeco($deviceip,4370);
        $zk->connect(); 
        $zk->disableDevice();  
        $zk->shutdown();

        return redirect()->back();
    }


    public function device_sleep()
    {
        $deviceip = $this->device_ip();

        $zk = new ZKTeco($deviceip,4370);
        $zk->connect(); 
        $zk->disableDevice();  
        $zk->testVoice(); 
        return redirect()->back()->with('success_message','Device is put on sleep.');

    }


    public function device_adduser()
    {
        $deviceip = $this->device_ip();
        return view('admin/deviceadduser',compact('deviceip'));
        
    }

    public function device_setuser(Request $request)
    {
       $deviceip = $this->device_ip();
       $uid = $request->uid;
       $userid = $request->userid;
       $name = $request->name;
       $role = (int)$request->role;
       $password = $request->password;
       $cardno = $request->cardno;
       //dd($request->role);
       $zk = new ZKTeco($deviceip,4370);
       $zk->connect(); 
       $zk->disableDevice();  
       $zk->setUser($uid , $userid , $name , $role , $password , $cardno);

    //    return redirect()->back()->with('success_message','User added to device successfully.');

      flash()->success('Success', 'User added to device successfully');
      return redirect()->route('machine.devicedata.user');



    }

    public function device_removeuser_single($uid)
    {
        $deviceip = $this->device_ip();
        $zk = new ZKTeco($deviceip,4370);
        $zk->connect(); 
        $zk->disableDevice();  
        $zk->removeUser($uid);

        // return redirect()->back()->with('success_message','User removed from device successfully.');

        flash()->success('Success', 'User removed from device successfully.');
  
        return redirect()->back();

        
    }

    public function device_viewuser_single(Request $request)
    {
        $deviceip = $this->device_ip();
        $uid = $request->uid;
        $userid = $request->userid;
        $name = $request->name;
        $role = (int)$request->role;
        $password = $request->password;
        $cardno = $request->cardno;

        $zk = new ZKTeco($deviceip,4370);
        $zk->connect(); 
        $userfingerprints=$zk->getFingerprint($request->uid);
        
        // foreach($userfingerprints as $userfingerprint)
        // {
        //     $imagearray= unpack("C*",$userfingerprint); 
        // }
        // $data = implode('', array_map(function($e) {
        //     return pack("C*", $e);
        // }, $$userfingerprint));
        // echo $data;
        // dd($data);
        
        //dd($userfingerprints);
        return view('admin/device-information-user',compact(
            'deviceip','uid','userid','name',
            'role','password','cardno','userfingerprints',
        ));
    }

}
