<?php

namespace App\Controllers;


use App\Models\ClassDayModel;
use App\Models\ClassModel;
use App\Models\ClassStudentModel;
use App\Models\ClassTypeModel;
use App\Models\GradeModel;
use App\Models\PaymentTypeModel;
use App\Models\StudentModel;
use App\Models\UserRoleModel;

class Class_Controller extends BaseController
{
    public function index()
    {
        $data['title'] = 'Class';
        $model = new ClassModel();

        $classTypeModel = new ClassTypeModel();
        $paymentTypeModel = new PaymentTypeModel();
        $gradeModel = new GradeModel();
        $studentModel = new StudentModel();

        $data['grades'] = $gradeModel->whereIn('status', [1])->orderBy("CAST(REPLACE(name, 'Grade ', '') AS UNSIGNED)", '', false)->findAll();
        $data['paymenttypes'] = $paymentTypeModel->whereIn('status', [1])->orderBy('created_datetime', 'DESC')->findAll();
        $data['classtypes'] = $classTypeModel->whereIn('status', [1])->orderBy('created_datetime', 'DESC')->findAll();
        $data['students'] = $studentModel->whereIn('status', [1])->orderBy('created_datetime', 'DESC')->findAll();

        return view('class', $data);
    }

    public function getDataTable(){
        helper('status');
        $model = new ClassModel();

        $classes = $model
            ->select("
            class.*,
            class_type.name AS class_type_name,
            grade.name AS grade_name,

            GROUP_CONCAT(
                DISTINCT CONCAT(
                    student.first_name,' ',
                    student.last_name,
                    ' (', class_student.fee, ')'
                )
                SEPARATOR '<br>'
            ) AS student_names,

            GROUP_CONCAT(
                DISTINCT CONCAT(
                    day.name,
                    ' (',
                    TIME_FORMAT(class_day.start_time,'%h:%i %p'),
                    ' - ',
                    TIME_FORMAT(class_day.end_time,'%h:%i %p'),
                    ')'
                )
                SEPARATOR '<br>'
            ) AS class_days
        ", false)
            ->join('class_type','class_type.id=class.class_type_id','left')
            ->join('grade','grade.id=class.grade_id','left')
            ->join('class_student','class_student.class_id=class.id','left')
            ->join('student','student.id=class_student.student_id','left')
            ->join('class_day','class_day.class_id=class.id','left')
            ->join('day','day.id=class_day.day_id','left')
            ->whereIn('class.status',[1,2])
            ->groupBy('class.id')
            ->orderBy('grade.name', 'DESC')
            ->findAll();

        $data = [];

        foreach ($classes as $item) {

            $actions = '
            <button id="btnUpdate"
                    data-id="'.$item['id'].'"
                    data-bs-toggle="modal"
                    data-bs-target="#updateModal"
                    style="padding: 3px 3px; width: 30px; height: 30px;"
                    class="btn btn-secondary btn-circle">
                <i class="fa fa-pencil-alt"></i>
            </button>

            <button id="btnDelete"
                    data-id="'.$item['id'].'"
                    data-bs-toggle="modal"
                    data-bs-target="#deleteModal"
                    style="padding: 3px 3px; width: 30px; height: 30px;"
                    class="btn btn-danger btn-circle">
                <i class="fa fa-trash"></i>
            </button>';

            $data[] = [
                $item['code'],
                $item['name'],
                $item['grade_name'],
                $item['class_type_name'],
                $item['class_days'],
                $item['student_names'],
                getStatusName($item['status']),
                $actions
            ];
        }

        return $this->response->setJSON([
            'data' => $data
        ]);
    }

    public function save()
    {
        $model = new ClassModel();
        $classStudentModel = new ClassStudentModel();
        $classdaymodel = new ClassDayModel();

        $result = $model->save([
            'name'            => $this->request->getPost('name'),
            'code'            => strtoupper($this->request->getPost('code')),
            'description'     => $this->request->getPost('description'),
            'started_date'    => $this->request->getPost('started_date'),
            'start_time'      => $this->request->getPost('start_time'),
            'end_time'        => $this->request->getPost('end_time'),
            'status'          => $this->request->getPost('status'),
            'class_type_id'   => $this->request->getPost('class_type_id'),
            'payment_type_id' => $this->request->getPost('payment_type_id'),
            'grade_id'        => $this->request->getPost('grade_id'),
        ]);

        //get the last saved class id
        $classId = $model->getInsertID();

        //getting student id and fee array then save to class_student
        $studentIds = $this->request->getPost('student_id');
        $fees = $this->request->getPost('fee');

        $data = [];

        foreach ($studentIds as $studentId) {

            $data[] = [
                'class_id'   => $classId,
                'student_id' => $studentId,
                'fee'        => $fees[$studentId],
                'status'     => 1
            ];
        }

        $classStudentModel->insertBatch($data);

        //getting class day and start end times array then save to class_day
        $dayIds = $this->request->getPost('dayId');
        $startTimes = $this->request->getPost('startTime');
        $endTimes = $this->request->getPost('endTime');

        $data = [];

        foreach ($dayIds as $dayId) {

            $data[] = [
                'class_id'   => $classId,
                'day_id' => $dayId,
                'start_time' => $startTimes[$dayId],
                'end_time'   => $endTimes[$dayId],
                'status'     => 1
            ];
        }

        $classdaymodel->insertBatch($data);

        if ($result) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Class saved successfully.'
            ]);
        } else {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Unable to save class.'
            ]);
        }
    }

    public function get($id)
    {
        $classModel = new ClassModel();
        $classStudentModel = new ClassStudentModel();
        $classDayModel = new ClassDayModel();

        $class = $classModel->find($id);

        //getting students
        $students = $classStudentModel
            ->select('student_id, fee')
            ->where('class_id', $id)
            ->where('status', 1)
            ->findAll();

        $class['students'] = $students;

        //getting days
        $days = $classDayModel
            //->select('day_id, start_time, end_time')
            ->where('class_id', $id)
            ->where('status', 1)
            ->findAll();

        $class['class_days'] = $days;

        return $this->response->setJSON($class);
    }

    public function getStudents($id)
    {
        $db = \Config\Database::connect();

        $studentIds = $db->table('class_student')
            ->select('student_id')
            ->where('class_id', $id)
            ->get()
            ->getResultArray();

        $response['student_ids'] = array_column($studentIds, 'student_id');

        return $this->response->setJSON($response);
    }

    public function update()
    {
        $model = new ClassModel();
        $classStudentModel = new ClassStudentModel();
        $classDayModel = new ClassDayModel();

        $id = $this->request->getPost('updid');

        $result = $model->update($id, [
            'name'            => $this->request->getPost('updname'),
            'code'            => strtoupper($this->request->getPost('updcode')),
            'description'     => $this->request->getPost('upddescription'),
            'started_date'    => $this->request->getPost('updstarted_date'),
            'start_time'      => $this->request->getPost('updstart_time'),
            'end_time'        => $this->request->getPost('updend_time'),
            'status'          => $this->request->getPost('updstatus'),
            'class_type_id'   => $this->request->getPost('updclass_type_id'),
            'payment_type_id' => $this->request->getPost('updpayment_type_id'),
            'grade_id'        => $this->request->getPost('updgrade_id'),
        ]);

        //delete the relevant records from class_student
        $classStudentModel->where('class_id', $id)->delete();

        //add records
        //getting student id and fee array
        $studentIds = $this->request->getPost('updstudent_id');
        $fees = $this->request->getPost('fee');

        foreach ($studentIds as $studentId) {

            $classStudentModel->save([
                'class_id'   => $id,
                'student_id' => $studentId,
                'fee' => $fees[$studentId] ?? 0,
                'status' => 1
            ]);
        }

        //delete the relevant records from class_day
        $classDayModel->where('class_id', $id)->delete();

        //add records
        //getting student id and fee array
        $dayIds = $this->request->getPost('day_id') ?? [];

        $startTimes = $this->request->getPost('start_time') ?? [];

        $endTimes = $this->request->getPost('end_time') ?? [];


        foreach($dayIds as $dayId){

            $classDayModel->save([

                'class_id'   => $id,
                'day_id'     => $dayId,
                'start_time' => $startTimes[$dayId],
                'end_time'   => $endTimes[$dayId],
                'status'     => 1

            ]);

        }

        if ($result) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Class updated successfully.'
            ]);
        } else {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Unable to update class.'
            ]);
        }
    }

    public function delete()
    {
        $model = new ClassModel();
        $classStudentModel = new ClassStudentModel();
        $classDayModel = new ClassDayModel();

        $id = $this->request->getPost('delid');

        $result = $model->update($id, [
            'status' => 3
        ]);

        $result_class_student = $classStudentModel
            ->where('class_id', $id)
            ->set(['status' => 3])
            ->update();

        $result_class_day = $classDayModel
            ->where('class_id', $id)
            ->set(['status' => 3])
            ->update();

        if ($result) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Class deleted successfully.'
            ]);
        } else {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Unable to delete class.'
            ]);
        }
    }
}