<?php

namespace App\Controllers\View;
use App\Controllers\BaseController;
use App\Models\ClassSectionModel;
use App\Models\StudentModel;
use App\Models\TeacherModel;
use App\Models\ConfigurationModel;

class ClassController extends BaseController
{
    protected $classsectionModel;
    protected $studentModel;
    protected $teacherModel;
    protected $configModel;
    protected $semester;
    protected $schoolYear;

    protected $db;

    public function __construct(private \CodeIgniter\HTTP\IncomingRequest $request)
    {
        $this->db = \Config\Database::connect();
        $this->classsectionModel = new ClassSectionModel();

        // Load necessary models
        $this->studentModel = new StudentModel();
        $this->teacherModel = new TeacherModel();
        $this->configModel = new ConfigurationModel();

        // Get the semester from the configuration table
        $this->semester  = $this->configModel->getConfig('semester');
        $this->schoolYear = $this->configModel->getConfig('school_year');
    }

    public function index()
    {
        // Retrieve all classes from the database
        $classsection = $this->classsectionModel->getAllClasses();
        // Pass the classes to the view
        return view('administrator/class_section', ['classsection' => $classsection]);
    }

    public function create()
    {
        // Show the form to create a new class
        return view('administrator/create_class');
    }

    public function store()
    {
        // Handle the form submission to create a new class
        $data = [
            'name' => $this->request->getPost('name'),
            'description' => $this->request->getPost('description'),
        ];
        //$this->classModel->createClass($data);
        return redirect()->to('/administrator/classes');
    }

    public function edit($id)
    {
        // Retrieve the class details to edit
        //$class = $this->ClassSectionModel->getClassById($id);
        //return view('administrator/edit_class', ['class' => $class]);
    }

    public function updateClass($id)
    {
        // Handle the form submission to update an existing class
        $data = [
            'name' => $this->request->getPost('name'),
            'description' => $this->request->getPost('description'),
        ];
        //$this->classModel->updateClass($id, $data);
        return redirect()->to('/administrator/classes');
    }

    public function destroyClass($id)
    {
        // Delete the class
        //$this->classModel->deleteClass($id);
        return redirect()->to('/administrator/classes');
    }

    public function addClasses()
    {
        // Include the shared database connection file
        $file = __DIR__ . '/../db_connection.php';

        if (file_exists($file)) {
            require_once $file;
        } else {
            die("Error: Could not find the required file '$file'.");
        }


        $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],
        ];

        foreach ($classes as $class) {
            $stmt = $conn->prepare("INSERT INTO classes (class_name, teacher_id, schedule, capacity) VALUES (?, ?, ?, ?)");
            if (!$stmt) {
                die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
            }
            $stmt->bind_param("sisi", $class['class_name'], $class['teacher_id'], $class['schedule'], $class['capacity']);
            $stmt->execute();
            $stmt->close();
        }

        $conn->close();

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

    public function classAttendance($class_section_id)
    {
        // Get the teacher's ID from the session
        $teacherId = session()->get('user_id');

        // Fetch teacher data
        $teacherData = $this->teacherModel->find($teacherId);

        // Fetch students for the class
        $studentsData = $this->studentModel->join('student_class', 'students.id = student_class.student_id')
            ->where('student_class.class_section_id', $class_section_id)
            ->select('students.*, student_class.class_section_id')
            ->findAll();

        // Get class name (assuming it's stored in the students data)
        $className = !empty($studentsData) && isset($studentsData[0]['class_name']) ? $studentsData[0]['class_name'] : 'Class Name Not Available';

        // Check if the teacher data and students data are available
        if (empty($teacherData) || empty($studentsData)) {
            return redirect()->to('/teacher/classes')->with('error', 'No data found for this class.');
        }

        // Pass data to the view
        return view('/teacher/classes', [
            'teacher_name' => $teacherData['teacher_first'] . ' ' . $teacherData['teacher_last'],
            'students' => $studentsData,
            'class_name' => $className,
            'semester' => $this->semester,
            'class_section_id' => $class_section_id,  // Pass the class_id for attendance update forms
        ]);
    }
}
