<?php

ini_set('display_errors', 1);

require_once '../../../../resources/base_path_include.php';
// should we not call header and ch
//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';
//creating dynamic db
require_once $base_path_to_resources . 'includes/specific_db_config.php';

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

// either the user has to fill gst or pan or ledgerhead 

function fetchInventoryRegionGroups($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $search_string, $limit, $offset)
{

  $sql = "Select count(*) as total_rows from inventory_region_details where workspace_id = ? and company_id =? and branch_id =? and book_id  =? and name like ?";
  $array_params = [$workspace_id, $company_id, $branch_id, $book_id, '%' . $search_string . '%'];
  $validate_region = $specific_db_conn->prepare($sql);
  $validate_region->execute($array_params);

  $result_total = $validate_region->fetchAll();
  $totalrows = $result_total[0]['total_rows'];

  $data = array();


  if ($limit == 'all') {
    $sql_region = "Select * FROM inventory_region_details WHERE workspace_id= ? and company_id = ? and branch_id= ? and book_id =? and name LIKE ?";
    /// $array_params = [$workspace_id,$company_id,$branch_id,$book_id,'%' . $search . '%'];

    $stmt = $specific_db_conn->prepare($sql_region);
    $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, '%' . $search_string . '%'));
    $result = $stmt->fetchAll();
  } else {

    $sql_region = "Select * FROM inventory_region_details WHERE workspace_id= ? and company_id = ? and branch_id= ? and book_id =? and name LIKE ? LIMIT $offset,$limit ";
    /// $array_params = [$workspace_id,$company_id,$branch_id,$book_id,'%' . $search . '%'];

    $stmt = $specific_db_conn->prepare($sql_region);
    $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, '%' . $search_string . '%'));
    $result = $stmt->fetchAll();
  }

  foreach ($result as $rows) {
    $data[] = array('region_id' => $rows['id'], 'name' => $rows['name'], 'address' => $rows['address'], 'city' => $rows['city'], 'pincode' => $rows['pincode']);
  }

  if (count($result) < 50) {
    return array('total_rows' => $totalrows, 'region_info' => $data, 'maxreach' => 1);
  } else {
    return array('total_rows' => $totalrows, 'region_info' => $data, 'maxreach' => 0);
  }
}


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

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

  $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;
  $limit = $postdata['limit'];

  if ($limit != 'all') {
    $offset = ($page - 1) * $limit;
    $success = fetchInventoryRegionGroups($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $search_string, $limit, $offset);
    successreturn($success);
  } else {
    $success = fetchInventoryRegionGroups($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $search_string, $limit, null);
    successreturn($success);
  }
}
