<?php

namespace App\Commands;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Modules\Attendance\Services\AutoPunchService;

class AttendanceAutoPunch extends BaseCommand
{
    protected $group       = 'Attendance';
    protected $name        = 'attendance:auto-punch';
    protected $description = 'Run daily auto-punch for all active directory employees.';
    protected $usage       = 'attendance:auto-punch [date]';
    protected $arguments   = [
        'date' => 'Optional date (Y-m-d). Defaults to yesterday.',
    ];

    public function run(array $params): void
    {
        $date = $params[0] ?? date('Y-m-d', strtotime('-1 day'));

        if (! preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            CLI::error('Invalid date format. Use Y-m-d.');
            return;
        }

        CLI::write("Running auto-punch for {$date}...", 'yellow');

        $service = new AutoPunchService();
        $stats   = $service->runForDate($date);

        CLI::write("Processed: {$stats['processed']}", 'green');
        CLI::write("Auto present: {$stats['auto_present']}", 'green');
        CLI::write("Absent: {$stats['absent']}", 'yellow');
        CLI::write("On leave: {$stats['on_leave']}", 'cyan');
        CLI::write("Holiday: {$stats['holiday']}", 'cyan');
        CLI::write("Skipped (already punched): {$stats['skipped']}", 'white');
    }
}
