<?php
ini_set('display_errors', 1);

require_once '../../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . '/user_management/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'faculty_api/faculty_function/common_faculty_function.php';

$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['classname']) or !checkIfIssetAndNotEmpty($postdata['classname']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or
    !isset($postdata['jwt_token']) or  !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning,$conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

$classname = ucwords(strtolower(trim($postdata['classname'])));
$function_type = trim($postdata['function_type']);

$check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($check_academic_confirmation != true) {
    errorreturn("Access denied. Academic session not active.");
}

if (!checkOnlyCharcterNumericwithSpace($classname)) { // for english chars + numbers only

    errorreturn('Invalid class name');
}
$sql_codes = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$sql_codes->execute(array($userid, $institution_id, $branch_id));

// Fetch a single row instead of all
$result_faculty = $sql_codes->fetch(PDO::FETCH_ASSOC);

// Check if the faculty exists
if ($result_faculty === false) {
    errorreturn("Faculty Not Found.");
}

// Retrieve the faculty_id from the result
$faculty_id = $result_faculty['id'];

$function_check = checkFacultyModuleGranted($institution_id, $branch_id, $faculty_id, $function_type, null, null, null, $conn_rjllearning_specific, $conn_rjllearning);
var_dump($function_check);
if ($branch_id != 'all') {

    // Prepare and execute the query to check if the branch exists
    $sql_codes = $conn_rjllearning_specific->prepare("SELECT COUNT(*) as total FROM branch WHERE id=? AND institution_id=? AND status=?");
    $sql_codes->execute(array($branch_id, $institution_id, '1'));
    $result_branch = $sql_codes->fetchAll()[0]['total'];

    // Check if the branch exists
    if ($result_branch < 1) {
        errorreturn("Branch Not Found.");
    }

    // Store the branch_id as a single-quoted value
    $imploded_branchids = "'" . $branch_id . "'";
} else {
    // If branch_id is 'all', store it as is
    $imploded_branchids = $branch_id;
}

die();

if ($postdata['function_type'] == "create_class") {

    $res = $conn_rjllearning_specific->prepare("SELECT *  FROM  class_info WHERE institution_id = ? AND branch_id like ? AND classname = ?");
    $res->execute(array($institution_id, '%' . $branch_id . '%', $classname));
    $result = $res->fetchAll();
    if (count($result) >= 1) {
        errorreturn("Class Name already exist");
    }

    try {

        $sql = "INSERT INTO class_info(institution_id,branch_id,classname,status)VALUES(?,?,?,?)";
        $stmt =  $conn_rjllearning_specific->prepare($sql);
        $stmt->execute(array($institution_id, $imploded_branchids, $classname, '1'));
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }
    $id = $conn_rjllearning_specific->lastInsertId();
    successreturn(array('class_id' => $id, 'successmsg' => "Successfully class added."));
} else if ($postdata['function_type'] == "alter_class") {


    if (!isset($postdata['class_id']) or !checkIfIssetAndNotEmpty($postdata['class_id'])) {
        errorreturn('Error in updating the class.');
    } else {
        $id = $postdata['class_id'];
    }

    $res = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM homework WHERE institution_id = ? AND branch_id = ? AND class_id = ?");
    $res->execute(array($institution_id, $branch_id, $id));
    $result1 = $res->fetchAll();

    if (count($result1) >= 1) {
        errorreturn("Access denied. A homework exists for this class, so it cannot be updated.");
    }

    $res = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM announcement WHERE institution_id = ? AND branch_id = ? AND class_id = ?");
    $res->execute(array($institution_id, $branch_id, $id));
    $result1 = $res->fetchAll();

    if (count($result1) >= 1) {
        errorreturn("Access denied. A announcement exists for this class, so it cannot be updated.");
    }


    $res = $conn_rjllearning_specific->prepare("SELECT id,institution_id FROM class_info WHERE id != ? and institution_id=? AND branch_id LIKE ? AND  classname= ?");
    $res->execute(array($id, $institution_id, '%' . $branch_id . '%', $classname));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("The class already exists");
    }

    $sql_users = "UPDATE class_info SET classname=? WHERE id=? and institution_id=? AND branch_id = ?";
    $conn_rjllearning_specific->prepare($sql_users)->execute(array($classname, $id, $institution_id, $branch_id));
    successreturn("Updated class Successfully");
}
