<?php

/* 
stock_id, stock_name, mindate, maxdate, stock_closing_default : {
inwards, outwards, closing
},stock_transactions_closing : {
inwards, outwards, closing
}
 transactions_info : [
    [date, particulars, transaction_type, transaction_unique_id, transaction_id, inwards, outwards, closing], 
    [date, particulars, transaction_type, transaction_unique_id, transaction_id, inwards, outwards, closing]
]

*/

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/functions/basic_balance_function.php';

require_once $base_path . 'modules/accounting/groups_ledgers/functions/ledger_functions.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_id']) or !checkIfIssetAndNotEmpty($postdata['stock_id']) or
    !isset($postdata['mindate']) or !checkIfIssetAndNotEmpty($postdata['mindate']) or
    !isset($postdata['maxdate']) or !checkIfIssetAndNotEmpty($postdata['maxdate']) 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_details_monthwise") {

    $company_id = trim($postdata['company_id']);
    $branch_id = trim($postdata['branch_id']);
    $book_id = trim($postdata['book_id']);
    $stock_id = trim($postdata['stock_id']);
    $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);
        }
    }

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

    function getMonthsBetweenDates($start_date, $end_date)
    {
        $start = new DateTime($start_date);
        $end = new DateTime($end_date);
        $interval = DateInterval::createFromDateString('1 month');
        $period = new DatePeriod($start, $interval, $end);

        $months = [];
        foreach ($period as $dt) {
            $months[] = $dt->format('Y-m');
        }

        return $months;
    }
    $months_between = getMonthsBetweenDates($mindate, $maxdate);

    $stock_info = [];

    $stock_purchased_qty = 0;
    $stock_purchased_value = 0;

    $stock_sales_qty = 0;
    $stock_sales_value = 0;

    $total_closing_stock = 0;
    $total_closing_value = 0;

    if ($mindate == $book_opening_date) {
        $stock_valuation_opening_obj = getAvgCpSummaryClosingStockSpecific($specific_db_conn, $mindate, $maxdate, $workspace_id, $company_id, $branch_id, $book_id, [$stock_id]);

        $stock_name = $stock_valuation_opening_obj[0]['stock_name'];
        $stock_opening = $stock_valuation_opening_obj[0]['opening_stock'];
        $unit_name = $stock_valuation_opening_obj[0]['unit_name'];
        $stock_opening_qty = $stock_valuation_opening_obj[0]['opening_qty'];
    } else {
        $stock_valuation_opening_obj = getAvgCpSummaryClosingStockSpecific($specific_db_conn, $mindate, date('Y-m-d', strtotime('-1 day', strtotime($mindate))), $workspace_id, $company_id, $branch_id, $book_id, [$stock_id]);

        print_r($stock_valuation_opening_obj);
        die();

        $stock_name = $stock_valuation_opening_obj[0]['stock_name'];
        $stock_opening = $stock_valuation_opening_obj[0]['closing_stock'];
        $unit_name = $stock_valuation_opening_obj[0]['unit_name'];
        $stock_opening_qty = $stock_valuation_opening_obj[0]['closing_qty'];
    }

    $opening_balance = array(
        'inwards' => array(
            'qty' => $stock_opening_qty > 0 ? $stock_opening_qty . ' ' . $unit_name  : '',
            'value' => $stock_opening > 0 ? $stock_opening : ''
        ),
        'outwards' => array(
            'qty' => $stock_opening_qty < 0 ? $stock_opening_qty . ' ' . $unit_name  : '',
            'value' => $stock_opening_qty < 0 ? $stock_opening : ''
        ),
        'closing' => array(
            'qty' => $stock_opening_qty != 0 ? $stock_opening_qty . ' ' . $unit_name  : '',
            'value' => $stock_opening != 0 ? $stock_opening : ''
        ),
    );

    if ($stock_opening_qty > 0) {
        $stock_purchased_qty += $stock_opening_qty;
        $stock_purchased_value += $stock_opening;
    } else {
        $stock_sales_qty += abs($stock_opening_qty);
        $stock_sales_value += abs($stock_opening);
    }

    $total_closing_stock += $stock_opening_qty;
    $total_closing_value += $stock_opening;

    // month code starts now

    $sql = "SELECT SUM(qty) as qty, SUM(total_amount) as total_amount, type from inventory_stocktransaction where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and stock_id = ? and date LIKE ? and date >= ? and date <= ? group by type";
    $fetch_month_transactions = $specific_db_conn->prepare($sql);

    foreach ($months_between as $month) {
        $fetch_month_transactions->execute(array($workspace_id, $company_id, $branch_id, $book_id, $stock_id, $month . '-%', $mindate, $maxdate));
        $result_month_transactions = $fetch_month_transactions->fetchAll();

        $month_purchase_qty = 0;
        $month_purchase_value = 0;
        $month_sales_qty = 0;
        $month_sales_value = 0;

        foreach ($result_month_transactions as $row_month_transactions) {
            if ($row_month_transactions['type'] == 'purchase') {
                $month_purchase_qty = $row_month_transactions['qty'];
                $month_purchase_value = $row_month_transactions['total_amount'];
            } else if ($row_month_transactions['type'] == 'sales') {
                $month_sales_qty = $row_month_transactions['qty'];
                $month_sales_value = $row_month_transactions['total_amount'];
            }
        }

        $stock_purchased_qty += $month_purchase_qty;
        $stock_purchased_value += $month_purchase_value;

        $stock_sales_qty += $month_sales_qty;
        $stock_sales_value += $month_sales_value;

        $new_stock_average = $stock_purchased_value / $stock_purchased_qty;

        $total_closing_stock = ($stock_purchased_qty - $stock_sales_qty);
        $total_closing_value = $total_closing_stock * $new_stock_average;

        $inwards = ['qty' => $month_purchase_qty != 0 ? $month_purchase_qty . ' ' . $unit_name : 0, 'value' => $month_purchase_value];
        $outwards = ['qty' => $month_sales_qty != 0 ? $month_sales_qty . ' ' . $unit_name : 0, 'value' => $month_sales_value];

        $closing_transaction = [
            'qty' => $total_closing_stock != 0 ? $total_closing_stock . ' ' . $unit_name : 0,
            'value' => $total_closing_value
        ];

        $stock_info[] = array(
            'month' => date_format(new DateTime($month), 'M Y'),
            'inwards' => $inwards,
            'outwards' => $outwards,
            'closing' => $closing_transaction
        );
    }

    $grand_total = [
        'inwards' => [
            'qty' => $stock_purchased_qty != 0 ? $stock_purchased_qty . ' ' . $unit_name : 0,
            'value' => $stock_purchased_value
        ],
        'outwards' => [
            'qty' => $stock_sales_qty != 0 ? $stock_sales_qty . ' ' . $unit_name : 0,
            'value' => $stock_sales_value
        ],
        'closing' => [
            'qty' => $total_closing_stock != 0 ? $total_closing_stock . ' ' . $unit_name : 0,
            'value' => $total_closing_value
        ]
    ];

    successreturn(array(
        "stock_id" => $stock_id, "stock_name" => $stock_name, 'total_closing_value' => $total_closing_value, 'stock_info' => $stock_info,
        'opening_balance' => $opening_balance,
        'grand_total' => $grand_total
    ));
} else {
    errorreturn('Access denied.');
}
// [date, particulars, transaction_type, transaction_unique_id, transaction_id, inwards, outwards, closing], 
