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

    require_once($_SERVER["DOCUMENT_ROOT"] . '/engine/data/config.php');
    require_once($_SERVER["DOCUMENT_ROOT"] . "/engine/data/dbconfig.php");

    global $db_connect;

    session_start();

    $response = ['success' => false];

    try {
        $grade_id    = isset($_POST['grade_id']) ? intval($_POST['grade_id']) : null;
        $student_id  = isset($_POST['student_id']) ? intval($_POST['student_id']) : 0;
        $teacher_id  = !empty($_POST['teacher_id']) ? intval($_POST['teacher_id']) : $_SESSION["user_id"]; // нужно передавать из JS
        $subject     = isset($_POST['subject']) ? $_POST['subject'] : '';
        $grade       = isset($_POST['grade']) ? $_POST['grade'] : '';
        $comment     = isset($_POST['comment']) ? $_POST['comment'] : null;

        if (!$student_id || !$teacher_id || !$subject) {
            throw new Exception('Некорректные данные');
        }

        $teacherCanGrade = (bool)$db_connect->get("teacher_classes", [
            "[>]class_students" => ["class_id" => "class_id"]
        ], "teacher_classes.teacher_id", [
            "teacher_classes.teacher_id" => $teacher_id,
            "class_students.student_id" => $student_id
        ]);

        $subject = $db_connect->get("subjects", "subject", [
            "id" => $subject
        ]);

        $currentRoleId = $db_connect->get("users_roles", "role_id", ["user_id" => $_SESSION["user_id"]]);
        $currentRole = $db_connect->get("roles", "name", ["id" => $currentRoleId]);

        if ($currentRole == "Admin") {
            $teacherCanGrade = true;
            $teacher_id = $_SESSION["user_id"];
        }

        if (!$teacherCanGrade) {
            throw new Exception('У вас нету доступа к изменениям оценки');
        }

        if ($grade_id) {
            // Обновляем существующую оценку
            $db_connect->update('grades', [
                'grade' => $grade,
                'comment' => $comment
            ], [
                'id' => $grade_id
            ]);
        } else {
            // Создаём новую оценку
            $grade_id = $db_connect->insert('grades', [
                'student_id' => $student_id,
                'teacher_id' => $teacher_id,
                'subject'    => $subject,
                'grade'      => $grade,
                'comment'    => $comment,
                'created_at' => $_POST["day"],
                'class_id'   => $_POST["class_id"]
            ]);
        }

        $response['success'] = true;
        $response['grade_id'] = $grade_id;

    } catch (Exception $e) {
        $response['success'] = false;
        $response['message'] = $e->getMessage();
    }

    echo json_encode($response);