<?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/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

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


if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or  !isset($postdata['subject_id']) or !checkIfIssetAndNotEmpty($postdata['subject_id']) 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  !isset($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;

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

function deleteSubject($conn_rjllearning_specific, $institution_id, $subject_id)
{
    //apply_leaves,assignments,homework,lessons,lesson_categories,library_management,question_bank_info,test,timetable
    $res = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM homework WHERE institution_id = ? AND subject_id = ?");
    $res->execute(array($institution_id, $subject_id));
    $result1 = $res->fetchAll();

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

    // Check for existing timetable
    $sql_timetable = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM timetable WHERE institution_id = ? AND subject_id = ?");
    $sql_timetable->execute(array($institution_id, $subject_id));
    $result_timetable = $sql_timetable->fetchAll();
    if (count($result_timetable) >= 1) {
        errorreturn("Access denied. A timetable exists for this subject, so it cannot be deleted.");
    }

    // Check for existing assignments
    $sql_assignments = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM assignments WHERE institution_id = ? AND subject_id = ?");
    $sql_assignments->execute(array($institution_id, $subject_id));
    $result_assignments = $sql_assignments->fetchAll();
    if (count($result_assignments) >= 1) {
        errorreturn("Access denied. An assignment exists for this subject, so it cannot be deleted.");
    }

    // Check for existing apply leaves
    $sql_apply_leaves = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM apply_leaves WHERE institution_id = ? AND subject_id = ?");
    $sql_apply_leaves->execute(array($institution_id, $subject_id));
    $result_apply_leaves = $sql_apply_leaves->fetchAll();
    if (count($result_apply_leaves) >= 1) {
        errorreturn("Access denied. An apply leave exists for this subject, so it cannot be deleted.");
    }

    // Check for existing lessons
    $sql_lessons = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM lessons WHERE institution_id = ? AND subject_id = ?");
    $sql_lessons->execute(array($institution_id, $subject_id));
    $result_lessons = $sql_lessons->fetchAll();
    if (count($result_lessons) >= 1) {
        errorreturn("Access denied. A lesson exists for this subject, so it cannot be deleted.");
    }

    // Check for existing lesson categories
    $sql_lesson_categories = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM lesson_categories WHERE institution_id = ? AND subject_id = ?");
    $sql_lesson_categories->execute(array($institution_id, $subject_id));
    $result_lesson_categories = $sql_lesson_categories->fetchAll();
    if (count($result_lesson_categories) >= 1) {
        errorreturn("Access denied. A lesson category exists for this subject, so it cannot be deleted.");
    }

    // Check for existing library management
    $sql_library_management = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM library_management WHERE institution_id = ? AND subject_id = ?");
    $sql_library_management->execute(array($institution_id, $subject_id));
    $result_library_management = $sql_library_management->fetchAll();
    if (count($result_library_management) >= 1) {
        errorreturn("Access denied. A library management entry exists for this subject, so it cannot be deleted.");
    }


    // reeturns all data from the specific row of the profile
    $sql = "DELETE FROM subject_info WHERE  id=? and institution_id = ? ";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute(array($subject_id, $institution_id));
    $count = $stmt->rowCount();
    if ($count == 1) {
        return "Delete subject Successfully";
    }
}

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

    $subject_id = trim($postdata['subject_id']);
    $institution_id = trim($postdata['institution_id']);

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

    $success['data'] = deleteSubject($conn_rjllearning_specific, $institution_id, $subject_id);
    successreturn($success);
}
