<?php

namespace App\Http\Controllers\View;

use App\Http\Controllers\Controller;
use App\Models\ClassSection;
use App\Models\Configuration;
use App\Models\Student;
use App\Models\Teacher;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class ClassController extends Controller
{
    protected ClassSection $classSection;
    protected Student $student;
    protected Teacher $teacher;
    protected Configuration $config;
    protected ?string $semester;
    protected ?string $schoolYear;

    public function __construct(
        ClassSection $classSection,
        Student $student,
        Teacher $teacher,
        Configuration $config
    ) {
        $this->classSection = $classSection;
        $this->student      = $student;
        $this->teacher      = $teacher;
        $this->config       = $config;

        $this->semester   = $this->config->getConfig('semester');
        $this->schoolYear = $this->config->getConfig('school_year');
    }

    public function index(): View
    {
        $classSections = $this->classSection
            ->newQuery()
            ->orderBy('class_section_name', 'ASC')
            ->get();

        return view('administrator.class_section', [
            'classsection' => $classSections,
        ]);
    }

    public function create(): View
    {
        return view('administrator.create_class');
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->only(['name', 'description']);
        // TODO: persist the payload once the backing model/table columns are finalized.

        return redirect()->to('/administrator/classes')->with([
            'payload' => $data,
        ]);
    }

    public function edit(int $id): View
    {
        return view('administrator.edit_class', [
            'class' => $this->classSection->find($id),
        ]);
    }

    public function updateClass(Request $request, int $id): RedirectResponse
    {
        $data = $request->only(['name', 'description']);
        // TODO: persist the payload once the backing model/table columns are finalized.

        return redirect()->to('/administrator/classes')->with([
            'payload' => $data,
            'id'      => $id,
        ]);
    }

    public function destroyClass(int $id): RedirectResponse
    {
        // TODO: remove the record once the backing model/table columns are finalized.

        return redirect()->to('/administrator/classes')->with([
            'deleted_id' => $id,
        ]);
    }

    public function addClasses(): RedirectResponse
    {
        $classes = [
            ['class_name' => 'Class 1', 'teacher_id' => 1, 'schedule' => 'Monday 9:00 AM - 10:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 2', 'teacher_id' => 2, 'schedule' => 'Tuesday 9:00 AM - 10:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 3', 'teacher_id' => 3, 'schedule' => 'Wednesday 9:00 AM - 10:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 4', 'teacher_id' => 4, 'schedule' => 'Thursday 9:00 AM - 10:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 5', 'teacher_id' => 5, 'schedule' => 'Friday 9:00 AM - 10:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 6', 'teacher_id' => 6, 'schedule' => 'Monday 10:00 AM - 11:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 7', 'teacher_id' => 7, 'schedule' => 'Tuesday 10:00 AM - 11:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 8', 'teacher_id' => 8, 'schedule' => 'Wednesday 10:00 AM - 11:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 9', 'teacher_id' => 9, 'schedule' => 'Thursday 10:00 AM - 11:00 AM', 'capacity' => 30],
            ['class_name' => 'Youth', 'teacher_id' => 10, 'schedule' => 'Friday 10:00 AM - 11:00 AM', 'capacity' => 30],
        ];

        DB::transaction(function () use ($classes) {
            foreach ($classes as $class) {
                DB::table('classes')->insert($class);
            }
        });

        return redirect()->to('/parent/classes')->with('success', 'Classes added successfully.');
    }

    public function classAttendance(int $classSectionId): RedirectResponse|View
    {
        $teacherId = (int) (session()->get('user_id') ?? 0);
        if ($teacherId <= 0) {
            return redirect()->to('/teacher/classes')->with('error', 'Missing teacher session.');
        }

        $teacherData = $this->teacher->find($teacherId);

        $studentsData = $this->student->newQuery()
            ->join('student_class', 'students.id', '=', 'student_class.student_id')
            ->leftJoin('class_sections', 'class_sections.id', '=', 'student_class.class_section_id')
            ->where('student_class.class_section_id', $classSectionId)
            ->select('students.*', 'student_class.class_section_id', 'class_sections.class_section_name')
            ->get()
            ->toArray();

        $className = $studentsData[0]['class_section_name'] ?? 'Class Name Not Available';

        if (empty($teacherData) || empty($studentsData)) {
            return redirect()->to('/teacher/classes')->with('error', 'No data found for this class.');
        }
        $teacherFirst = $teacherData['teacher_first'] ?? $teacherData['firstname'] ?? '';
        $teacherLast  = $teacherData['teacher_last'] ?? $teacherData['lastname'] ?? '';

        return view('teacher.classes', [
            'teacher_name'     => trim($teacherFirst . ' ' . $teacherLast),
            'students'         => $studentsData,
            'class_name'       => $className,
            'semester'         => $this->semester,
            'class_section_id' => $classSectionId,
        ]);
    }
}
