<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\BioTimeService;
use App\Services\AttendanceService;

class SyncBioTimeAttendance extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'biotime:sync {--date= : The date to sync (YYYY-MM-DD)}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync attendance logs from BioTime API and process daily attendance';

    /**
     * Execute the console command.
     */
    public function handle(BioTimeService $bioTimeService, AttendanceService $attendanceService)
    {
        $date = $this->option('date') ?: now()->toDateString();
        
        $this->info("Starting BioTime sync for date: {$date}...");

        // 1. Fetch raw logs from BioTime
        $newLogsCount = $bioTimeService->fetchTransactions($date . ' 00:00:00', $date . ' 23:59:59', 'system');
        
        if ($newLogsCount === false) {
            $this->error("Failed to fetch logs from BioTime API.");
            return 1;
        }

        $this->info("Successfully fetched and saved {$newLogsCount} new raw logs.");

        // 2. Process logs into daily attendance summary
        $dailyCount = $attendanceService->processLogsToDailyAttendance($date);

        $this->info("Successfully updated {$dailyCount} daily attendance records.");
        $this->info("Sync completed!");

        return 0;
    }
}
