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

// including the basic files
// validating the inputs: mindate, maxdate, function_type == 'profit_loss_account', valuation_method (FIFO, LIFO, AVG_CP)
// calling the function of P & L Account


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


require_once $base_path_to_resources . "includes/config.php"; // use require for mandatory files
require_once $base_path_to_resources . 'lib/function.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/net_group_summary/net_group_summary/net_group_summary_function.php";
// require_once $base_path . "modules/accounting/groups_ledgers/functions/ledger_functions.php";

//creating dynamic db
require_once $base_path_to_resources . 'includes/specific_db_config.php';
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();
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;
//print_r($workspace_id);die();
$role = $jwt_validate->data->role;

$username = $jwt_validate->data->username;

if ($postdata['function_type']  == "profit_loss_account") {
  $company_id = trim($postdata['company_id']);
  $branch_id = trim($postdata['branch_id']);
  $book_id = trim($postdata['book_id']);

  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/net_group_summary/net_group_summary_function.php";
  $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'];
  $book_closing_date = $book_info['book_basic_info']['book_closing_date'];


  if (isset($postdata['mindate']) and !empty($postdata['mindate']) and isset($postdata['maxdate']) and !empty($postdata['maxdate']) and strtotime($postdata['mindate']) and strtotime($postdata['maxdate'])) {
    $mindate = trim($postdata['mindate']);
    $maxdate = trim($postdata['maxdate']);
  } else errorreturn('Kindly enter valid dates.');

  //   if ($mindate < $book_opening_date or $maxdate > $book_closing_date or $mindate > $maxdate) {
  //     errorreturn('Kindly enter valid dates2.');
  //   }

  if (!strtotime($mindate) or $mindate < $book_opening_date) {
    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');
  }

  // include valuation_method file
  if ($valuation_method == 'FIFO') {
    require_once '../valuation_methods/closing_stock_summary/fifo_summary_function.php';
    $stock_object = getFifoSummaryClosingStock($specific_db_conn, $mindate, $maxdate, $workspace_id, $company_id, $branch_id, $book_id);
  } else if ($valuation_method == 'LIFO') {
    require_once '../valuation_methods/closing_stock_summary/lifo_summary_function.php';
    $stock_object = getFifoSummaryClosingStock($specific_db_conn, $mindate, $maxdate, $workspace_id, $company_id, $branch_id, $book_id);
  } else if ($valuation_method == 'AVG_CP') {
    require_once '../valuation_methods/closing_stock_summary/avg_cp_summary_function.php';
    $stock_object = getAvgCpSummaryClosingStock($specific_db_conn, $mindate, $maxdate, $workspace_id, $company_id, $branch_id, $book_id);
  }
  if ($stock_object['status'] == 1) {
    $closing_stock = $stock_object['closing_stock'];

    $opening_stock = $stock_object['opening_stock'];
  } else {
    errorreturn('Error in calculating stock valuation.');
  }

  require_once $base_path . "modules/accounting/reports/profitloss/function_profit_loss.php";
  $success['data'] = getProfitLossAccount($specific_db_conn, $mindate, $maxdate, $workspace_id, $company_id, $branch_id, $book_id, $book_opening_date, $closing_stock, $opening_stock);
  successreturn($success);
}
