<?php
    /*
            *****************************************************************************
            * MEGA Digital Space - by MEGA Digital Studio                               *
            * ------------------------------------------------------------------------- *
            * CMS Website:  https://megadigital.space                                   *
            * License:  https://megadigital.space/license                               *
            * Owner:  Giorgi Basharuli                                                  *
            * Contact:  online@megadigital.studio                                       *
            * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
            * Website:  https://megadigital.studio                                      *
            * ------------------------------------------------------------------------- *
            * Description: This file is a part of the MEGA Digital Space CMS system.    *
            * Unauthorized distribution, modification, or commercial use is strictly -  *
            * prohibited without prior written permission.                              *
            * ------------------------------------------------------------------------- *
            * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
            * All rights reserved.                                                      *
            *****************************************************************************
        */


    function teacherSchedulesController ()
    {
        global $db_connect, $smarty;

        $teacher_id = $_SESSION['user_id'] ?? null;
        $class_id = $_GET['class_id'] ?? null;
        if (!$teacher_id) {
            exit('NO_TEACHER');
        }

        /**
         * 1. ТЕКУЩАЯ НЕДЕЛЯ (можно брать из GET)
         */
        $baseDate = new DateTime($_GET['schedule_date'] ?? 'now');
        $baseDate->modify('monday this week');

        $scheduleDays = [];
        for ($i = 0; $i < 5; $i++) {
            $d = clone $baseDate;
            $d->modify("+{$i} day");

            $scheduleDays[] = [
                'label' => $d->format('d.m'),
                'day'   => $d->format('l'),
                'date'  => $d->format('Y-m-d'),
            ];
        }

        $weekStart = $scheduleDays[0]['date'];
        $weekEnd   = end($scheduleDays)['date'];


        if (empty($class_id)) {
            $class_id = $db_connect->get("teacher_classes", "class_id", [
                "teacher_id" => $teacher_id,
            ]);
        }

        /**
         * 2. ВРЕМЕННЫЕ СЛОТЫ ИЗ БД
         */
        $rowsStartEnds = $db_connect->select('schedules', [
            'starts',
            'ends'
        ], [
            'teacher_id' => $teacher_id,
            'class_id' => $class_id,
            'GROUP' => ['starts', 'ends'],
            'ORDER' => ['starts' => 'ASC']
        ]);

        $lessons = [];
        foreach ($rowsStartEnds as $r) {
            $lessons[] =
                substr($r['starts'], 0, 5) . ' – ' .
                substr($r['ends'], 0, 5);
        }

        /**
         * 3. РАСПИСАНИЕ УЧИТЕЛЯ ТОЛЬКО ЗА НЕДЕЛЮ
         */
        $rows = $db_connect->select('schedules', [
            '[>]classes'  => ['class_id' => 'id'],
            '[>]subjects' => ['subject_id' => 'id'],
            '[>]users' => ['teacher_id' => 'id'],
        ], [
            'schedules.schedule_date',
            'schedules.starts',
            'schedules.ends',
            'schedules.id(schedule_id)',
            'subjects.subject',
            'subjects.id(subject_id)',
            'users.name(teacher_name)',
            'classes.id(class_id)',
            'classes.name(class)',
        ], [
            'teacher_id' => $teacher_id,
            'class_id' => $class_id,
            'schedule_date[>=]' => $weekStart,
            'schedule_date[<=]' => $weekEnd,
            'ORDER' => ['starts' => 'ASC']
        ]);

        /**
         * 4. GRID: [schedule_date][lesson_index]
         */
        $schedule = [];

        foreach ($rows as $row) {

            $time = substr($row['starts'], 0, 5) . ' – ' . substr($row['ends'], 0, 5);
            $lessonIndex = array_search($time, $lessons, true);

            if ($lessonIndex === false) {
                continue;
            }

            $dateKey = $row['schedule_date'];

            $schedule[$dateKey][$lessonIndex] = [
                'subject' => $row['subject'],
                'class'   => $row['class'],
                'starts'  => $row['starts'],
                'ends'    => $row['ends'],
                'subject_id'    => $row['subject_id'],
                'class_id'    => $row['class_id'],
                'teacher_name'    => $row['teacher_name'],
                'schedule_date' => $row['schedule_date'],
                'schedule_id' => $row['schedule_id'],
            ];
        }

        /**
         * 5. LABEL НЕДЕЛИ (15–19, А НЕ 15–21)
         */
        $monthName = $baseDate->format('F');
        $year      = $baseDate->format('Y');

        $startDay = (int)date('j', strtotime($weekStart));
        $endDay   = (int)date('j', strtotime($weekEnd));

        $firstDayOfMonth = new DateTime($baseDate->format('Y-m-01'));
        $weekOfMonth = (int)ceil(
            (
                $startDay + (int)$firstDayOfMonth->format('N') - 1
            ) / 7
        );

        $teacherClasses = $db_connect->select(
            "teacher_classes",
            "class_id",
            ["teacher_id" => $teacher_id]
        );

        $classes = [];

        if (!empty($teacherClasses)) {
            // Получаем все данные классов
            $classes = $db_connect->select(
                "classes",
                "*",
                ["id" => $teacherClasses]
            );

            // Добавляем имя учителя к каждому классу
            $teacherName = $db_connect->get("users", "name", ["id" => $teacher_id]);
            foreach ($classes as &$class) {
                $class["teacherName"] = $teacherName;
            }
            unset($class); // Разрываем ссылку
        }


        $weekLabel = sprintf(
            '%s %s • %d–%d / Week %d',
            $monthName,
            $year,
            $startDay,
            $endDay,
            $weekOfMonth
        );

        /**
         * 6. В SMARTY
         */
        $smarty->assign([
            'schedulesDays' => $scheduleDays,
            'lessons'       => $lessons,
            'schedule'      => $schedule,
            'weekLabel'     => $weekLabel,
            'scheduleClasses' => $classes,
            'class_id' => $class_id
        ]);

        // $smarty->display('teacher/schedule.tpl');
    }


    function parentSchedulesController()
    {
        global $db_connect, $smarty;

        $parent_id = $_SESSION['user_id'] ?? null;
        if (!$parent_id) {
            exit('NO_PARENT');
        }

        /**
         * 1. НЕДЕЛЯ
         */
        $baseDate = new DateTime($_GET['schedule_date'] ?? 'now');
        $baseDate->modify('monday this week');

        $scheduleDays = [];
        for ($i = 0; $i < 5; $i++) {
            $d = clone $baseDate;
            $d->modify("+{$i} day");

            $scheduleDays[] = [
                'label' => $d->format('d.m'),
                'day'   => $d->format('l'),
                'date'  => $d->format('Y-m-d'),
            ];
        }

        $weekStart = $scheduleDays[0]['date'];
        $weekEnd   = end($scheduleDays)['date'];


        $children = $db_connect->select(
            'parents_students',
            [
                '[>]users' => ['student_id' => 'id'],
                '[>]class_students' => ['student_id' => 'student_id'],
                '[>]classes' => ['class_students.class_id' => 'id'],
            ],
            [
                'users.id(student_id)',
                'users.name(student_name)',
                'classes.id(class_id)',
                'classes.name(class_name)',
            ],
            [
                'parent_id' => $parent_id
            ]
        );

        if (empty($children)) {
            exit('NO_CHILDREN');
        }

        $selectedStudentId = $_GET['student_id'] ?? $children[0]['student_id'];

        $selectedChild = null;
        foreach ($children as $child) {
            if ($child['student_id'] == $selectedStudentId) {
                $selectedChild = $child;
                break;
            }
        }

        if (!$selectedChild) {
            exit('INVALID_STUDENT');
        }

        $classId = $selectedChild['class_id'];

        /**
         * 2. ДЕТИ РОДИТЕЛЯ
         */
        $studentIds = $db_connect->select(
            'parents_students',
            'student_id',
            ['parent_id' => $parent_id]
        );

        if (empty($studentIds)) {
            exit('NO_CHILDREN');
        }

        /**
         * 3. КЛАССЫ ДЕТЕЙ (class_students)
         */
        $classIds = $db_connect->select(
            'class_students',
            'class_id',
            ['student_id' => $studentIds]
        );

        $classIds = array_unique(array_filter($classIds));
        if (empty($classIds)) {
            exit('NO_CLASSES');
        }

        /**
         * 4. ВРЕМЕННЫЕ СЛОТЫ
         */
        $rowsStartEnds = $db_connect->select('schedules', [
            'starts',
            'ends'
        ], [
            'class_id' => $classIds,
            'GROUP' => ['starts', 'ends'],
            'ORDER' => ['starts' => 'ASC']
        ]);

        $lessons = [];
        foreach ($rowsStartEnds as $r) {
            $lessons[] =
                substr($r['starts'], 0, 5) . ' – ' .
                substr($r['ends'], 0, 5);
        }

        /**
         * 5. РАСПИСАНИЕ КЛАССОВ
         */
        $rows = $db_connect->select('schedules', [
            '[>]subjects' => ['subject_id' => 'id'],
            '[>]users'    => ['teacher_id' => 'id'],
        ], [
            'schedules.schedule_date',
            'schedules.starts',
            'schedules.ends',
            'subjects.subject',
            'users.name(teacher_name)',
        ], [
            'class_id' => $classId,
            'schedule_date[>=]' => $weekStart,
            'schedule_date[<=]' => $weekEnd,
            'ORDER' => ['starts' => 'ASC']
        ]);


        /**
         * 6. GRID [date][lessonIndex]
         */
        $schedule = [];

        foreach ($rows as $row) {

            $time = substr($row['starts'], 0, 5) . ' – ' . substr($row['ends'], 0, 5);
            $lessonIndex = array_search($time, $lessons, true);
            if ($lessonIndex === false) continue;

            $dateKey = $row['schedule_date'];

            $schedule[$dateKey][$lessonIndex] = [
                'subject' => $row['subject'],
                'class'   => $row['class'],
                'teacher_name' => $row['teacher_name'],
            ];
        }

        /**
         * 7. LABEL НЕДЕЛИ
         */
        $monthName = $baseDate->format('F');
        $year      = $baseDate->format('Y');

        $startDay = (int)date('j', strtotime($weekStart));
        $endDay   = (int)date('j', strtotime($weekEnd));

        $firstDayOfMonth = new DateTime($baseDate->format('Y-m-01'));
        $weekOfMonth = (int)ceil(
            ($startDay + (int)$firstDayOfMonth->format('N') - 1) / 7
        );

        $weekLabel = sprintf(
            '%s %s • %d–%d / Week %d',
            $monthName,
            $year,
            $startDay,
            $endDay,
            $weekOfMonth
        );

        /**
         * 8. В SMARTY
         */
        $smarty->assign([
            'scheduleChildren'        => $children,
            'selectedChild'   => $selectedChild,
            'schedulesDays'   => $scheduleDays,
            'lessons'         => $lessons,
            'schedule'        => $schedule,
            'weekLabel'       => $weekLabel,
        ]);


        // $smarty->display('parent/schedule.tpl');
    }


    function saveScheduleController() {

        global $db_connect, $config, $smarty;


        $teacher_id = $_SESSION['user_id'];


        $id = $_POST['schedule_id'] ?? null;
        $class_id = (int)$_POST['class_id'];
        $subject_id = $_POST['subject_id'] ?: null;
        $title = trim($_POST['title']);
        $day = (int)$_POST['day_of_week'];
        $starts = $_POST['starts'];
        $ends = $_POST['ends'];
        $schedule_date = $_POST['schedule_date'];


        if ($starts >= $ends) {
            //exit(json_encode(['error' => 'Неверный диапазон времени']));
        }


        // Проверка пересечений
        $where = [
            'class_id'    => $class_id,
            'schedule_date' => $_POST["schedule_date"],
            'starts[<]'   => $ends,
            'ends[>]'     => $starts,
        ];

        if ($id) {
            $where['id[!]'] = $id;
        }

        $conflict = $db_connect->count('schedules', $where);

        if ($conflict) {
           // exit(json_encode(['error' => 'Есть пересечение по времени']));
        }


        $data = [
            'class_id' => $class_id,
            'teacher_id'=> $teacher_id,
            'subject_id'=> $subject_id,
            'title' => $title,
            'day_of_week'=> $day,
            'starts' => $starts,
            'ends' => $ends,
            'schedule_date' => $schedule_date,
        ];


        if ($id) {
            $db_connect->update('schedules', $data, ['id' => $id]);
        } else {
            $db_connect->insert('schedules', $data);
        }


    }