<?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';

//valdation file
require_once $base_path . 'modules/accounting/stock_management/functions/functions.php';
require_once $base_path . 'modules/accounting/stock_management/inventory_regions/region_functions.php';
require_once $base_path . 'modules/accounting/book_management/basic_book_info_function.php';
require_once $base_path . 'modules/accounting/reports/valuation_methods/closing_stock_summary/avg_cp_summary_function.php';
require_once $base_path_to_resources . 'lib/bucket_functions/bucket_functions.php';

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

//aws image store

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

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


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



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

if (
    !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;
$role = $jwt_validate->data->role;
$username = $jwt_validate->data->username;



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


    if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }


    if (isset($postdata['appended_region']) and $postdata['appended_region'] == 1) {
        $appended_region_bool = 1;
    } else {
        $appended_region_bool = 0;
    }

    $company_id = trim($postdata['company_id']);
    $branch_id = trim($postdata['branch_id']);
    $book_id = trim($postdata['book_id']);
    $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);
        }
    }
    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;

    $book_info = GetBasicBook($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id);
    $book_name = $book_info['book_basic_info']['book_name'];
    $book_opening_date = $book_info['book_basic_info']['book_opening_date'];
    $book_closing_date = $book_info['book_basic_info']['book_closing_date'];

    $additionaldata = array();
    // $additionaldata = ['id', 'stock_name', 'current_qty', 'parent_group'];
    $additionaldata = ['id', 'stock_name', 'current_qty', 'default_sp', 'current_balance', 'boolean_inventory'];

    $additionaldata = array_merge($additionaldata, $postdata['additional_data']);

    $limit = $postdata['limit'];

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
    } else {
        $offset = null;
    }

    $export_type = (isset($postdata['export_type']) and !empty($postdata['export_type'])) ? trim($postdata['export_type']) : null;

    if (isset($export_type)) { // true // value check should either be spreadsheet pdf 
        if ($export_type == 'spreadsheet') {

            require_once $base_path . 'modules/accounting/stock_management/export/manage_stocks/excel/export_manage_stocks_excel.php';
        } else  if ($export_type == 'pdf') {

            require_once $base_path . 'modules/accounting/stock_management/export/manage_stocks/pdf/export_manage_stocks_pdf.php';
        } else if ($export_type == 'print') {

            require_once $base_path . 'modules/accounting/stock_management/export/manage_stocks/print/export_manage_stocks_print.php';
        }
    } else {

        if ($limit != 'all') {
            $offset = ($page - 1) * $limit;
            $success['data'] = GetStockDetail($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $search_string, $additionaldata, $limit, $offset, $appended_region_bool, $book_opening_date, $book_closing_date);
            successreturn($success);
        } else {

            $success['data'] = GetStockDetail($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $search_string, $additionaldata, $limit, null, $appended_region_bool, $book_opening_date, $book_closing_date);
            successreturn($success);
        }
    }
}
