<?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_id']) or !checkIfIssetAndNotEmpty($postdata['expense_id']) or
  !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_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;

$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 getSpecificVendor($conn_rjllearning_specific, $institution_id, $vehicle_expense_id) {
    // Query to fetch expense details
    $sql = $conn_rjllearning_specific->prepare("SELECT * FROM unmarked_transaction WHERE id = ? AND institution_id = ?");
    $sql->execute([$vehicle_expense_id, $institution_id]);
    $rows = $sql->fetchAll(PDO::FETCH_ASSOC);
   
    if (count($rows) == 1) {
         if ($rows[0]['attachment'] != null and !is_array($rows[0]['attachment'])) {
            $data_attachment = json_decode($rows[0]['attachment'], true);
            $filePath = $data_attachment['filepath'];
            $originalName = $data_attachment['original_name'];
            $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
            $final_array_attachment   = array("filepath" => $aws_attachment, "original_name" => $originalName);
        } else {
            $final_array_attachment =  null;
        }
        $category_id = $rows[0]['category_id']; // Vendor ID to use for fetching details

        // Validate the vendor ID
        if (empty($category_id)) {
            errorreturn("Category ID is required.");
        }

        // Query to fetch name and contact_number from vendor table
        $fetch_vendor_sql = "SELECT id,group_name FROM unmarked_transaction_type_group WHERE id = ?";

        // Prepare and execute the query
        $stmt = $conn_rjllearning_specific->prepare($fetch_vendor_sql);
        $stmt->execute([$category_id]);

        // Fetch the result
        $vendor_info = $stmt->fetch(PDO::FETCH_ASSOC);

        // Check if vendor info was found
        if ($vendor_info) {
            // Successfully fetched vendor info
            $group_id = $vendor_info['id'];
            $group_name= $vendor_info['group_name'];
        } else {
            $group_id = null;
            $group_name = null;
        }
        // Decode expense_id if it's JSON encoded
        
        // Get branch info
        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows[0]['branch_id']);

        // Prepare the result
        $array_return = [
            'expense_id' => $rows[0]['id'],
            'institution_id' => $rows[0]['institution_id'],
            'branch_id' => $branch_info,
            'category_id' => $group_name,
            // 'expense_id' => $rows['expense_id'],
            'amount' => $rows[0]['amount'],
            'vendor_name' => $rows[0]['vendor_name'],
            'date' => $rows[0]['date'],
            'transaction_reference_id' => $rows[0]['transaction_reference_id'],
            'payment_bool' => $rows[0]['payment_bool'],
            'payment_method' => $rows[0]['payment_method'],
            'paid_on'=>$rows[0]['paid_on'],
            'attachment'=>$final_array_attachment,
            'remarks' => $rows[0]['remarks'],
            'initiated_by' => $rows[0]['initiated_by'],
            'last_edit' => $rows[0]['last_edit'],
            'last_edit_at' => $rows[0]['last_edit_at'],
            'recorded_in_finware' => $rows[0]['recorded_in_finware'],
             'transaction_type_group' => $rows[0]['transaction_type_group'],
            'approved_by' => $rows[0]['approved_by'],
            'created_by' => $rows[0]['created_by'],
            'time_created' => $rows[0]['time_created'],
            'date_created' => $rows[0]['date_created']
        ];

        // Return or use $array_return as needed
        return $array_return;
    } else {
        errorreturn("Invalid expense information.");
    }
}


if($postdata['function_type']  == "fetch_specific_unmarked_expense_transaction") {  
    
    $vehicle_expense_id = trim($postdata['expense_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.");
    }
    $success['data'] = getSpecificVendor($conn_rjllearning_specific,$institution_id,$vehicle_expense_id);
    successreturn($success);
      
}

