<?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';
//aws image store
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";

require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$postdata = json_decode(file_get_contents("php://input"), true);
//print_r($postdata);
checkIfNoPhpContentsReceive();


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


function getSpecificVendor($conn_rjllearning_specific, $institution_id, $expense_group_id) {
    // Query to fetch expense details
    $sql = $conn_rjllearning_specific->prepare("SELECT * FROM unmarked_transaction_type_group WHERE id = ? AND institution_id = ?");
    $sql->execute([$expense_group_id, $institution_id]);
    $row = $sql->fetchAll(PDO::FETCH_ASSOC);

    if (count($row) == 1) {
        $expense_group = $row[0]; // Fetch the first element in the row

        // Get necessary information from the result
        // $expense_group_id = $expense_group['id'];
        // $branch_id = $expense_group['branch_id'];
        
        // // Fetch branch info
        // $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_id);
        
        // // Initialize parent group name
        // $parent_group_name = null;

        // // Check if parent_group is set
        // if (!empty($expense_group['parent_group'])) {
        //     $parent_group_id = $expense_group['parent_group'];
            
        //     // Query to fetch parent group name
        //     $fetch_parent_group_sql = "SELECT name FROM expense_group WHERE id = ? AND institution_id = ?";
        //     $stmt = $conn_rjllearning_specific->prepare($fetch_parent_group_sql);
        //     $stmt->execute([$parent_group_id, $expense_group['institution_id']]);
        //     $parent_group_info = $stmt->fetch(PDO::FETCH_ASSOC);
            
        //     // Assign parent group name if found
        //     if ($parent_group_info) {
        //         $parent_group_name = $parent_group_info['name'];
        //     }
        // }

        // Prepare the result
        $array_return = [
            'institution_id' => $expense_group['institution_id'],
            // 'branch_id' => $branch_info,
            'group_name' => $expense_group['group_name'],
             'main_ledgerhead' => $expense_group['main_ledgerhead'],
              'parent_lvl1' => $expense_group['parent_lvl1'],
               'parent_lvl2' => $expense_group['parent_lvl2'],
                'parent_lvl3' => $expense_group['parent_lvl3'],
                 'parent_lvl4' => $expense_group['parent_lvl4'],
                 'parent_lvl5' => $expense_group['parent_lvl5'],
            'created_by' => $expense_group['created_by'],
            'time_created' => $expense_group['time_created'],
            'date_created' => $expense_group['date_created'],
            // 'parent_group_name' => $parent_group_name
        ];

        // Return the result
        return $array_return;
    } else {
        errorreturn("Invalid expense information.");
    }
}

if($postdata['function_type']  == "fetch_unmarked_specific_expense_group") {  
    
    $expense_group_id = trim($postdata['expense_group_id']);

    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific,$institution_id);
    if($check_academic_confirmation != true){
         errorreturn("Access denied. Academic session not active.");
    }
    $success['data'] = getSpecificVendor($conn_rjllearning_specific,$institution_id,$expense_group_id);
    successreturn($success);
      
}

