<?php
namespace App\Controllers;

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

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

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

        $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();


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

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

        $rows = $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,
    
            GROUP_CONCAT(
                CONCAT(
                    student.first_name,
                    ' ',
                    student.last_name,
                    ' (',
                    class_attendance.comment,
                    ')'
                )
                ORDER BY student.first_name
                SEPARATOR '<br>'
            ) AS student_names
        ", false)
                ->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')
                ->where('class_diary.status', 1)
                ->groupBy('class_diary.id')
                ->orderBy('class_diary.date', 'DESC')
                ->orderBy('class_diary.started_time', 'DESC')
                ->findAll();

            $data = [];

            foreach ($rows as $item) {

                $dateTime =
                    date('Y-m-d', strtotime($item['date'])) .
                    '<br>' .
                    date('h:i A', strtotime($item['started_time'])) .
                    ' - ' .
                    date('h:i A', strtotime($item['ended_time']));

                $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[] = [
                    $dateTime,
                    $item['class_name'],
                    $item['lesson_name'],
                    $item['student_names'],
                    $item['comment'],
                    getClassStatusName($item['class_status_id']),
                    $actions
                ];
            }

            return $this->response->setJSON([
                'data' => $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) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Class diary saved successfully.'
            ]);
        } else {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Unable to save class diary.'
            ]);
        }
    }

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

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

        return $this->response->setJSON($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);
    }

    //get class day and times by class id
    public function getClassDayByClassId($classId)
    {
        $classDayModel = new ClassDayModel();

        $firstDay = $classDayModel
            ->select('day_id, start_time, end_time')
            ->where('class_id', $classId)
            ->where('status', 1)
            ->first();

        $data['selected_day_id'] = $firstDay['day_id'] ?? '';
        $data['start_time'] = $firstDay['start_time'] ?? '';
        $data['end_time'] = $firstDay['end_time'] ?? '';

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

    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) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Class diary deleted successfully.'
            ]);
        } else {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Unable to delete class diary.'
            ]);
        }
    }
}