<?php
ini_set('display_errors', 1);
//error_reporting(0);


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_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';
require_once $base_path . 'modules/accounting/book_management/basic_book_info_function.php';

require_once $base_path . '/modules/accounting/reports/balancesheet/bs_groups_structure.php';
require_once $base_path_to_resources . 'includes/specific_db_config.php';

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

if (
    !isset($postdata['bs_group_name']) or !checkIfIssetAndNotEmpty($postdata['bs_group_name']) 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['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
$created_by = $jwt_validate->data->username;
$workspace_id = $jwt_validate->data->workspace_id;
$role = $jwt_validate->data->role;
$userid = $jwt_validate->data->id;



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

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

    if (isset($postdata['valuation_method'])) {
        $valuation_method = $postdata['valuation_method'];
        if (!in_array($valuation_method, ['FIFO', 'LIFO', 'AVG_CP'])) {
            $valuation_method = 'FIFO';
        }
    } else {
        $valuation_method = 'AVG_CP';
    }

    $function_code = $postdata['function_type'];
    // checking who is accessing the file
    $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);
        }
    }
    require_once $base_path . 'modules/accounting/reports/net_group_summary/bs_group_summary/classified_bs_group_summary.php';
    // check here if this group name received exists in balance sheet groups or not
    $bs_group_selected = null;
    $error_counter = 1;

    foreach ($default_bs_groups as $temp) {
        //   print_r($default_bs_groups);
        if ($temp['bs_group_name'] == $bs_group_name) { {

                $error_counter = 0;
                $bs_group_selected = $temp;
                break;
            }
        }
    }


    if ($error_counter == 1) {
        errorreturn('Group details not found.');
    }

    $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'];



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

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

    if (!strtotime($mindate) or $mindate < $book_opening_date) {
        // echo $mindate,$book_opening_date;die();
        errorreturn('Mininum date cannot be less than book opening date');
    }

    if (!strtotime($maxdate) or $maxdate > $book_closing_date) {

        errorreturn('Maximum date cannot be less than book opening date');
    }
    if ($maxdate < $mindate) {

        errorreturn('Invalid Date format');
    }


    $success['data'] = ClassifiedBsGroupSummary($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $mindate, $maxdate, $bs_group_selected, $valuation_method);
    successreturn($success);
}
