<?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_to_resources . 'includes/specific_db_config.php';

require_once $base_path . "modules/accounting/reports/valuation_methods/closing_stock_summary/avg_cp_summary_function.php";

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

if (
    !isset($postdata['stock_category']) or !checkIfIssetAndNotEmpty($postdata['stock_category']) 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_stock_summary_group_wise") {

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

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

    // verifying if stock_category_exists 
    $sql = "SELECT group_name from inventory_groups_info where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and group_name = ?";
    $fetch_group_name_main = $specific_db_conn->prepare($sql);
    $fetch_group_name_main->execute(array($workspace_id, $company_id, $branch_id, $book_id, $stock_category));
    $result = $fetch_group_name_main->fetchAll();
    if (count($result) != 1) {
        errorreturn('Unable to find group.');
    }

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

    // this shall be divided into two parts
    // group wise
    // direct children
    $total_closing_value = 0;
    $stock_info = [];

    // gets imediate children group name
    {
        $sql = "SELECT group_name from inventory_groups_info where parent_lvl1 = ? and workspace_id = ? and company_id = ? and branch_id = ? and book_id = ?";
        $fetch_category_subs = $specific_db_conn->prepare($sql);
        $fetch_category_subs->execute(array($stock_category, $workspace_id, $company_id, $branch_id, $book_id));

        // preparing query to get
        $sql_get_stock_id_array = "SELECT id from inventory_stockdetails where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and parent_group IN (SELECT group_name from inventory_groups_info where (parent_lvl1 = ? or parent_lvl2 = ? or parent_lvl3 = ? or parent_lvl4 = ? or parent_lvl5 = ? or parent_lvl6 = ? or parent_lvl7 = ? or parent_lvl8 = ? or parent_lvl9 = ?) and workspace_id = ? and company_id = ? and branch_id = ? and book_id = ?)";
        $get_stock_id_array = $specific_db_conn->prepare($sql_get_stock_id_array);

        $result_category_subs = $fetch_category_subs->fetchAll();
        foreach ($result_category_subs as $row_subs) {
            $get_stock_id_array->execute(array($workspace_id, $company_id, $branch_id, $book_id, $row_subs['group_name'], $row_subs['group_name'], $row_subs['group_name'], $row_subs['group_name'], $row_subs['group_name'], $row_subs['group_name'], $row_subs['group_name'], $row_subs['group_name'], $row_subs['group_name'], $workspace_id, $company_id, $branch_id, $book_id));

            $result_get_stock_id_array = $get_stock_id_array->fetchAll(PDO::FETCH_ASSOC);
            $stock_id_array = [];
            foreach ($result_get_stock_id_array as $temp) {
                $stock_id_array[] = $temp['id'];
            }

            $temp_closing_value = 0;
            $temp_closing_qty = null;
            $temp_closing_rate = null;

            // fetching average for all
            foreach (getAvgCpSummaryClosingStockSpecific($specific_db_conn, $mindate, $maxdate, $workspace_id, $company_id, $branch_id, $book_id, $stock_id_array) as $temp) {
                $temp_closing_value += $temp['closing_stock'];
            }

            $stock_info[] = array(
                'type' => 'category',
                'name' => $row_subs['group_name'],
                'closing_stock' => $temp_closing_value,
                'closing_qty' => $temp_closing_qty,
                'rate' => $temp_closing_rate
            );
            $total_closing_value += $temp_closing_value;
        }
    }

    // get immediate children stock
    // preparing query to get
    $sql_get_stock_id_array = "SELECT id from inventory_stockdetails where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and parent_group = ?";
    $get_stock_id_array = $specific_db_conn->prepare($sql_get_stock_id_array);
    $get_stock_id_array->execute(array($workspace_id, $company_id, $branch_id, $book_id, $stock_category));
    $result_get_stock_id_array = $get_stock_id_array->fetchAll(PDO::FETCH_ASSOC);
    $stock_id_array = [];
    foreach ($result_get_stock_id_array as $temp) {
        $stock_id_array[] = $temp['id'];
    }
    // fetching average for all
    foreach (getAvgCpSummaryClosingStockSpecific($specific_db_conn, $mindate, $maxdate, $workspace_id, $company_id, $branch_id, $book_id, $stock_id_array) as $temp) {
        $stock_info[] = array(
            'type' => 'stock_item',
            'stock_id' => $temp['id'],
            'name' => $temp['stock_name'],
            'closing_stock' => $temp['closing_stock'],
            'closing_qty' => $temp['closing_qty'] . ' ' . $temp['unit_name'],
            'rate' => $temp['rate']
        );
        $total_closing_value += $temp['closing_stock'];
    }

    successreturn(array('total_closing_value' => $total_closing_value, 'stock_info' => $stock_info));
}
