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

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

//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['name']) or !checkIfIssetAndNotEmpty($postdata['name']) 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;
$created_by = $jwt_validate->data->username;


$company_id = trim($postdata['company_id']);
$branch_id = trim($postdata['branch_id']);
$book_id = trim($postdata['book_id']);
$name = trim($postdata['name']);
$address = (isset($postdata['address']) and !empty($postdata['address'])) ? trim($postdata['address']) : null;
$city = (isset($postdata['city']) and !empty($postdata['city'])) ? trim($postdata['city']) : null;
$pincode = (isset($postdata['pincode']) and !empty($postdata['pincode'])) ? trim($postdata['pincode']) : null;
$country = (isset($postdata['country']) and !empty($postdata['country'])) ? trim($postdata['country']) : null;


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

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

    //if(!CheckAddressValidation($address)) { 
    //eg House Name, Street Name
    // errorreturn('Invalid Address');
    //}

    //Branch Pin Code Validation 
    //if(!PinCodeValidation($pincode)) { // 6 digit only
    //eg House Name, Street Name
    // errorreturn('Invalid Pin Code');
    //}


    $res = $specific_db_conn->prepare("SELECT name FROM inventory_region_details WHERE name = ? and workspace_id= ? and company_id = ? and branch_id= ? and book_id =?");
    $res->execute(array($name, $workspace_id, $company_id, $branch_id, $book_id));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("Inventory region already exists");
    }

    try {
        $sql = "INSERT INTO inventory_region_details(workspace_id,company_id,branch_id,book_id,name,address,city,pincode,country)
            VALUES(?,?,?,?,?,?,?,?,?)";
        $stmt =  $specific_db_conn->prepare($sql);
        $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, $name, $address, $city, $pincode, $country));
        $id = $specific_db_conn->lastInsertId();

        successreturn(array('region_id' => $id, 'successmsg' => "Successfully inventory region added."));
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }
} else if ($postdata['function_type'] == "alter_inventory_region") {

    if (!isset($postdata['region_id']) or !checkIfIssetAndNotEmpty($postdata['region_id'])) {
         errorreturn('Error in updating the region.');
     } else {
          $id = $postdata['region_id'];
     }
   

    // validate from branch if existing super admins 
    $res = $specific_db_conn->prepare("SELECT * FROM inventory_region_details WHERE id= ? and workspace_id =? and company_id = ? and branch_id = ? and book_id = ?");
    $res->execute(array($id, $workspace_id, $company_id, $branch_id, $book_id));
    $result_count = $res->fetchAll();

    if ($result_count[0]['name'] == 'Primary') {
        errorreturn("Contact Adminstrator.");
    }

    // validate from branch if existing super admins 
    $res = $specific_db_conn->prepare("SELECT * FROM inventory_region_details WHERE id != ? and workspace_id =? and company_id = ? and branch_id = ? and book_id = ? and name=?");
    $res->execute(array($id, $workspace_id, $company_id, $branch_id, $book_id, $name));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("Inventory region already exists");
    }

    $sql = "UPDATE inventory_region_details SET name=?, address=?, city=?,pincode=?,country=? WHERE id=? and workspace_id  =? and company_id=? and branch_id =? and book_id = ?";
    $specific_db_conn->prepare($sql)->execute(array($name, $address, $city, $pincode, $country, $id, $workspace_id, $company_id, $branch_id, $book_id));

    successreturn("Updated Inventory region Successfully");
}
