<?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.                                                      *
        *****************************************************************************
    */

    // Путь к config.php относительно текущего файла
    require_once(ENGINE_DIR . '/data/config.php');

    global $db_connect, $lang, $smarty;


    $teacher_id = $_SESSION['user_id'] ?? null;
    $class_id = $_GET['class_id'] ?? null;

    /**
     * 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");
    }

    /**
     * 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
    );

    $classes = [];
    $classes = $db_connect->select("classes", "*");

    // Добавляем имя учителя к каждому классу
    $teacherName = $db_connect->get("users", "name");
    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
    ]);
/*
    $addModalHtml = $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/extensions/education/schedules/add_schedule.tpl');

    $smarty->assign("modalHtml", $addModalHtml);*/

    $smarty->registerPlugin('modifier', 'json_encode', function($value) {
        return json_encode($value);
    });
    $smarty->assign('teachers', $teachersDataAssoc);
    $smarty->assign('subjects', $subjects);
    $yourData = array('title' => "Предметы" . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
        <li class="breadcrumb-item active">' . "Предметы" . '</li>
    ');
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);