<?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';
require_once $base_path_to_learning . 'functions/common_functions.php';
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

if ( !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;

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

if (!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or 
    !isset($postdata['section_name']) or !checkIfIssetAndNotEmpty($postdata['section_name'])) {
    errorreturn("All * fields are required.");
    }
    
    $institution_id = trim($postdata['institution_id']);
    $section_name = trim($postdata['section_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);

if ($postdata['function_type'] == "create_section") {
    
    // $branch_id = $postdata['branch_id'];
     $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific,$institution_id);
    if($check_academic_confirmation != true){
         errorreturn("Access denied. Academic session not active.");
    }

    if ($branch_id != 'all') {

        if (!is_array($branch_id) or count($branch_id) <= 0) {
            echo 'w';
            errorreturn("Select atleast one branch.");
        }

        $imploded_branch_ids = "('" . implode("','", $branch_id) . "')";
        $count_ids = count($branch_id);

        $sql_codes = $conn_rjllearning_specific->prepare("Select count(*) as total from  branch WHERE id IN $imploded_branch_ids and status =? ");
        $sql_codes->execute(array('1'));
        $result_branch = $sql_codes->fetchAll()[0]['total'];
        if ($result_branch != $count_ids) {
            errorreturn("Branch Not Found.");
        }
        $imploded_branchids = "'" . implode("','", $branch_id) . "'";
    } else {

        $imploded_branchids = $branch_id;
    }
    
    // $confirmed_role_user = validatePrimaryAccess($conn_rjllearning_specific, $institution_id, $branch_id, $role, $userid);

    // if ($confirmed_role_user != "superadmin" && $confirmed_role_user != "admin"  && $confirmed_role_user != "principal") {
    //     errorreturn("Access denied.");
    // }

    $sql_table = $conn_rjllearning_specific->prepare("SELECT * FROM section_info WHERE institution_id = ? AND branch_id IN $imploded_branchids AND section_name= ?");
    $sql_table->execute(array($institution_id,$section_name));
    $result1 = $sql_table->fetchAll();

    if (count($result1) >= 1) {

        errorreturn("This class section already exists");
    }

    try {

        $sql = "INSERT INTO section_info(institution_id,branch_id,section_name,added_by,time_created,status)VALUES(?,?,?,?,?,?)";
        $stmt =  $conn_rjllearning_specific->prepare($sql);

        $stmt->execute(array($institution_id, $imploded_branchids, $section_name, $username, time(), '1'));
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }

    $id = $conn_rjllearning_specific->lastInsertId();
    successreturn(array('id' => $id, 'successmsg' => "Successfully section added."));
} else if ($postdata['function_type'] == "alter_section") {
    if (!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id'])  or !isset($postdata['section_name']) or !checkIfIssetAndNotEmpty($postdata['section_name'])) {
    errorreturn("All * fields are required.");
    }
    $institution_id = trim($postdata['institution_id']);
    $section_name = trim($postdata['section_name']);
    $branch_id = $postdata['branch_id'];
    
     $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific,$institution_id);
    if($check_academic_confirmation != true){
         errorreturn("Access denied. Academic session not active.");
    }
    if (!isset($postdata['section_id']) or !checkIfIssetAndNotEmpty($postdata['section_id'])) {
        errorreturn('Error in updating the academic session.');
    } else {
        $id = $postdata['section_id'];
    }

    if ($branch_id != 'all') {

        if (!is_array($branch_id) or count($branch_id) <= 0) {
            errorreturn("Select atleast one branch.");
        }

        $imploded_branch_ids = "('" . implode("','", $branch_id) . "')";
        $count_ids = count($branch_id);

        $sql_codes = $conn_rjllearning_specific->prepare("Select count(*) as total from  branch WHERE id IN $imploded_branch_ids and status =? ");
        $sql_codes->execute(array('1'));
        $result_branch = $sql_codes->fetchAll()[0]['total'];
        if ($result_branch != $count_ids) {
            errorreturn("Branch Not Found.");
        }
        $imploded_branchids = "'" . implode("','", $branch_id) . "'";
    } else {

        $imploded_branchids = $branch_id;
    }
    $res = $conn_rjllearning_specific->prepare("SELECT id,institution_id FROM section_info WHERE id != ? and institution_id=? AND branch_id  IN $imploded_branchids AND section_name =?");
    $res->execute(array($id, $institution_id,$section_name));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("The Class Section already exists. ");
    }

    $sql_users = "UPDATE section_info SET section_name =? WHERE id=? and institution_id=? AND branch_id = ?";
    $conn_rjllearning_specific->prepare($sql_users)->execute(array($section_name, $id, $institution_id,$branch_id));
    successreturn("Updated section Successfully");
} else if ($postdata['function_type'] == "section_status" ) {
  
 

  if (!isset($postdata['section_id']) or !checkIfIssetAndNotEmpty($postdata['section_id']) or !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) ) {
        errorreturn('Error in updating the academic session.');
    } else {
        $id = $postdata['section_id'];
        $institution_id = trim($postdata['institution_id']);
    }

     $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific,$institution_id);
    if($check_academic_confirmation != true){
         errorreturn("Access denied. Academic session not active.");
    }
    $res = $conn_rjllearning_specific->prepare("SELECT status FROM section_info WHERE id = ? and institution_id=? AND branch_id LIKE ?");
    $res->execute(array($id, $institution_id,'%' . $branch_id . '%'));
    $result1 = $res->fetchAll();

    if (count($result1) == 1) {
        $existing_status = $result1[0]['status'];

        if ($existing_status == '1') {
            $status = '0';
            $sql = "UPDATE section_info SET status=?  WHERE id = ? and institution_id=? AND branch_id = ?";
            $conn_rjllearning_specific->prepare($sql)->execute(array($status, $id, $institution_id,$branch_id));
        } else if ($existing_status == '0') {
            $status = '1';
            $sql = "UPDATE section_info SET status=?  WHERE id = ? and institution_id=? AND branch_id = ?";
            $conn_rjllearning_specific->prepare($sql)->execute(array($status, $id, $institution_id,$branch_id));
        }
    }
    successreturn("Section Status Updated Successfully");
}
