<?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');
    require_once(ENGINE_DIR . '/mods/permission.php');

    global $db_connect, $lang, $smarty;

    if (!hasPermission($_SESSION["user_id"], "grades.view")) {
        displayError("У вас нет доступа к школьной успеваемости", "Доступ запрещен");
        exit();
    }

    $classId   = (int)($_GET['class_id'] ?? 0);
    $subjectId = (int)($_GET['subject_id'] ?? 0);
    $period    = $_GET['period'] ?? date('Y-m-d');

    $classes = $db_connect->select("teacher_classes", [
        "[>]classes" => ["class_id" => "id"]
    ], [
        "classes.id",
        "classes.name"
    ]/*, [
        "teacher_classes.teacher_id" => $_SESSION['user_id']
    ]*/);

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

    $students = [];
    if ($classId) {
        $students = $db_connect->select("class_students", [
            "[>]users" => ["student_id" => "id"]
        ], [
            "users.id",
            "users.name"
        ], [
            "class_students.class_id" => $classId
        ]);
    }

    $teacherSubjects = $db_connect->select("teacher_subjects", "subject_id"/*, [
        "teacher_id" => $_SESSION['user_id']
    ]*/);

    $subjects = [];
    if ($teacherSubjects) {
        $subjects = $db_connect->select("subjects", "*", [
            "id" => $teacherSubjects
        ]);
    }

    $diary = null;
    if ($classId && $subjectId) {
        $diary = buildDiaryGrid(
            $db_connect,
            $_SESSION['user_id'],
            $classId,
            $subjectId,
            $period
        );
    }

    $smarty->assign(compact(
        'classes',
        'students',
        'subjects',
        'classId',
        'subjectId',
        'period',
        'diary'
    ));

    function buildDiaryGrid($db, $teacherId, $classId, $subjectId, $period)
    {
        global $smarty;

        // получаем СТРОКУ предмета
        $subject = $db->get("subjects", "subject", [
            "id" => $subjectId
        ]);

        if (!$subject) {
            return null;
        }

        // неделя
        $start = new DateTime($period);
        $start->modify('monday this week');
        $end = (clone $start)->modify('+6 days');

        $days = [];
        for ($dt = clone $start; $dt <= $end; $dt->modify('+1 day')) {
            $days[] = $dt->format('Y-m-d');
        }

        // ученики
        $students = $db->select("class_students", [
            "[>]users" => ["student_id" => "id"]
        ], [
            "users.id",
            "users.name"
        ], [
            "class_students.class_id" => $classId
        ]);

        // оценки — ВНИМАНИЕ: subject = СТРОКА
        $grades = $db->select("grades", "*", [
           // "teacher_id" => $teacherId,
            "class_id"   => $classId,
            "subject"    => $subject,
            "created_at[<>]" => [
                $start->format('Y-m-d 00:00:00'),
                $end->format('Y-m-d 23:59:59')
            ]
        ]);

        // карта: student_id → day → grade
        $map = [];

        foreach ($grades as $g) {
            $day = substr($g['created_at'], 0, 10);
            // перезаписываем — останется последняя
            $map[$g['student_id']][$day] = $g;
        }

        $smarty->assign([
            'days'      => $days,
            'students'  => $students,
            'gradeMap'  => $map,
            'subjectId' => $subjectId,
            'subject'   => $subject
        ]);

        return [
            'days'     => $days,
            'students' => $students,
            'map'      => $map
        ];
    }


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