<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\CachedMonthlyAttendance;
use Illuminate\Http\Request;

class CachedMonthlyAttendanceController extends Controller
{
    protected $signature = 'attendance:check-cache {employee_id?}';
    protected $description = 'Check cached attendance data structure';

    public function handle()
    {
        $employeeId = $this->argument('employee_id');
        
        if ($employeeId) {
            $cached = CachedMonthlyAttendance::where('employee_id', $employeeId)->get();
        } else {
            $cached = CachedMonthlyAttendance::latest()->limit(5)->get();
        }
        
        if ($cached->isEmpty()) {
            $this->error('No cached data found');
            return;
        }
        
        foreach ($cached as $cache) {
            $this->info("========================================");
            $this->info("Employee ID: {$cache->employee_id}");
            $this->info("Year-Month: {$cache->year_month}");
            $this->info("Computed At: {$cache->computed_at}");
            $this->info("Is Valid: " . ($cache->isValid() ? 'YES' : 'NO'));
            
            // Check data structure
            $data = $cache->attendance_data;
            $this->info("Data Type: " . gettype($data));
            
            if (is_string($data)) {
                $this->warn("WARNING: Data is stored as string!");
                $decoded = json_decode($data, true);
                if ($decoded) {
                    $this->info("But can be decoded. Keys: " . implode(', ', array_keys($decoded)));
                } else {
                    $this->error("ERROR: Cannot decode JSON!");
                }
            } elseif (is_array($data)) {
                $this->info("Data Keys: " . implode(', ', array_keys($data)));
                $this->info("Schedule count: " . count($data['schedule'] ?? []));
                $this->info("Holiday count: " . count($data['holiday'] ?? []));
                $this->info("Leave count: " . count($data['leave'] ?? []));
            }
            
            $this->info("========================================\n");
        }
    }
}
