<?php

namespace App\Livewire\Parent;

use App\Models\AttendanceRecord;
use App\Models\SchoolSetting;
use App\Models\User;
use Carbon\Carbon;
use Livewire\Component;

class ParentPortalShow extends Component
{
    public string $token;

    public function mount(string $token): void
    {
        $this->token = $token;
    }

    public function render()
    {
        $student = User::with(['role', 'shift'])
            ->where('parent_token', $this->token)
            ->firstOrFail();

        $todayStr = now()->toDateString();
        $monthStr = now()->format('Y-m');

        // Today's attendance record
        $todayRecord = AttendanceRecord::where('user_id', $student->id)
            ->where('date', $todayStr)
            ->first();

        // Monthly records
        $monthlyRecords = AttendanceRecord::where('user_id', $student->id)
            ->where('date', 'like', "{$monthStr}%")
            ->orderBy('date', 'desc')
            ->get();

        // 30 Days Timeline Records
        $timelineRecords = AttendanceRecord::where('user_id', $student->id)
            ->orderBy('date', 'desc')
            ->take(30)
            ->get();

        // Monthly Stats
        $hadir = $monthlyRecords->where('status', 'Hadir')->count();
        $terlambat = $monthlyRecords->where('status', 'Terlambat')->count();
        $izin = $monthlyRecords->where('status', 'Izin')->count();
        $sakit = $monthlyRecords->where('status', 'Sakit')->count();
        $alpha = $monthlyRecords->where('status', 'Alpha')->count();
        $totalRecorded = $monthlyRecords->count();
        $pctHadir = $totalRecorded > 0 ? round((($hadir + $terlambat) / $totalRecorded) * 100, 1) : 0;

        $schoolSettings = SchoolSetting::getAllCached();

        return view('livewire.parent.parent-portal-show', [
            'student' => $student,
            'todayRecord' => $todayRecord,
            'monthlyRecords' => $monthlyRecords,
            'timelineRecords' => $timelineRecords,
            'stats' => [
                'hadir' => $hadir,
                'terlambat' => $terlambat,
                'izin' => $izin,
                'sakit' => $sakit,
                'alpha' => $alpha,
                'pctHadir' => $pctHadir,
            ],
            'school' => $schoolSettings,
            'monthLabel' => now()->translatedFormat('F Y'),
            'todayLabel' => now()->translatedFormat('l, d F Y'),
        ])->layout('components.layouts.guest');
    }
}
