<?php

ini_set('display_errors', 1);
// error_reporting(0);

//require_once '../../resources/base_path_include.php';
require_once '../../../resources/base_path_include.php';
// should we not call header and ch
require_once $base_path_to_resources . "includes/config.php"; // use require for mandatory files
//require($base_path_to_resources."/lib/function.php");
require_once $base_path_to_resources . 'lib/function.php';

require_once  $base_path_to_resources . 'includes/config.php';
require_once  $base_path_to_resources . 'lib/function.php';
require_once $base_path_to_resources . "lib/currency_functions.php";

//valdation file
require_once $base_path_to_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_resources . 'lib/validate_function.php';
require_once $base_path . 'user_management/authenticate.php';

//valdation file
require_once $base_path . 'modules/accounting/groups_ledgers/functions/ledger_functions.php';
require_once $base_path . 'modules/accounting/book_management/basic_book_info_function.php';
require_once $base_path . 'modules/accounting/stock_management/inventory_regions/region_functions.php';
require_once $base_path . 'modules/accounting/transaction_management/functions/get_transaction_uniqueid.php';

//user upload
require_once $base_path_to_resources . 'lib/bucket_functions/bucket_functions.php';

//creating dynamic db
require_once $base_path_to_resources . 'includes/specific_db_config.php';

//aws image store

require_once $base_path . "vendor/autoload.php";

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

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

