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

    $errors = [];

    if(empty($_POST['selected_class'])) $errors['selected_class'] = "Класс обязателен";
    if(empty($_POST['selected_student'])) $errors['selected_student'] = "Ученик обязателен";

    if($errors){
        echo json_encode(['success'=>false,'errors'=>$errors]);
        exit;
    }

    $isExists = $db_connect->has("class_students", [
        "student_id" => $_POST['selected_student'],
        //"class_id" => $_POST['selected_class']
    ]);

    if ($isExists) {
        $errors['selected_student'] = "Ученик уже связан с другим классом";
        echo json_encode(['success'=>false,'errors'=>$errors]);
        exit;
    }

    $db_connect->insert("class_students", [
        "student_id" => $_POST['selected_student'],
        "class_id" => $_POST['selected_class']
    ]);

    echo json_encode(["success" => true]);
