<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\Attendance;
use App\Models\Branch;

class SyncAttendanceFromApi extends Command
{
    protected $signature = 'attendance:sync';
    protected $description = 'Sync attendance records from remote API every minute';

    public function handle()
    {
        try {
            $token = zktecoGetToken(); // ✅ Get token

            if (!$token) {
                \Log::error('Attendance Sync Failed: Token not retrieved.');
                return;
            }

            $url = env('ZKTECO_IP') . '/iclock/api/transactions/?page_size=100000';
         

            $response = Http::withHeaders([
                'Authorization' => "Token $token",
                'Content-Type'  => 'application/json',
            ])->get($url);

            if ($response->successful()) {
                $data = $response->json();
                if (!empty($data['data'])) {
                    $groupedPunches = [];

                    // Group punches by employee and date
                    foreach ($data['data'] as $punch) {
                        if (empty($punch['emp_code']) || empty($punch['punch_time'])) {
                            continue;
                        }

                        $employeeId = $punch['emp_code'];
                        $date = date('Y-m-d', strtotime($punch['punch_time']));
                        $time = date('H:i:s', strtotime($punch['punch_time']));

                        $groupedPunches[$employeeId][$date][] = $time;
                    }

                    // Now process each employee's punches
                    foreach ($groupedPunches as $employeeId => $dates) {
                        foreach ($dates as $date => $times) {
                            $this->saveAttendance($employeeId, $date, $times);
                        }
                    }
                }
            } else {
                \Log::error('Attendance API fetch failed: ' . $response->status() . ' - ' . $response->body());
            }
        } catch (\Exception $e) {
            \Log::error('Attendance sync error: ' . $e->getMessage());
        }
    }

  private function saveAttendance($employeeId, $date, $times)
{
    sort($times); 

    $signIn = $times[0]; 
    $signOut = count($times) > 1 ? end($times) : null;

    $signInHour = (int) date('H', strtotime($signIn));

    if ($signInHour >= 0 && $signInHour < 6) {
       
        $previousDate = date('Y-m-d', strtotime($date . ' -1 day'));

        $prevAttendance = Attendance::where('emplyee_id', $employeeId)
            ->whereDate('date', $previousDate)
            ->first();

        if ($prevAttendance && !$prevAttendance->sign_out) {
            $prevAttendance->sign_out = $signIn;
            $prevAttendance->save();
        }

    
        return;
    }

   
    $attendance = Attendance::where('emplyee_id', $employeeId)
        ->whereDate('date', $date)
        ->first();

    if (!$attendance) {
        $attendance = new Attendance();
        $attendance->emplyee_id = $employeeId;
        $attendance->branch_id = Branch::first()->id;
        $attendance->date = $date;
    }

    if (!$attendance->sign_in && $signIn) {
        $attendance->sign_in = $signIn;
    }

    if (!$attendance->sign_out && $signOut) {
        $attendance->sign_out = $signOut;
    }

    $attendance->save();
}

}
