<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class AttendanceData extends BaseModel
{
    protected $table = 'attendance_data';

    public $timestamps = true; // uses created_at / updated_at

    protected $fillable = [
        'class_id',
        'class_section_id',
        'student_id',
        'school_id',
        'date',
        'status',
        'reason',
        'is_reported',
        'is_notified',
        'semester',
        'school_year',
        'modified_by',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'class_id'         => 'integer',
        'class_section_id' => 'integer',
        'school_id'        => 'integer',
        'student_id'       => 'integer',
        'modified_by'      => 'integer',
        'date'             => 'datetime', // ✅ DATETIME column
    ];

    /* =========================
     * Relationships (optional)
     * ========================= */
    public function student()
    {
        return $this->belongsTo(Student::class, 'student_id');
    }

    public function classSection()
    {
        return $this->belongsTo(ClassSection::class, 'class_section_id');
    }

    /* =========================
     * DATETIME helpers
     * ========================= */
    private static function dayRange(string $day): array
    {
        $day = substr($day, 0, 10); // YYYY-MM-DD
        $start = Carbon::parse($day)->startOfDay();
        $endEx = Carbon::parse($day)->addDay()->startOfDay(); // exclusive
        return [$start, $endEx];
    }

    /* =========================
     * CI method equivalents
     * ========================= */

    /**
     * Retrieve attendance by class and section for a specific date (DATETIME-safe).
     */
    public static function getAttendanceByClass(int $classId, int $classSectionId, string $date)
    {
        [$start, $endEx] = static::dayRange($date);

        return static::query()
            ->where('class_id', $classId)
            ->where('class_section_id', $classSectionId)
            ->where('date', '>=', $start)
            ->where('date', '<', $endEx)
            ->get();
    }

    /**
     * Update attendance record by PK.
     */
    public static function updateAttendance(int $attendanceId, array $data): bool
    {
        $affected = static::query()->whereKey($attendanceId)->update($data);
        return $affected >= 0;
    }

    /**
     * Retrieve attendance for a specific student, class section, and date (DATETIME-safe).
     */
    public static function getAttendance(int $studentId, int $classSectionId, string $date): ?self
    {
        [$start, $endEx] = static::dayRange($date);

        return static::query()
            ->where('student_id', $studentId)
            ->where('class_section_id', $classSectionId)
            ->where('date', '>=', $start)
            ->where('date', '<', $endEx)
            ->first();
    }

    /**
     * Retrieve reported attendance for a specific date or range (DATETIME-safe).
     */
    public static function getReportedAttendance(string $startDate, ?string $endDate = null)
    {
        $q = static::query();
        static::applyReportedFilter($q);

        [$start, ] = static::dayRange($startDate);

        if ($endDate) {
            [, $endEx] = static::dayRange($endDate); // end exclusive of next day
            $q->where('date', '>=', $start)->where('date', '<', $endEx);
        } else {
            [, $endEx] = static::dayRange($startDate);
            $q->where('date', '>=', $start)->where('date', '<', $endEx);
        }

        return $q->get();
    }

    public static function getTodayAbsentees(?int $classSectionId = null, ?string $schoolYear = null, ?string $semester = null)
    {
        [$start, $endEx] = [now()->startOfDay(), now()->addDay()->startOfDay()];

        $q = static::query()
            ->where('date', '>=', $start)
            ->where('date', '<', $endEx)
            ->where(function ($w) {
                $w->whereIn(DB::raw("UPPER(TRIM(status))"), ['ABSENT', 'ABS', 'A'])
                  ->orWhereRaw("UPPER(TRIM(status)) LIKE 'ABS%'");
            });

        if ($classSectionId !== null) $q->where('class_section_id', $classSectionId);
        if ($schoolYear !== null)     $q->where('school_year', $schoolYear);
        if ($semester !== null)       $q->where('semester', $semester);

        return $q->get();
    }

    public static function getTodayLates(?int $classSectionId = null, ?string $schoolYear = null, ?string $semester = null)
    {
        [$start, $endEx] = [now()->startOfDay(), now()->addDay()->startOfDay()];

        $q = static::query()
            ->where('date', '>=', $start)
            ->where('date', '<', $endEx)
            ->where(function ($w) {
                $w->whereIn(DB::raw("UPPER(TRIM(status))"), ['LATE', 'L'])
                  ->orWhereRaw("UPPER(TRIM(status)) LIKE 'LATE%'");
            });

        if ($classSectionId !== null) $q->where('class_section_id', $classSectionId);
        if ($schoolYear !== null)     $q->where('school_year', $schoolYear);
        if ($semester !== null)       $q->where('semester', $semester);

        return $q->get();
    }

    public static function getAbsencesByClassSection(int $classSectionId, string $schoolYear, string $semester)
    {
        return static::query()
            ->where('class_section_id', $classSectionId)
            ->where('school_year', $schoolYear)
            ->where('semester', $semester)
            ->where(function ($w) {
                $w->whereIn(DB::raw("UPPER(TRIM(status))"), ['ABSENT', 'ABS', 'A'])
                  ->orWhereRaw("UPPER(TRIM(status)) LIKE 'ABS%'");
            })
            ->orderByDesc('date')
            ->get();
    }

    /**
     * Fetch attendance rows for a student, optionally filtered by date range.
     * Note: Uses inclusive date range by day using datetime bounds.
     */
    public static function getStudentAttendance(
        int $studentId,
        ?string $startDate = null,
        ?string $endDate   = null,
        ?string $schoolYear = null,
        ?string $semester   = null
    ) {
        $q = static::query()->where('student_id', $studentId);

        if (!empty($startDate)) {
            [$start, ] = static::dayRange($startDate);
            $q->where('date', '>=', $start);
        }
        if (!empty($endDate)) {
            [, $endEx] = static::dayRange($endDate);
            $q->where('date', '<', $endEx);
        }
        if (!empty($schoolYear)) $q->where('school_year', $schoolYear);
        if (!empty($semester))   $q->where('semester', $semester);

        return $q->orderByDesc('date')->get();
    }

    /**
     * Convenience: attendance for an exact date (DATETIME-safe).
     */
    public static function getStudentAttendanceOnDate(int $studentId, string $date): ?self
    {
        [$start, $endEx] = static::dayRange($date);

        return static::query()
            ->where('student_id', $studentId)
            ->where('date', '>=', $start)
            ->where('date', '<', $endEx)
            ->first();
    }

    /**
     * Unreported rows for students in term.
     */
    public static function unreportedTermRows(array $studentIds, string $schoolYear, ?string $semester)
    {
        $q = static::query()
            ->select(['id','student_id','class_id','class_section_id','date','status','reason','school_year','semester','is_reported'])
            ->where('school_year', $schoolYear);

        if ($semester !== null && $semester !== '') {
            $q->where('semester', $semester);
        }
        if (!empty($studentIds)) {
            $q->whereIn('student_id', array_map('intval', $studentIds));
        }

        static::applyUnreportedFilter($q);

        return $q->orderByDesc('date')->get();
    }

    /**
     * NOT-REPORTED absences/lates for ALL students in optional term filters.
     * Returns grouped array: [student_id => ['absences'=>[], 'lates'=>[], 'counts'=>...]]
     */
    public static function getUnreportedAbsencesAndLates(?string $schoolYear = null, ?string $semester = null): array
    {
        $q = static::query()
            ->select(['id','student_id','class_id','class_section_id','date','status','reason','school_year','semester','is_reported']);

        static::applyUnreportedFilter($q);

        // Not notified yet: supports 0/'0'/NULL and string enums like 'yes'
        $q->where(function ($w) {
            $w->whereNull('is_notified')
              ->orWhere('is_notified', 0)
              ->orWhere('is_notified', '0')
              ->orWhereRaw("LOWER(TRIM(COALESCE(is_notified, ''))) != 'yes'");
        });

        if (!empty($schoolYear)) $q->where('school_year', $schoolYear);
        if (!empty($semester))   $q->where('semester', $semester);

        // Status filter: exact + prefixes (ABS_3, LATE_2, etc.)
        $q->where(function ($w) {
            $w->whereIn(DB::raw("UPPER(TRIM(status))"), ['ABS','ABSENT','LATE','A','L'])
              ->orWhereRaw("UPPER(TRIM(status)) LIKE 'ABS%'")
              ->orWhereRaw("UPPER(TRIM(status)) LIKE 'LATE%'");
        });

        $rows = $q->orderBy('student_id')->orderByDesc('date')->get()->toArray();

        $out = [];
        foreach ($rows as $r) {
            $sid = (int) ($r['student_id'] ?? 0);

            if (!isset($out[$sid])) {
                $out[$sid] = [
                    'absences' => [],
                    'lates'    => [],
                    'counts'   => ['absences' => 0, 'lates' => 0, 'total' => 0],
                ];
            }

            $st     = strtoupper(trim((string)($r['status'] ?? '')));
            $isAbs  = ($st === 'ABS' || $st === 'ABSENT' || $st === 'A' || str_starts_with($st, 'ABS'));
            $isLate = ($st === 'LATE' || $st === 'L' || str_starts_with($st, 'LATE'));

            $rec = [
                'id'               => $r['id'] ?? null,
                'date'             => $r['date'] ?? null,
                'status'           => $r['status'] ?? null,
                'reason'           => $r['reason'] ?? null,
                'class_id'         => $r['class_id'] ?? null,
                'class_section_id' => $r['class_section_id'] ?? null,
                'school_year'      => $r['school_year'] ?? null,
                'semester'         => $r['semester'] ?? null,
            ];

            if ($isAbs) {
                $out[$sid]['absences'][] = $rec;
                $out[$sid]['counts']['absences']++;
            } elseif ($isLate) {
                $out[$sid]['lates'][] = $rec;
                $out[$sid]['counts']['lates']++;
            }

            $out[$sid]['counts']['total'] =
                $out[$sid]['counts']['absences'] + $out[$sid]['counts']['lates'];
        }

        return $out;
    }

    /**
     * Mark rule as notified for a student on a specific day (DATETIME-safe).
     */
    public static function markRuleAsNotifiedData(
        int $studentId,
        string $date,
        ?string $semester = null,
        ?string $schoolYear = null
    ): bool {
        [$start, $endEx] = static::dayRange($date);

        $q = static::query()
            ->where('student_id', $studentId)
            ->where('date', '>=', $start)
            ->where('date', '<', $endEx);

        if (!empty($semester))   $q->where('semester', $semester);
        if (!empty($schoolYear)) $q->where('school_year', $schoolYear);

        $affected = $q->update([
            'is_notified' => 'yes',
            'updated_at'  => now(),
        ]);

        return $affected >= 0;
    }

    /**
     * Mark specific attendance dates as reported + notified for a student (DATETIME index-friendly).
     */
    public static function markReportedAndNotified(int $studentId, array $dates, ?string $semester = null, ?string $schoolYear = null): bool
    {
        $dates = array_values(array_unique(array_filter($dates, static function ($d) {
            return is_string($d) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $d);
        })));

        if (empty($dates)) return true;

        $q = static::query()
            ->where('student_id', $studentId)
            ->whereRaw("LOWER(TRIM(status)) IN ('absent','late')");

        if (!empty($semester))   $q->where('semester', $semester);
        if (!empty($schoolYear)) $q->where('school_year', $schoolYear);

        // OR day ranges instead of DATE(date)
        $q->where(function ($w) use ($dates) {
            foreach ($dates as $d) {
                [$start, $endEx] = static::dayRange($d);
                $w->orWhere(function ($x) use ($start, $endEx) {
                    $x->where('date', '>=', $start)->where('date', '<', $endEx);
                });
                $w->orWhere('date', $d);
            }
        });

        $payload = [
            'updated_at'  => now(),
            'is_notified' => 'yes',
        ];

        $cols = static::reportedColumns();
        if (!empty($cols['is_reported'])) $payload['is_reported'] = 'yes';
        if (!empty($cols['reported']))    $payload['reported']    = 1;

        $affected = $q->update($payload);

        return $affected >= 0;
    }

    /**
     * Fetch unreported dates for a student within N days for the given status set (DATETIME-safe).
     */
    public static function getRecentUnreportedDates(
        int $studentId,
        array $statuses,
        ?string $incidentDate = null,
        int $lookbackDays = 35,
        ?string $semester = null,
        ?string $schoolYear = null
    ): array {
        if ($studentId <= 0 || empty($statuses)) return [];

        $statuses = array_map('strtolower', $statuses);

        $day = ($incidentDate && preg_match('/^\d{4}-\d{2}-\d{2}$/', $incidentDate))
            ? $incidentDate
            : now()->toDateString();

        $startDay = Carbon::parse($day)->subDays(max(0, $lookbackDays))->toDateString();
        [$start, ] = static::dayRange($startDay);
        [, $endEx] = static::dayRange($day);

        $q = static::query()
            ->select('date')
            ->where('student_id', $studentId)
            ->where('date', '>=', $start)
            ->where('date', '<', $endEx)
            ->whereIn(DB::raw("LOWER(TRIM(status))"), $statuses);

        static::applyUnreportedFilter($q);

        if (!empty($semester))   $q->where('semester', $semester);
        if (!empty($schoolYear)) $q->where('school_year', $schoolYear);

        $rows = $q->orderByDesc('date')->pluck('date')->all();

        return array_values(array_unique(array_map(static function ($d) {
            return substr((string)$d, 0, 10); // YYYY-MM-DD
        }, $rows)));
    }

    /* =========================
     * Filters / schema helpers
     * ========================= */

    private static function reportedColumns(): array
    {
        static $cache = null;
        if ($cache !== null) return $cache;

        $table = (new static)->getTable();

        $cache = [
            'is_reported' => static::columnExists($table, 'is_reported'),
            'reported'    => static::columnExists($table, 'reported'),
        ];

        return $cache;
    }

    private static function columnExists(string $table, string $column): bool
    {
        try {
            return DB::connection()
                ->getSchemaBuilder()
                ->hasColumn($table, $column);
        } catch (\Throwable) {
            return false;
        }
    }

    /**
     * Not-reported filter:
     * - is_reported = 'no' OR 0 OR NULL (if column exists)
     * - legacy 'reported' column: treat values yes/1/true/on as reported, so exclude those
     */
    private static function applyUnreportedFilter($q): void
    {
        $cols = static::reportedColumns();

        if (!empty($cols['is_reported'])) {
            $q->where(function ($w) {
                $w->whereNull('is_reported')
                  ->orWhere('is_reported', 0)
                  ->orWhere('is_reported', '0')
                  ->orWhereRaw("LOWER(TRIM(COALESCE(is_reported, ''))) = 'no'");
            });
        }

        if (!empty($cols['reported'])) {
            $q->whereRaw("(LOWER(TRIM(COALESCE(reported, ''))) NOT IN ('yes','1','true','y','on'))");
        }
    }

    /**
     * Reported filter best-effort (used by getReportedAttendance()).
     */
    private static function applyReportedFilter($q): void
    {
        $q->where(function ($w) {
            $w->where('is_reported', 1)
              ->orWhere('is_reported', '1')
              ->orWhereRaw("LOWER(TRIM(COALESCE(is_reported, ''))) = 'yes'");
        });
    }
}
