<?php

namespace App\Controllers;


use App\Models\ClassAttendanceModel;
use App\Models\ClassDiaryModel;
use App\Models\ClassModel;
use App\Models\ClassStatusModel;
use App\Models\ClassStudentModel;
use App\Models\LessonModel;
use App\Models\StudentModel;

class Report_Class_Diary extends BaseController
{
    public function index()
    {
        $model = new ClassDiaryModel();

        $ClassDiaryModel = new ClassModel();
        $lessonModel = new LessonModel();
        $classStatusModel = new ClassStatusModel();
        $studentModel = new StudentModel();

        $data['students'] = $studentModel->whereIn('status', [1,2])->orderBy('first_name', 'ASC')->findAll();

        $data['classes'] = $ClassDiaryModel->whereIn('status', [1])->orderBy('created_datetime', 'DESC')->findAll();
        $data['lessons'] = $lessonModel->whereIn('status', [1])->orderBy('created_datetime', 'DESC')->findAll();
        $data['classstatuses'] = $classStatusModel->whereIn('status', [1])->orderBy('id', 'ASC')->findAll();

        $rows = $model->select("
                class_diary.*,
                class_diary.started_time AS started_time,
                class_diary.ended_time AS ended_time,
                class.name AS class_name,
                class.code AS class_code,
                grade.name AS grade_name,
                lesson.name AS lesson_name,
                lesson.code AS lesson_code,
                class_status.name AS class_status_name,

                student.id AS student_id,
                student.first_name,
                student.last_name,

                class_attendance.comment AS attendance_comment,
                class_attendance.attendance_status,
                class_attendance.duration,

                class_status.name AS class_status_name,
                class_status.id AS class_status_id
            ")
            ->join('class', 'class.id = class_diary.class_id', 'left')
            ->join('grade', 'grade.id = class.grade_id', 'left')
            ->join('class_status', 'class_status.id = class_diary.class_status_id', 'left')
            ->join('lesson', 'lesson.id = class_diary.lesson_id', 'left')
            ->join('class_attendance', 'class_attendance.class_diary_id = class_diary.id', 'left')
            ->join('student', 'student.id = class_attendance.student_id', 'left')
            ->where('class_diary.status', 1)
            ->where('class_attendance.attendance_status', 1)
            ->orderBy('class_diary.date', 'DESC')
            ->findAll();

        // Convert to Nested Array Here
        $classDiaries = [];

        foreach ($rows as $row) {

            $diaryId = $row['id'];

            if (!isset($classDiaries[$diaryId])) {

                $classDiaries[$diaryId] = [
                    // class_diary
                    'id'                => $row['id'],
                    'class_id'          => $row['class_id'],
                    'lesson_id'         => $row['lesson_id'],
                    'date'              => $row['date'],
                    'started_time'      => $row['started_time'],
                    'ended_time'        => $row['ended_time'],
                    'comment'           => $row['comment'],
                    'payment_status'    => $row['payment_status'],
                    'status'            => $row['status'],
                    'class_status_id'   => $row['class_status_id'],

                    // class
                    'class_name'        => $row['class_name'],
                    'class_code'        => $row['class_code'],

                    // grade
                    'grade_name'        => $row['grade_name'],

                    // lesson
                    'lesson_name'       => $row['lesson_name'],
                    'lesson_code'       => $row['lesson_code'],

                    // class status
                    'class_status_name' => $row['class_status_name'],

                    // students array
                    'students'          => []
                ];
            }

            $classDiaries[$diaryId]['students'][] = [
                'student_id' => $row['student_id'],
                'name' => $row['first_name'] . ' ' . $row['last_name'],
                'comment' => $row['attendance_comment'],
                'attendance_status' => $row['attendance_status'],
                'duration' => $row['duration']
            ];
        }

        $data['classdiaries'] = $classDiaries;



//            $model->select("
//        class_diary.*,
//        class.name AS class_name,
//        class.code AS class_code,
//        grade.name AS grade_name,
//        lesson.name AS lesson_name,
//        lesson.code AS lesson_code,
//        class_status.name AS class_status_name,
//        class_status.id AS class_status_id,
//        payment_type.name AS payment_type_name,
//        student.first_name AS student_first_name,
//        student.last_name AS student_last_name,
//        GROUP_CONCAT(
//        CONCAT(student.first_name, ' ', student.last_name, ' (', class_attendance.comment, ')')
//        ORDER BY student.first_name
//        SEPARATOR '<br> '
//    ) AS student_names
//
//    ")
//            ->join('class', 'class.id = class_diary.class_id', 'left')
//            ->join('class_status', 'class_status.id = class_diary.class_status_id', 'left')
//            ->join('grade', 'grade.id = class.grade_id', 'left')
//            ->join('lesson', 'lesson.id = class_diary.lesson_id', 'left')
//            ->join('payment_type', 'payment_type.id = class.payment_type_id', 'left')
//            ->join('class_attendance', 'class_attendance.class_diary_id = class_diary.id', 'left')
//            ->join('student', 'student.id = class_attendance.student_id', 'left')
//            ->whereIn('class_diary.status', [1])
//            ->whereIn('class_attendance.attendance_status', [1])
//            ->orderBy('class_diary.date', 'DESC')
//            ->groupBy('class_diary.id')
//            ->findAll();

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

    public function save()
    { 
        $model = new ClassDiaryModel();
        $classAttendancemodel = new ClassAttendanceModel();

        $result = $model->save([
            'comment'        => $this->request->getPost('comment'),
            'date'           => $this->request->getPost('date'),
            'started_time'   => $this->request->getPost('started_time'),
            'ended_time'     => $this->request->getPost('ended_time'),
            'status'         => $this->request->getPost('status'),
            //'payment_status' => $this->request->getPost('payment_status'),
            'class_id'       => $this->request->getPost('class_id'),
            'lesson_id'      => $this->request->getPost('lesson_id'),
            'class_status_id'      => $this->request->getPost('class_status_id')
        ]);

        $classDiaryId = $model->getInsertID();

//        $result_class_attendance = $classAttendancemodel->save([
//
//            'comment'        => $this->request->getPost('comment'),
//            'date'           => $this->request->getPost('date'),
//            'status'         => $this->request->getPost('status'),
//        ]);

        $studentIds = $this->request->getPost('student_id');

        $data = [];

        foreach ($studentIds as $studentId) {

            $data[] = [
                'class_diary_id'        => $classDiaryId,
                'class_id' => $this->request->getPost('class_id'),
                'student_id' => $studentId,
                'attendance_status' =>
                    $this->request->getPost('attendance')[$studentId] ?? 0,
                'duration' =>
                    $this->request->getPost('duration')[$studentId] ?? 0,
                'comment' =>
                    $this->request->getPost('student_comment')[$studentId] ?? '',
                'date' => $this->request->getPost('date'),
                'status' => 1
            ];
        }

        $classAttendancemodel->insertBatch($data);

        if ($result) {
            session()->setFlashdata(
                'success',
                'Class Diary saved successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Unable to save Class Diary.'
            );
        }

        return redirect()->to('/classdiary');
    }

    public function get($id)
    {
        $model = new ClassDiaryModel();

        $data = $model->find($id);

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

    public function getStudentByStudentId()
    {
        $classDiaryModel = new ClassDiaryModel();

        $studentId = $this->request->getPost('student');

        $data['classdiaries'] = $classDiaryModel
            ->select("
                class_diary.*,
                class.name AS class_name,
                class.code AS class_code,
                lesson.name AS lesson_name,
                lesson.code AS lesson_code,
                class_attendance.attendance,
                class_attendance.duration,
                class_attendance.comment AS attendance_comment
            ")      ->join(
                        'class_attendance',
                        'class_attendance.class_diary_id = class_diary.id'
                    )
                    ->join(
                        'class',
                        'class.id = class_diary.class_id',
                        'left'
                    )
                    ->join(
                        'lesson',
                        'lesson.id = class_diary.lesson_id',
                        'left'
                    )
                    ->where('class_attendance.student_id', $studentId)
                    ->whereIn('class_diary.status', [1, 2])
                    ->orderBy('class_diary.date', 'DESC')
                    ->findAll();

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

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

        $lessons = $db->table('lesson l')
            ->select('l.id, l.code, l.name')
            ->join('class c', 'c.grade_id = l.grade_id')
            ->where('c.id', $id)
            ->where('l.status', 1)
            ->get()
            ->getResultArray();

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

    public function getStudentsByClassId($classId)
    {
        $db = \Config\Database::connect();

        $students = $db->table('student s')
            ->select('s.id, s.first_name AS first_name, s.last_name')
            ->join('class_student sc', 'sc.student_id = s.id')
            ->where('sc.class_id', $classId)
            ->orderBy('s.first_name', 'ASC')
            ->get()
            ->getResultArray();

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

    public function update()
    {
        $model = new ClassDiaryModel();
        $classStudentModel = new ClassStudentModel();

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

        $result = $model->update($id, [
            'comment'        => $this->request->getPost('updcomment'),
            'date'           => $this->request->getPost('upddate'),
            'started_time'   => $this->request->getPost('updstarted_time'),
            'ended_time'     => $this->request->getPost('updended_time'),
            'status'         => $this->request->getPost('updstatus'),
            'payment_status' => $this->request->getPost('updpayment_status'),
            'class_id'       => $this->request->getPost('updclass_id'),
            'lesson_id'      => $this->request->getPost('updlesson_id'),
            'class_status_id'      => $this->request->getPost('updclass_status_id')
        ]);

        if ($result) {
            session()->setFlashdata(
                'success',
                'Class Diary updated successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Unable to update Class Diary.'
            );
        }

        return redirect()->to('/classdiary');
    }

    public function delete()
    {
        $model = new ClassDiaryModel();

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

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

        if ($result) {
            session()->setFlashdata(
                'success',
                'Class Diary deleted successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Unable to delete Class Diary.'
            );
        }

        return redirect()->to('/classdiary');
    }
}