<?php

namespace App\Services\Payments;

use App\Models\Configuration;
use App\Models\Enrollment;
use App\Models\StudentClass;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class PaymentEventChargesService
{
    public function listCharges(?string $schoolYear, ?string $semester): array
    {
        $schoolYear = $schoolYear ?: Configuration::getConfig('school_year');
        $semester = $semester ?: Configuration::getConfig('semester');

        $charges = DB::table('event_charges')
            ->select(
                'event_charges.*',
                'users.firstname AS parent_firstname',
                'users.lastname AS parent_lastname',
                'students.firstname AS student_firstname',
                'students.lastname AS student_lastname'
            )
            ->leftJoin('users', 'users.id', '=', 'event_charges.parent_id')
            ->leftJoin('students', 'students.id', '=', 'event_charges.student_id')
            ->where('event_charges.school_year', $schoolYear)
            ->where('event_charges.semester', $semester)
            ->orderByDesc('event_charges.created_at')
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();

        return [
            'charges' => $charges,
            'parents' => User::getParents(),
            'school_year' => $schoolYear,
            'semester' => $semester,
        ];
    }

    public function addCharges(array $payload, int $userId): int
    {
        $studentIds = $payload['student_ids'] ?? [];
        $parentId = (int) $payload['parent_id'];

        $commonData = [
            'parent_id' => $parentId,
            'event_name' => $payload['event_name'],
            'description' => $payload['description'] ?? null,
            'amount' => (float) $payload['amount'],
            'semester' => $payload['semester'],
            'school_year' => $payload['school_year'],
            'charged' => 0,
            'updated_by' => $userId,
            'created_at' => now(),
            'updated_at' => now(),
        ];

        $count = 0;

        if (!empty($studentIds)) {
            foreach ($studentIds as $studentId) {
                DB::table('event_charges')->insert(array_merge($commonData, [
                    'student_id' => (int) $studentId,
                ]));
                $count++;
            }
        } elseif (!empty($payload['student_id'])) {
            DB::table('event_charges')->insert(array_merge($commonData, [
                'student_id' => (int) $payload['student_id'],
            ]));
            $count++;
        }

        return $count;
    }

    public function getEnrolledStudents(int $parentId, ?string $schoolYear): array
    {
        $schoolYear = $schoolYear ?: Configuration::getConfig('school_year');

        $enrollments = Enrollment::getEnrolledStudents($parentId, $schoolYear);

        $students = [];
        foreach ($enrollments as $row) {
            $students[] = [
                'id' => (int) ($row->id ?? 0),
                'firstname' => (string) ($row->firstname ?? ''),
                'lastname' => (string) ($row->lastname ?? ''),
                'grade' => StudentClass::getStudentGrade((int) ($row->id ?? 0)) ?: 'N/A',
            ];
        }

        return $students;
    }
}
