<?php

namespace App\Console\Commands;

use App\Enums\Biometrics\EnabledStatus;
use Exception;
use Illuminate\Console\Command;
use Suiterus\Adg\Models\Timekeeping\BiometricDevice;
use Suiterus\Adg\Services\ZKTecoService;

class SyncBiometricsAttendance extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:biometrics-attendance';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Get attendance records from ZKTeco device and transfer it to the HRIS database';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        try {

            $devices = BiometricDevice::where('status', EnabledStatus::ENABLED)->get();

            foreach($devices as $device) {
                $zk = new ZKTecoService($device->host, $device->port);
                if (!$zk->checkDeviceConnection()) continue;
                $this->info("Syncing attendance for {$device->name}...");
                // $zk->syncTime();
                $zk->syncAttendance($device->name);
                $zk->disconnect();
            }

        } catch(Exception $e) {
            echo $e->getLine();
            echo $e->getMessage();
            return Command::FAILURE;
        }
        return Command::SUCCESS;
    }
}
