<?php

namespace App\Commands;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Database;

class RecalculateAttendance extends BaseCommand
{
    protected $group       = 'Attendance';
    protected $name        = 'attendance:recalculate-summary';
    protected $description = 'Recalculates the attendance summary records (total absences, etc.) from the raw attendance data.';

    public function run(array $params)
    {
        $db = Database::connect();

        CLI::write('Starting attendance summary recalculation...', 'yellow');

        // 1. Truncate the attendance_record table
        try {
            $db->table('attendance_record')->truncate();
            CLI::write('Successfully truncated attendance_record table.', 'green');
        } catch (\Throwable $e) {
            CLI::error('Failed to truncate attendance_record table: ' . $e->getMessage());
            return;
        }

        // 2. Get all attendance data
        $attendanceData = $db->table('attendance_data')
            ->orderBy('student_id', 'ASC')
            ->orderBy('school_year', 'ASC')
            ->orderBy('semester', 'ASC')
            ->get()->getResultArray();

        if (empty($attendanceData)) {
            CLI::write('No attendance data found to process.', 'yellow');
            return;
        }

        $summary = [];

        // 3. Process the data
        foreach ($attendanceData as $row) {
            $studentId  = $row['student_id'];
            $schoolYear = $row['school_year'];
            $semester   = $row['semester'];
            $status     = strtolower($row['status']);

            $key = "{$studentId}-{$schoolYear}-{$semester}";

            if (!isset($summary[$key])) {
                $summary[$key] = [
                    'student_id'       => $studentId,
                    'school_year'      => $schoolYear,
                    'semester'         => $semester,
                    'class_section_id' => $row['class_section_id'],
                    'school_id'        => $row['school_id'],
                    'total_presence'   => 0,
                    'total_absence'    => 0,
                    'total_late'       => 0,
                    'total_attendance' => 0,
                    'created_at'       => utc_now(),
                    'updated_at'       => utc_now(),
                ];
            }

            $summary[$key]['total_attendance']++;
            if ($status === 'present') {
                $summary[$key]['total_presence']++;
            } elseif ($status === 'absent') {
                $summary[$key]['total_absence']++;
            } elseif ($status === 'late') {
                $summary[$key]['total_late']++;
            }
        }

        // 4. Insert the new summary records
        if (!empty($summary)) {
            $builder = $db->table('attendance_record');
            try {
                $builder->insertBatch(array_values($summary));
                CLI::write('Successfully inserted ' . count($summary) . ' summary records.', 'green');
            } catch (\Throwable $e) {
                CLI::error('Failed to insert summary records: ' . $e->getMessage());
                return;
            }
        }

        CLI::write('Attendance summary recalculation finished.', 'green');
    }
}
