<?php
ini_set('display_errors', 1);

require_once '../../../resources/base_path_include.php';

//valdation file
require_once $base_path_to_resources . "includes/config.php"; // use require for mandatory files
require_once $base_path_to_resources . 'lib/function.php';
require_once $base_path_to_resources . "lib/currency_functions.php";
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';

//function 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/functions/stock_function.php';
require_once $base_path . 'modules/accounting/stock_management/functions/inventory_batch_details_function.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 = $_POST;
// print_r($postdata);die();
// checkIfNoPhpContentsReceive();

$api_signature = $postdata['api_signature'];

if (
    !isset($postdata['company_id']) or
    !isset($postdata['branch_id']) or
    !isset($postdata['book_id']) or
    !isset($postdata['stock_name']) or
    !isset($postdata['parent_group']) or
    !isset($postdata['boolean_inventory']) or
    !isset($postdata['product_type']) or
    !isset($postdata['region_id']) or
    !isset($postdata['api_signature']) or
    !isset($postdata['function_type']) or
    !isset($postdata['jwt_token'])
) {
    errorreturn("All fields are required.");
}
validateApiSignature($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;
$role = $jwt_validate->data->role;
$created_by = $jwt_validate->data->username;


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

$function_code = $postdata['function_type'];

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

$default_tax_ledgerid = (isset($postdata['default_tax_ledgerid']) and !empty($postdata['default_tax_ledgerid'])) ? trim($postdata['default_tax_ledgerid']) : null;
$parent_group = trim($postdata['parent_group']);
$opening_qty = (isset($postdata['opening_qty']) and !empty($postdata['opening_qty']) and is_numeric($postdata['opening_qty'])) ? trim($postdata['opening_qty']) : 0;
$opening_balance = (isset($postdata['opening_balance']) and !empty($postdata['opening_balance'])) ? trim($postdata['opening_balance']) : 0;
$filesattached = (isset($_FILES['filesattached']) and !empty($_FILES['filesattached'])) ? $_FILES['filesattached'] : null;
$boolean_inventory = $postdata['boolean_inventory'];
$tax_applicable = $postdata['tax_applicable'];
$hsn_code = (isset($postdata['hsn_code']) and !empty($postdata['hsn_code'])) ? strtoupper(trim($postdata['hsn_code'])) : null;
$intra_tax_ledgerids = (isset($postdata['intra_tax_ledgerids']) and !empty($postdata['intra_tax_ledgerids'])) ? $postdata['intra_tax_ledgerids'] : null;
$inter_tax_ledgerids = (isset($postdata['inter_tax_ledgerids']) and !empty($postdata['inter_tax_ledgerids'])) ? $postdata['inter_tax_ledgerids'] : null;
$other_tax_ledgerids = (isset($postdata['other_tax_ledgerids']) and !empty($postdata['other_tax_ledgerids'])) ? $postdata['other_tax_ledgerids'] : null;
$inventory_batch_details = (isset($postdata['inventory_batch_details']) and !empty($postdata['inventory_batch_details'])) ? $postdata['inventory_batch_details'] : null;
$product_type = $postdata['product_type'];
$date_created = date('Y-m-d');
$region_id = $postdata['region_id'];
// $unit_id =  trim($postdata['unit_id']);
$unit_id = (isset($postdata['unit_id']) and !empty($postdata['unit_id'])) ? $postdata['unit_id'] : null;

// if inventory appliucable then quantity and opening balance should be received, if not then only opening balance ok

//$default_sp = (isset($postdata['default_sp']) and !empty($postdata['default_sp'])) ? trim($postdata['default_sp']) : null;
if (isset($postdata['default_sp']) and !empty($postdata['default_sp'])) {
    $default_sp = trim($postdata['default_sp']);
} else {
    $default_sp = 0;
}

if (!is_numeric($default_sp)) {
    errorreturn("Invalid default sp. Please provide a numeric value.");
}

if ($hsn_code != null) {
    if (strlen($hsn_code) > 6 or strlen($hsn_code) < 1 or !is_numeric($hsn_code)) {
        errorreturn("Invalid HSN code.");
    }
}

if ($boolean_inventory == 1) {

    $opening_balance = trim(floatval($postdata['opening_balance']));
    $opening_qty = trim(floatval($postdata['opening_qty']));
    if ($opening_qty == 0 and $opening_balance != 0) {

        errorreturn("Opening balance should be zero if opening quantity is zero");
    }
    $single_empty_barcode = 0;
    $unique_barcode_counter = 0;
    $existing_barcode_array = [];

    // Decoding the JSON string to an array
    $inventory_batch_details = json_decode($inventory_batch_details, true);


    if ($inventory_batch_details != null and !empty($inventory_batch_details)) {
        // match the total and rate with batch ids

        $qty_verified = 0;
        $amount_verified = 0;
        foreach ($inventory_batch_details as $temp) {

            //verifying that each element has one qty, barcode and rate
            //if(!is_numeric($temp['rate']) and !is_numeric($temp['qty'])) {

            $qty_verified += $temp['qty'];
            $amount_verified += ($temp['qty'] * $temp['rate']);

            //}

            if (empty(trim($temp['stock_barcode_uin'])) or $temp['stock_barcode_uin'] == $stock_name) {
                $single_empty_barcode++;
            }

            // check for duplicacy and uniqueness
            if (in_array($temp['stock_barcode_uin'], $existing_barcode_array)) {
                errorreturn("All barcodes for a stock item batch should be unique.");
            }
        }
        if ($single_empty_barcode > 1) {
            errorreturn("Only one particular for barcode can be left empty.");
        }

        if ($qty_verified != $opening_qty) {
            errorreturn('Opening quantity is not equal to the quantity in classification.');
        }
        if ($amount_verified != $opening_balance) {
            errorreturn('Opening quantity is not equal to the quantity in classification.');
        }
    } else {
        if ($opening_qty ==  0) {

            $inventory_batch_details[] = array('rate' => 0, 'qty' => 0, 'amount' => 0);
        } else {

            $inventory_batch_details[] = array('rate' => ($opening_balance / $opening_qty), 'qty' => $opening_qty, 'amount' => $opening_balance);
        }
    }

    $current_balance = null;
    $unit_id = (isset($postdata['unit_id']) and !empty($postdata['unit_id'])) ? $postdata['unit_id'] : null;
} else if ($boolean_inventory == 0) {
    $opening_balance = trim($postdata['opening_balance']);
    $current_balance = $opening_balance;
    $opening_qty = 0;
    $inventory_batch_details = null;
}

// verifying stock category
$sql_inventory = $specific_db_conn->prepare("SELECT group_name FROM  inventory_groups_info  where  workspace_id =? and company_id = ? and branch_id = ? and book_id = ? and group_name = ?");
$sql_inventory->execute(array($workspace_id, $company_id, $branch_id, $book_id,$parent_group));
$result_inventory = $sql_inventory->fetchAll();
if (count($result_inventory) != 1) {
    errorreturn("Stock group Not Found.");
}

if($unit_id != null){
$sql_unit = $specific_db_conn->prepare("SELECT symbol FROM   unit_creation  where id = ? and workspace_id =? and company_id = ? and branch_id = ? and book_id = ?");
$sql_unit->execute(array($unit_id, $workspace_id, $company_id, $branch_id, $book_id));
$result_unit = $sql_unit->fetchAll();
if (count($result_unit) == 1) {
    $unit_name = $result_unit[0]['symbol'];
} else {
    errorreturn("Unit Not Found.");
}
}else{
    $unit_name = null;
}

$book_info = GetBasicBook($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id);

$book_opening_date = $book_info['book_basic_info']['book_opening_date'];

// validate if all ledgerids of all three types of taxes are present in ledgerdetail with main_ledgerhead as Duties and Tax
//  store them as a pattern string like implode("', '", $array)  -> a string like '9', '90', '200'

$common_tax_ledgerids = [];

if ($intra_tax_ledgerids != null and is_array($intra_tax_ledgerids)) {
    $temp_ledgerid_array = [];
    foreach ($intra_tax_ledgerids as $temp) {
        $temp_ledgerid_array[] = $temp;
        if (!in_array($temp, $common_tax_ledgerids)) {
            $common_tax_ledgerids[] = $temp;
        }
    }
    $intra_tax_ledgerids = implode("', '", $temp_ledgerid_array);
    $intra_tax_ledgerids = "'" . $intra_tax_ledgerids . "'";
}

if ($inter_tax_ledgerids != null and is_array($inter_tax_ledgerids)) {

    $temp_ledgerid_array = [];
    foreach ($inter_tax_ledgerids as $temp) {
        $temp_ledgerid_array[] = $temp;
        if (!in_array($temp, $common_tax_ledgerids)) {
            $common_tax_ledgerids[] = $temp;
        }
    }
    $inter_tax_ledgerids = implode("', '", $temp_ledgerid_array);
    $inter_tax_ledgerids = "'" . $inter_tax_ledgerids . "'";
}

if ($other_tax_ledgerids != null and is_array($other_tax_ledgerids)) {
    $temp_ledgerid_array = [];
    foreach ($other_tax_ledgerids as $temp) {
        $temp_ledgerid_array[] = $temp;
        if (!in_array($temp, $common_tax_ledgerids)) {
            $common_tax_ledgerids[] = $temp;
        }
    }
    $other_tax_ledgerids = implode("', '", $temp_ledgerid_array);
    $other_tax_ledgerids = "'" . $other_tax_ledgerids . "'";
}

// validating the presence of all tax ledgerids
if ($inter_tax_ledgerids != null or $intra_tax_ledgerids != null or $other_tax_ledgerids != null) {
    $count_tax_ledgerids_received = count($common_tax_ledgerids);
    $append_counter_sql = 0;

    $sql_validate_tax_ledgerids = "Select count(*) as total_tax_ledgerids from act_ledgerdetails where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and id IN('" . implode("', '", $common_tax_ledgerids) . "') and ledger_main_ledgerhead = ?";
    $validate_tax_ledgerids = $specific_db_conn->prepare($sql_validate_tax_ledgerids);
    $validate_tax_ledgerids->execute(array($workspace_id, $company_id, $branch_id, $book_id, 'Duties & Taxes'));

    if ($validate_tax_ledgerids->fetchAll()[0]['total_tax_ledgerids'] != $count_tax_ledgerids_received) {
        errorreturn("Invalid tax ledger selected. Kindly try again.");
    }
}

if (!checkOnlyCharacterNumericBracketHyphenUnderscore($stock_name)) { //_. chara, num,spaces check
    errorreturn("Invalid stock name.");
}

// check region data
$sql_region = $specific_db_conn->prepare("SELECT name FROM   inventory_region_details  where id = ? and workspace_id =? and company_id = ? and branch_id = ? and book_id = ?");
$sql_region->execute(array($region_id, $workspace_id, $company_id, $branch_id, $book_id));
$result_region = $sql_region->fetchAll();
if (count($result_region) != 1) {
    errorreturn("Region Not Found.");
}

$category_file_upload = 'stock_icon';

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

    $res = $specific_db_conn->prepare("SELECT stock_name FROM  inventory_stockdetails WHERE  workspace_id = ? and company_id =? and branch_id =? and book_id  =? and stock_name = ? and region_id =?");
    $res->execute(array($workspace_id, $company_id, $branch_id, $book_id, $stock_name, $region_id));
    $result = $res->fetchAll();
    if (count($result) >= 1) {
        errorreturn("Stock Name already exist");
    }

    if ($filesattached == null) {

        $filesattached = null;
    } else {
        $currentYear = date('Y');
        $currentMonth = date('n');
        $currentDay =  date('d');


        // $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $company_id . "/" . $branch_id . "/" . $book_id . "/stocks_attachments/" . $currentYear . "/" . $currentMonth . "/" . $currentDay . "/";
        $directoryPathMain = "user_uploads/" .  'workspace_'  . $workspace_id . "/" . 'company_' .  $company_id . "/" . 'branch_' .  $branch_id . "/" . 'book_' .  $book_id . "/stocks_attachments/" . $currentYear . "/" . $currentMonth . "/";

        $fileTmpName = $_FILES['filesattached']["tmp_name"];
        $fileSize = $_FILES['filesattached']["size"];
        $fileType = $_FILES['filesattached']["type"];
        $fileError = $_FILES['filesattached']["error"];
        $file_extension = strtolower(pathinfo($_FILES['filesattached']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/heic']; // Allowed image types
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg'];
        $maxFileSize = 2; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }
    $success = InsertStockDetails(
        $specific_db_conn,
        $workspace_id,
        $company_id,
        $branch_id,
        $book_id,
        $stock_name,
        $default_sp,
        $unit_name,
        $unit_id,
        $default_tax_ledgerid,
        $opening_qty,
        $book_opening_date,
        $created_by,
        $parent_group,
        $opening_balance,
        $current_balance,
        null,
        $region_id,
        $boolean_inventory,
        $tax_applicable,
        $hsn_code,
        $intra_tax_ledgerids,
        $inter_tax_ledgerids,
        $other_tax_ledgerids,
        $product_type,
        $inventory_batch_details
    );

    if ($success != false) {
        $stock_id = $success;

        if ($filesattached == null) {
        } else {

            // Generate the image name
            $image_name = $stock_id . "." . $file_extension;
            $keyName = $directoryPathMain . $image_name;

            $party_1 =  null;
            $party_2 =  null;
            $party_3 =  null;
            $date_of_document = null;
            //$reminder_date=  trim(date('Y-m-d', strtotime($postdata['reminder_date'])));
            $reminder_date =  null;
            $last_modified_by = null;
            $termination_document_date =  null;
            //$tags =  null;
            $tags = [$stock_name, $parent_group];
            $share_mode =  'public';
            $share_with =  null;

            // run an updatequery that just updates the path of file in db at the specific row
            $sql = "UPDATE inventory_stockdetails SET filesattached = ? WHERE id = ? and workspace_id = ? and company_id = ? and branch_id= ? and book_id = ?";
            $specific_db_conn->prepare($sql)->execute(array($keyName, $stock_id, $workspace_id, $company_id, $branch_id, $book_id));

            awsS3UserUploadInsert(
                $s3_finware_bucket,
                $finware_bucketName,
                $specific_db_conn,
                $workspace_id,
                $company_id,
                $branch_id,
                $book_id,
                $userid,
                $filesattached,
                $image_name,
                $keyName,
                $size,
                strtolower($file_extension),
                $tags,
                $party_1,
                $party_2,
                $party_3,
                $date_of_document,
                $category_file_upload,
                $stock_id,
                $reminder_date,
                $created_by,
                $last_modified_by,
                $termination_document_date,
                $share_mode,
                $share_with,
                1,
                1
            );
        }
        successreturn(array('stock_id' => $stock_id, 'successmsg' => "Stock added successfully."));
    } else {
        // errorreturn
        errorreturn("Invalid Stock Details.");
    }
} else if ($postdata['function_type']  == "stock_update") {

    if (!isset($postdata['company_id']) or !checkIfIssetAndNotEmpty($postdata['stock_id'])) {
        errorreturn('Error in updating the stock.');
    } else {
        $stock_id = $postdata['stock_id'];
    }


    // $function_code = $postdata['function_type'];
    $remove_bool = (isset($postdata['remove_bool']) and !empty($postdata['remove_bool'])) ? trim($postdata['remove_bool']) : 0; //if logo_remove is 1 then user can delete logo

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


    $function_code = $postdata['function_type'];

    $res = $specific_db_conn->prepare("SELECT boolean_inventory, filesattached FROM  inventory_stockdetails WHERE id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =?");
    $res->execute(array($stock_id, $workspace_id, $company_id, $branch_id, $book_id));
    $result = $res->fetchAll();
    if (count($result) == 1) {
        $boolean_inventory_check = $result[0]['boolean_inventory'];
        $existing_filesattached = $result[0]['filesattached'];

        if ($boolean_inventory_check != $boolean_inventory) {
            $sql_stock = "SELECT count(*) as total FROM inventory_stocktransaction WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? and stock_id = ? ";
            $stmt_stock = $specific_db_conn->prepare($sql_stock);
            $stmt_stock->execute(array($workspace_id, $company_id, $branch_id, $book_id, $stock_id));
            $result_stock = $stmt_stock->fetchAll();
            if ($result_stock[0]['total'] >= 1) {
                errorreturn("Unable to update stock because of the presence in stock transaction.");
            }
        }
    } else {
        errorreturn("Stock not found.");
    }

    $res = $specific_db_conn->prepare("SELECT stock_name FROM  inventory_stockdetails WHERE id != ? and  workspace_id = ? and company_id =? and branch_id =? and book_id  =? and stock_name = ? and region_id = ?");
    $res->execute(array($stock_id, $workspace_id, $company_id, $branch_id, $book_id, $stock_name, $region_id));
    $result = $res->fetchAll();
    if (count($result) >= 1) {
        errorreturn("Stock Name already exist");
    }

    if ($filesattached == null) {
        $filesattached = null;
    } else {

        if ($existing_filesattached === null) {

            $currentYear = date('Y');
            $currentMonth = date('n');
            $currentDay =  date('d');
            $directoryPathMain = "user_uploads/" .  'workspace_'  . $workspace_id . "/" . 'company_' .  $company_id . "/" . 'branch_' .  $branch_id . "/" . 'book_' .  $book_id . "/stocks_attachments/" . $currentYear . "/" . $currentMonth . "/";
        } else {

            $directoryPathMain = substr($existing_filesattached, 0, strrpos($existing_filesattached, '/') + 1);
        }

        $fileTmpName = $_FILES['filesattached']["tmp_name"];
        $fileSize = $_FILES['filesattached']["size"];
        $fileType = $_FILES['filesattached']["type"];
        $fileError = $_FILES['filesattached']["error"];
        $file_extension = strtolower(pathinfo($_FILES['filesattached']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/heic']; // Allowed image types
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg'];
        $maxFileSize = 2; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }

    $success = UpdateStockDetails(
        $specific_db_conn,
        $workspace_id,
        $company_id,
        $branch_id,
        $book_id,
        $stock_id,
        $stock_name,
        $default_sp,
        $unit_name,
        $unit_id,
        $default_tax_ledgerid,
        $opening_qty,
        $book_opening_date,
        $created_by,
        $parent_group,
        $opening_balance,
        $current_balance,
        $region_id,
        $boolean_inventory,
        $tax_applicable,
        $intra_tax_ledgerids,
        $inter_tax_ledgerids,
        $other_tax_ledgerids,
        $hsn_code,
        $product_type,
        $inventory_batch_details
    );

    if ($success == true) {
        
     

        if ($filesattached == null) {
            if ($remove_bool == 1 and $existing_filesattached != null) {
                // get user upload id
                $sql_get_userupload_id = "Select id, let_others_delete, let_others_edit from user_upload where workspace_id = ? and path = ? and category = ? and category_unique_id = ?";
                $get_useruploadid = $specific_db_conn->prepare($sql_get_userupload_id);
                $get_useruploadid->execute(array($workspace_id, $existing_filesattached, 'stock_icon', $stock_id));
                $existing_upload_id = $get_useruploadid->fetchAll();
                // print_r($existing_upload_id);die();
                if (count($existing_upload_id) == 1) {
                    // remove and update
                    awsS3UserUploadDelete($s3_finware_bucket, $finware_bucketName, $specific_db_conn, $workspace_id, $existing_filesattached, $existing_upload_id[0]['id'], true);
                    $sql = "UPDATE inventory_stockdetails SET filesattached = ? WHERE id = ? and workspace_id = ? and company_id = ? and branch_id= ? and book_id = ?";
                    $specific_db_conn->prepare($sql)->execute(array(null, $stock_id, $workspace_id, $company_id, $branch_id, $book_id));
                } else {
                    // do nothing
                }
            }
        } else {
            // Generate the image name
            $image_name = $stock_id . "." . $file_extension;
            $keyName = $directoryPathMain . $image_name;

            $party_1 =  null;
            $party_2 =  null;
            $party_3 =  null;
            $date_of_document = null;
            $category_file_upload = 'stock_icon';
            //$reminder_date=  trim(date('Y-m-d', strtotime($postdata['reminder_date'])));
            $reminder_date =  null;
            $last_modified_by = null;
            $termination_document_date =  null;
            //$tags =  null;
            $tags = [$stock_name, $parent_group];
            $share_mode =  'public';
            $share_with =  null;

            if ($existing_filesattached == null) {
                // insert

                // run an updatequery that just updates the path of file in db at the specific row
                $sql = "UPDATE inventory_stockdetails SET filesattached = ? WHERE id = ? and workspace_id = ? and company_id = ? and branch_id= ? and book_id = ?";
                $specific_db_conn->prepare($sql)->execute(array($keyName, $stock_id, $workspace_id, $company_id, $branch_id, $book_id));

                awsS3UserUploadInsert(
                    $s3_finware_bucket,
                    $finware_bucketName,
                    $specific_db_conn,
                    $workspace_id,
                    $company_id,
                    $branch_id,
                    $book_id,
                    $userid,
                    $filesattached,
                    $image_name,
                    $keyName,
                    $size,
                    strtolower($file_extension),
                    $tags,
                    $party_1,
                    $party_2,
                    $party_3,
                    $date_of_document,
                    $category_file_upload,
                    $stock_id,
                    $reminder_date,
                    $created_by,
                    $last_modified_by,
                    $termination_document_date,
                    $share_mode,
                    $share_with,
                    1,
                    1
                );
            } else {
                // update
                // get user upload id
                $sql_get_userupload_id = "Select id from user_upload where workspace_id = ? and path = ? and category = ? and category_unique_id = ?";
                $get_useruploadid = $specific_db_conn->prepare($sql_get_userupload_id);
                $get_useruploadid->execute(array($workspace_id, $existing_filesattached, 'stock_icon', $stock_id));
                $existing_upload_id = $get_useruploadid->fetchAll();
                // print_r($existing_upload_id);die();
                if (count($existing_upload_id) == 1) {
                    awsS3UserUploadUpdate(
                        $s3_finware_bucket,
                        $finware_bucketName,
                        $specific_db_conn,
                        $workspace_id,
                        $userid,
                        $filesattached,
                        $image_name,
                        $keyName,
                        $size,
                        strtolower($file_extension),
                        $tags,
                        $party_1,
                        $party_2,
                        $party_3,
                        $date_of_document,
                        $category_file_upload,
                        $reminder_date,
                        $last_modified_by,
                        $termination_document_date,
                        $share_mode,
                        $share_with,
                        $existing_upload_id[0]['id'],
                        1,
                        1
                    );
                    // run an update query that just updates the path of file in db at the specific row
                    $sql = "UPDATE inventory_stockdetails SET filesattached = ? WHERE id = ? and workspace_id = ? and company_id = ? and branch_id= ? and book_id = ?";
                    $specific_db_conn->prepare($sql)->execute(array($keyName, $stock_id, $workspace_id, $company_id, $branch_id, $book_id));
                } else {
                    // do nothing
                }
            }
        }

        //success return
        successreturn(array('successmsg' => "Stock updated successfully."));
        // successreturn("Stock updated successfully.");
    } else {
        // errorreturn
        errorreturn("Invalid Stock Details.");
    }
}