if (
  !isset($postdata['transaction_id']) or !checkIfIssetAndNotEmpty($postdata['transaction_id']) or !isset($postdata['company_id']) or !checkIfIssetAndNotEmpty($postdata['company_id']) or  !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
  !isset($postdata['book_id']) or !checkIfIssetAndNotEmpty($postdata['book_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']);
//authenticate jwt token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is decoded in data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
//print_r($workspace_id);die();

$role = $jwt_validate->data->role;
$username = $jwt_validate->data->username;


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


  $company_id = trim($postdata['company_id']);
  $branch_id = trim($postdata['branch_id']);
  $book_id = trim($postdata['book_id']);
  $transaction_id = trim($postdata['transaction_id']);

  $ledgerrecord_rows = [];
  $stocktransaction_rows = [];
  $stockclassification_rows = [];

  $function_code = 'display_transactions';
  $confirmed_role_user = validatePrimaryAccess($conn, $workspace_id, $role, $userid, ['superadmin', 'admin', null]);
  if (!$confirmed_role_user) {
    errorreturn('Access denied.');
  } else {
    $specific_db_conn = dynamicDbConnection($confirmed_role_user);
    if ($role == null) {
      checkCompanyBranchFunctionAccess($specific_db_conn, $role, $userid, $workspace_id, $company_id, $branch_id, $book_id,  $function_code);
    }
  }
  $export_type = (isset($postdata['export_type']) and !empty($postdata['export_type'])) ? trim($postdata['export_type']) : null;

  $sql = "Select * from  act_transactiondata where id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =?";
  $stmt =  $specific_db_conn->prepare($sql);
  $stmt->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
  $result_transactiondata = $stmt->fetchAll();


  // info rows_array
  // $transactiondata = null;
  $transactiondata = array();
  $dispatch = array();
  if (count($result_transactiondata) == 1) {
    $filesattached = $result_transactiondata[0]['filesattached'];

    if ($filesattached != null) {
      $sql_file = "Select original_upload_name from user_upload where category_unique_id = ? and workspace_id= ?";
      $stmt_file = $specific_db_conn->prepare($sql_file);
      $stmt_file->execute(array($transaction_id, $workspace_id));
      $fetch_image = $stmt_file->fetchAll();
      if (count($fetch_image) == 1) {
        $original_upload_name = $fetch_image[0]['original_upload_name'];
        $presignedUrl = displayFileFromS3($GLOBALS['s3_finware_bucket'], $GLOBALS['finware_bucketName'], $filesattached);
        $fileName = array('original_upload_name' => $original_upload_name, 'path' => $presignedUrl);
      }
    } else {
      $fileName = null;
    }


    //if dispatch info exists
    $sql = "Select * from  act_dispatch_info where transaction_id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =?";
    $stmt =  $specific_db_conn->prepare($sql);
    $stmt->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
    $result_dispatch = $stmt->fetchAll();
    if (count($result_dispatch) == 1) {
      //   print_r($result_dispatch);
      $doc_no = $result_dispatch[0]['doc_no'];
      $delivery_note = $result_dispatch[0]['delivery_note'];
      $destination = $result_dispatch[0]['destination'];
      $carrier_name = $result_dispatch[0]['carrier_name'];
      $bill_of_lading = $result_dispatch[0]['bill_of_lading'];
      $dispatch_date = $result_dispatch[0]['dispatch_date'];
      $motor = $result_dispatch[0]['motor'];

      $dispatch = array('doc_no' => $doc_no, 'delivery_note' => $delivery_note, 'destination' => $destination, 'carrier_name' => $carrier_name, 'bill_of_lading' => $bill_of_lading, 'dispatch_date' => $dispatch_date, 'motor' =>
      $motor);
    }


    $transactiontype = $result_transactiondata[0]['transactiontype'];

    $transactionrows = [];
    $sql = "Select * from  act_transactionrecord where transaction_id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =?";
    $stmt =  $specific_db_conn->prepare($sql);
    $stmt->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
    $transactionrecord = $stmt->fetchAll();

    foreach ($transactionrecord as $result_transactionrecord) {
      $ledgerid = $result_transactionrecord['ledgerid'];
      $reference_id = $result_transactionrecord['reference_id'];
      $param_1 = $result_transactionrecord['param_1'];
      $additionaldata = array();
      $additionaldata = ['ledger_name', 'ledger_current_bal'];
      $ledgername = GetBasicLedgerDetail($specific_db_conn, $ledgerid, $workspace_id, $company_id, $branch_id, $book_id, $additionaldata);

      if ($ledgerid != 'null') {

        $bankinstrumentrows = [];
        $sql_bank = "Select * from  act_bankinstrument where id = ? and transaction_id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =?";
        $stmt_bank =  $specific_db_conn->prepare($sql_bank);
        $stmt_bank->execute(array($reference_id, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
        $bank_rows = $stmt_bank->fetchAll();

        if (count($bank_rows) == 1) {
          $bankinstrumentrows[] = array(
            'instrument_number' => $bank_rows[0]['instrument_number'], 'instrument_type' => $bank_rows[0]['instrument_type'],
            'date_instrument' => $bank_rows[0]['date_instrument'], 'date_transaction' => $bank_rows[0]['date_transaction']
          );
        }
      }

      $denominationsrows = [];
      if ($reference_id != 'null') {
        $sql_denomination = "Select * from  act_denominations where id =? and transaction_id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =?";
        $stmt_denomination =  $specific_db_conn->prepare($sql_denomination);
        $stmt_denomination->execute(array($reference_id, $transaction_id, $workspace_id, $company_id, $branch_id, $book_id));
        $bank__denomination = $stmt_denomination->fetchAll();

        foreach ($bank__denomination as $denomination_rows) {
          $inputString =  $denomination_rows['denominations'];
          $elements = explode(',', $inputString);
          $outputArray = [];

          foreach ($elements as $element) {
            // Remove the leading '#' character
            $element = ltrim($element, '#');

            // Split each element by colon to get the key and value
            list($key, $value) = explode(':', $element);

            // Convert the key and value to integers (optional, depending on your needs)
            $key = (int)$key;
            $value = (int)$value;

            // Add the key-value pair to the output array
            $outputArray[$key] = $value;
          }
          $denominationsrows[] = $outputArray;
        }
      }

      $transactionrows[] = array(
        'ledgerid' => $result_transactionrecord['ledgerid'], 'ledger_name' => $ledgername[0]['ledger_name'],
        'ledger_current_bal' => $ledgername[1]['ledger_current_bal'], 'parent_ledgerhead' => $result_transactionrecord['parent_ledgerhead'], 'amount' => $result_transactionrecord['amount'], 'balancetype' => $result_transactionrecord['balancetype'],
        'param_1' => $result_transactionrecord['param_1'],
        'denominations' => $denominationsrows, 'instrument_details' => $bankinstrumentrows
      );
    }

    if ($result_transactiondata[0]['billing_address'] != null) {

      $billing_address =   $result_transactiondata[0]['billing_address'];
      $sql = "SELECT * FROM act_ledger_addresses WHERE id=?";
      $stmt = $specific_db_conn->prepare($sql);
      $stmt->execute(array($billing_address));
      $result = $stmt->fetchAll();
      if (count($result) == 1) {

        $address_name = $result[0]['name'];

        $address_ln_1 = (isset($result[0]['address_ln_1']) and !empty($result[0]['address_ln_1'])) ? $result[0]['address_ln_1'] : null;
        $address_ln_2 = (isset($result[0]['address_ln_2']) and !empty($result[0]['address_ln_2'])) ? $result[0]['address_ln_2'] : null;
        $ledger_gst = (isset($result[0]['ledger_gst']) and !empty($result[0]['ledger_gst'])) ? $result[0]['ledger_gst'] : null;
        $country_id = $result[0]['country_id'];
        $state_id = $result[0]['state_id'];
        $mobile = $result[0]['mobile'];
        $email = $result[0]['email'];

        $sql = "SELECT * FROM country_info WHERE id=?";
        $stmt = $conn->prepare($sql);
        $stmt->execute(array($country_id));
        $result_country = $stmt->fetchAll();
        if (count($result_country) == 1) {

          $id = $result_country[0]['id'];
          $name = $result_country[0]['name'];
          $countryinfo = array('id' => $id, 'label' => $name);
        }

        $sql = "SELECT * FROM state_info WHERE id=? and country_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->execute(array($state_id, $country_id));
        $result_state = $stmt->fetchAll();
        if (count($result_state) == 1) {
          $id = $result_state[0]['id'];
          $state_name = $result_state[0]['state'];
          $stateinfo = array('id' => $id, 'label' => $state_name);
        }


        $billing_address = array(
          'id' => $billing_address, 'label' => $address_name,  'address_ln_1' => $address_ln_1, 'address_ln_2' => $address_ln_2, 'ledger_gst' => $ledger_gst,
          'country' => $countryinfo, 'state' => $stateinfo, 'mobile' => $mobile, 'email' => $email
        );
      }
    } else {
      $billing_address = null;
    }

    if ($result_transactiondata[0]['shipping_address'] != null) {
      $shipping_address = $result_transactiondata[0]['shipping_address'];
      $sql = "SELECT * FROM act_ledger_addresses WHERE id=?";
      $stmt = $specific_db_conn->prepare($sql);
      $stmt->execute(array($shipping_address));
      $result = $stmt->fetchAll();
      if (count($result) == 1) {

        $address_name = $result[0]['name'];
        $address_ln_1 = (isset($result[0]['address_ln_1']) and !empty($result[0]['address_ln_1'])) ? $result[0]['address_ln_1'] : null;
        $address_ln_2 = (isset($result[0]['address_ln_2']) and !empty($result[0]['address_ln_2'])) ? $result[0]['address_ln_2'] : null;
        $ledger_gst = (isset($result[0]['ledger_gst']) and !empty($result[0]['ledger_gst'])) ? $result[0]['ledger_gst'] : null;
        $country_id = $result[0]['country_id'];
        $state_id = $result[0]['state_id'];
        $mobile = $result[0]['mobile'];
        $email = $result[0]['email'];

        $sql = "SELECT * FROM country_info WHERE id=?";
        $stmt = $conn->prepare($sql);
        $stmt->execute(array($country_id));
        $result_country = $stmt->fetchAll();
        if (count($result_country) == 1) {

          $id = $result_country[0]['id'];
          $name = $result_country[0]['name'];
          $countryinfo = array('id' => $id, 'label' => $name);
        }

        $sql = "SELECT * FROM state_info WHERE id=? and country_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->execute(array($state_id, $country_id));
        $result_state = $stmt->fetchAll();
        if (count($result_state) == 1) {
          $id = $result_state[0]['id'];
          $state_name = $result_state[0]['state'];
          $stateinfo = array('id' => $id, 'label' => $state_name);
        }

        $shipping_address = array(
          'id' => $shipping_address, 'label' => $address_name, 'address_ln_1' => $address_ln_1, 'address_ln_2' => $address_ln_2, 'ledger_gst' => $ledger_gst,
          'country' => $countryinfo, 'state' => $stateinfo, 'mobile' => $mobile, 'email' => $email
        );
      }
    } else {

      $shipping_address = null;
    }

    // getting transaction_settings
    // fetching book settings to identify if numbering is automatic or manual or automatic_override_manual
    $sql = "Select financial_year_startdate from act_books where workspace_id = ? and company_id = ? and branch_id = ? and id = ?";
    $fetch_book = $specific_db_conn->prepare($sql);
    $fetch_book->execute(array($workspace_id, $company_id, $branch_id, $book_id));
    $book_info = $fetch_book->fetchAll();
    if (count($book_info) != 1) {
      errorreturn('Error in fetching book details.');
    }
    $financial_year_startdate = $book_info[0]['financial_year_startdate'];
    $sql = "Select transaction_numbering_system, prefix_financial_year, additional_transaction_prefix from act_book_settings where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ?";
    $fetch = $specific_db_conn->prepare($sql);
    $fetch->execute(array($workspace_id, $company_id, $branch_id, $book_id));
    $result_settings = $fetch->fetchAll();
    if (count($result_settings) == 1) {
      $transaction_numbering_system = json_decode($result_settings[0]['transaction_numbering_system'], true);
      $prefix_financial_year_bool = $result_settings[0]['prefix_financial_year'];
      $additional_transaction_prefix = $result_settings[0]['additional_transaction_prefix'];
    } else {
      require_once '../../global_settings/transaction_settings/function_renumber_automatic_transaction.php';
      $transaction_numbering_system = array("manual" => [], "automatic" => $transactiontypes_array_settings);
      $prefix_financial_year_bool = 0;
      $additional_transaction_prefix = '';
    }

    $unique_id =  getTransactionUniqueId($additional_transaction_prefix, $transaction_numbering_system, $result_transactiondata[0]['unique_id'], $result_transactiondata[0]['transactiontype'], $prefix_financial_year_bool, $result_transactiondata[0]['date'], $financial_year_startdate);

    $transactiondata = array(
      'transaction_id' => $result_transactiondata[0]['id'], 'transactiontype' => $result_transactiondata[0]['transactiontype'],
      'reference_number' => $result_transactiondata[0]['reference_number'], 'date' => $result_transactiondata[0]['date'],
      'entry_by' => $result_transactiondata[0]['entry_by'], 'filesattached' => $fileName, 'narration' => $result_transactiondata[0]['narration'], 'e_way_bill' => $result_transactiondata[0]['e_way_bill'],
      'last_modified_by' => $result_transactiondata[0]['last_modified_by'], 'billing_address' => $billing_address,  'shipping_address' => $shipping_address, 'dispatch_info' => $dispatch, 'transaction_unique_id' => $unique_id

    );

    $sql_stock_classification = "Select id,ledgerid,percentage,total_amount,adjusted_type,is_add from inventory_stock_classification where transaction_id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =? and inventory_transaction_stockid= ? ";
    $stmt_stock_classification =  $specific_db_conn->prepare($sql_stock_classification);
    $stmt_stock_classification->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id, '_'));
    $stockclassification_result = $stmt_stock_classification->fetchAll();


    foreach ($stockclassification_result as $stockclassification) {

      $ledgerid =   $stockclassification['ledgerid'];
      $sql_ledgerdetails = "Select  ledger_name,ledger_main_ledgerhead from  act_ledgerdetails where id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =?  ";
      $stmt_ledgerdetails =  $specific_db_conn->prepare($sql_ledgerdetails);
      $stmt_ledgerdetails->execute(array($ledgerid, $workspace_id, $company_id, $branch_id, $book_id));
      $ledgerdetails_result = $stmt_ledgerdetails->fetchAll();
      foreach ($ledgerdetails_result as $ledger_rows) {
        $ledger_name = $ledger_rows['ledger_name'];
        $ledger_main_ledgerhead = $ledger_rows['ledger_main_ledgerhead'];
        $ledgerrecord_rows[] = array(
          'ledgerid' => $stockclassification['ledgerid'], 'ledger_name' => $ledger_name, 'ledger_main_ledgerhead' => $ledger_main_ledgerhead, 'percentage' => $stockclassification['percentage'],
          'total_amount' => $stockclassification['total_amount'], 'adjusted_type' => $stockclassification['adjusted_type'], 'is_add' => $stockclassification['is_add']
        );
      }
    }

    $stock_record = array();
    $sql_stock = "Select id,type,qty,per_price,total_amount,unit_id,stock_id,description,index_batch from  inventory_stocktransaction where transaction_id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =? and type=?";
    $stmt_stock =  $specific_db_conn->prepare($sql_stock);
    $stmt_stock->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id, $transactiontype));
    $result_stocktransactionrows = $stmt_stock->fetchAll();

    if (count($result_stocktransactionrows) >= 1) {
      foreach ($result_stocktransactionrows as $stocktransactionrows) {

        $stockid = $stocktransactionrows['stock_id'];
        $unit_id = $stocktransactionrows['unit_id'];
        $index_batch = $stocktransactionrows['index_batch'];

        if ($unit_id != null) {
          $sql_unit = "Select id,symbol from unit_creation where id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =?";
          $stmt_unit =  $specific_db_conn->prepare($sql_unit);
          $stmt_unit->execute(array($unit_id, $workspace_id, $company_id, $branch_id, $book_id));
          $result_unit = $stmt_unit->fetchAll();
          if (count($result_unit) == 1) {

            $unit_name = $result_unit[0]['symbol'];
          }
        } else {
          $unit_name = null;
        }

        $sql_stock_classification = "Select id,ledgerid,percentage,total_amount,adjusted_type,is_add, index_stock_classification from inventory_stock_classification where transaction_id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =? and inventory_transaction_stockid= ? and index_stock_classification = ? order by index_stock_classification asc";
        $stmt_stock_classification =  $specific_db_conn->prepare($sql_stock_classification);
        $stmt_stock_classification->execute(array($transaction_id, $workspace_id, $company_id, $branch_id, $book_id, $stockid, $index_batch));
        $stockclassification_result = $stmt_stock_classification->fetchAll();
        //   print_r($stockclassification_result);
        $stockclassification_rows = [];
        foreach ($stockclassification_result as $stockclassification) {
          $ledgerid = $stockclassification['ledgerid'];
          $sql_ledgerdetails = "Select  ledger_name,ledger_main_ledgerhead from  act_ledgerdetails where id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id = ?";
          $stmt_ledgerdetails =  $specific_db_conn->prepare($sql_ledgerdetails);
          $stmt_ledgerdetails->execute(array($ledgerid, $workspace_id, $company_id, $branch_id, $book_id));
          $ledgerdetails_result = $stmt_ledgerdetails->fetchAll();
          foreach ($ledgerdetails_result as $ledgerrows) {
            $ledger_name = $ledgerrows['ledger_name'];
            $ledger_main_ledgerhead = $ledgerrows['ledger_main_ledgerhead'];
            $stockclassification_rows[] = array(
              'ledgerid' => $stockclassification['ledgerid'], 'ledger_name' => $ledger_name,
              'ledger_main_ledgerhead' => $ledger_main_ledgerhead, 'percentage' => $stockclassification['percentage'],
              'total_amount' => $stockclassification['total_amount'], 'adjusted_type' => $stockclassification['adjusted_type'], 'is_add' => $stockclassification['is_add'], "index_stock_classification" => $stockclassification['index_stock_classification']
            );

            //inventory transaction
          }
        }

        $sql_batch_details = "Select * from inventory_batch_details where  workspace_id = ? and company_id =? and branch_id =? and book_id  =? and stock_id= ? and transaction_id = ? and index_batch = ? order by index_batch asc";
        $stmt_batch_details =  $specific_db_conn->prepare($sql_batch_details);
        $stmt_batch_details->execute(array($workspace_id, $company_id, $branch_id, $book_id, $stockid, $transaction_id, $index_batch));
        $result_batchdetails = $stmt_batch_details->fetchAll();
        //   print_r($stockclassification_result);
        $batch_details = [];
        foreach ($result_batchdetails as $batch_rows) {
          $batch_details[] = array(
            'id' => $batch_rows['id'], 'stock_barcode_uin' => $batch_rows['stock_barcode_uin'],
            'date' => $batch_rows['date'], 'type' => $batch_rows['type'],
            'rate' => $batch_rows['rate'], 'qty' => abs($batch_rows['qty']), 'expiry' => $batch_rows['expiry'], 'mfg_date' => $batch_rows['mfg_date'], 'amount' => $batch_rows['amount'], 'remarks' => $batch_rows['remarks'], "index_batch" => $batch_rows['index_batch']
          );
        }


        $sql_stockdeatils = "Select id,stock_name,boolean_inventory,current_qty,region_id,hsn_code,unit_name from  inventory_stockdetails where id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =?";
        $stmt_stockdetails =  $specific_db_conn->prepare($sql_stockdeatils);
        $stmt_stockdetails->execute(array($stockid, $workspace_id, $company_id, $branch_id, $book_id));
        $result_stockdetails = $stmt_stockdetails->fetchAll();

        if (count($result_stockdetails) == 1) {
          $stock_id = $result_stockdetails[0]['id'];
          $stock_name = $result_stockdetails[0]['stock_name'];
          $boolean_inventory = $result_stockdetails[0]['boolean_inventory'];
          $current_qty = $result_stockdetails[0]['current_qty'];
          $hsn_code = $result_stockdetails[0]['hsn_code'];
          $region_id = $result_stockdetails[0]['region_id'];
          $unit_name = $result_stockdetails[0]['unit_name'];
          $stockname = " (" . getRegionName($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $region_id) . ")";
          // $rate = 0.00;
          $qty = $stocktransactionrows['qty'];
          $total_amount = $stocktransactionrows['total_amount'];

          $rate = $total_amount / $qty;
          $stocktransaction_rows[] = array(
            'id' => $stockid, 'stock_name' => $stock_name . $stockname, 'boolean_inventory' => $boolean_inventory, 'current_qty' => $current_qty,
            'per_price' => $stocktransactionrows['per_price'], 'qty' => $stocktransactionrows['qty'], 'total_amount' => $stocktransactionrows['total_amount'], 'rate' => $rate,
            'unit_id' => $stocktransactionrows['unit_id'], 'unit_name' => $unit_name, 'description' => $stocktransactionrows['description'], 'hsn_code' => $hsn_code,
            'ledger_entries' => $stockclassification_rows, 'batchdetails' => $batch_details
          );
        }
        //$stock_record[] = array('stocktransaction' => $stocktransaction_rows);

      }
    }

    if ($export_type == null) {

      successreturn(array('transaction_info' => array('transactiondata' => $transactiondata, 'transactionrecord' => $transactionrows, 'stock_items' => $stocktransaction_rows, 'stock_ledger_entries' => $ledgerrecord_rows)));
    } else {

      if ($transactiondata['transactiontype'] == 'sales') {
        if (isset($export_type)) { // true // value check should either be spreadsheet pdf 
          if ($export_type == 'pdf') {
            require_once $base_path . 'modules/accounting/transaction_management/export/manage_transactions/pdf/sales/export_manage_transactions_pdf.php';
          } else  if ($export_type == 'print') {
            require_once $base_path . 'modules/accounting/transaction_management/export/manage_transactions/print/sales/export_manage_transactions_print.php';
          }
        }
      }
    }
  } else {
    errorreturn('Transaction Data Not Found');
  }
}
