<?php

namespace App\Livewire\Guardian;

use App\Domain\Attendance\Models\AttendanceRecord;
use App\Domain\Financial\Models\Invoice;
use App\Domain\Identity\Models\Guardian;
use App\Domain\Participant\Models\Participant;
use App\Domain\Training\Enums\SessionStatus;
use App\Domain\Training\Models\TrainingSession;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('بوابة ولي الأمر')]
class GuardianDashboard extends Component
{
    public function mount(): void
    {
        // Guardian role doesn't have a specific permission — guard by role check
        $user = auth()->user();

        if (! $user->person_id) {
            abort(403, __('لا يوجد ملف شخصي مرتبط بحسابك'));
        }

        // Ensure user is actually a guardian
        $guardian = Guardian::where('person_id', $user->person_id)->first()
            ?? Guardian::where('user_id', $user->id)->first();

        if (! $guardian) {
            abort(403, __('هذه الصفحة مخصصة لأولياء الأمور فقط'));
        }
    }

    public function render()
    {
        $user = auth()->user();

        // Find guardian record for this user
        $guardian = Guardian::where('person_id', $user->person_id)->first()
            ?? Guardian::where('user_id', $user->id)->first();

        // Get participant IDs for this guardian's children
        $participantIds = $guardian->participants()->pluck('participants.id');

        // Load children with their person data and active enrollments
        $children = Participant::whereIn('id', $participantIds)
            ->with(['person', 'activeEnrollments.group', 'activeEnrollments.program'])
            ->get();

        // Calculate attendance rates per child
        $attendanceData = [];
        foreach ($children as $child) {
            $totalRecords = AttendanceRecord::where('subject_type', Participant::class)
                ->where('subject_id', $child->id)
                ->whereNotIn('status', ['cancelled', 'exempt'])
                ->count();

            $positiveRecords = AttendanceRecord::where('subject_type', Participant::class)
                ->where('subject_id', $child->id)
                ->whereIn('status', ['present', 'late', 'partial'])
                ->count();

            $attendanceData[$child->id] = [
                'rate' => $totalRecords > 0 ? round(($positiveRecords / $totalRecords) * 100, 1) : null,
                'total' => $totalRecords,
                'positive' => $positiveRecords,
            ];
        }

        // Upcoming sessions for children's active groups
        $activeGroupIds = $children->flatMap(function ($child) {
            return $child->activeEnrollments->pluck('training_group_id');
        })->unique()->filter();

        $upcomingSessions = TrainingSession::whereIn('training_group_id', $activeGroupIds)
            ->where('session_date', '>=', now()->toDateString())
            ->where('status', SessionStatus::Scheduled)
            ->with('group')
            ->orderBy('session_date')
            ->orderBy('start_time')
            ->limit(10)
            ->get();

        // Invoices for children (billable = Participant)
        $invoices = Invoice::where('billable_type', Participant::class)
            ->whereIn('billable_id', $participantIds)
            ->orderByDesc('issue_date')
            ->limit(20)
            ->get();

        // Outstanding balance
        $totalOutstanding = Invoice::where('billable_type', Participant::class)
            ->whereIn('billable_id', $participantIds)
            ->whereIn('status', ['sent', 'partially_paid', 'overdue'])
            ->sum('due_amount');

        // Total paid
        $totalPaid = Invoice::where('billable_type', Participant::class)
            ->whereIn('billable_id', $participantIds)
            ->sum('paid_amount');

        return view('livewire.guardian.guardian-dashboard', [
            'children' => $children,
            'attendanceData' => $attendanceData,
            'upcomingSessions' => $upcomingSessions,
            'invoices' => $invoices,
            'totalOutstanding' => $totalOutstanding,
            'totalPaid' => $totalPaid,
        ]);
    }
}
