<?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';
//valdation file
require_once $base_path . 'modules/accounting/groups_ledgers/functions/group_functions.php';

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

if (!isset($postdata['group_id']) or !checkIfIssetAndNotEmpty($postdata['group_id']) 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
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$role = $jwt_validate->data->role;
$username = $jwt_validate->data->username;

function deleteGroupInfo($specific_db_conn, $group_id, $workspace_id, $company_id, $branch_id, $book_id)
{
    $sql = "Select group_name  from inventory_groups_info where id = ? and  workspace_id = ? and company_id =? and branch_id =? and book_id =? ";
    $stmt_groups = $specific_db_conn->prepare($sql);
    $stmt_groups->execute(array($group_id, $workspace_id, $company_id, $branch_id, $book_id));
    $fetch_groups = $stmt_groups->fetchAll();

    $group_name = $fetch_groups[0]['group_name'];
    
    if($group_name == 'Primary') {
        errorreturn("Unable to delete Primary category.");
    }
    $sql = "SELECT count(*) as total FROM inventory_groups_info WHERE   (parent_lvl1 = ? or  parent_lvl2 = ? or  parent_lvl3 = ? or  parent_lvl4 = ? or  parent_lvl5 = ?) and workspace_id = ? 
    and company_id =? and branch_id =? and book_id =? ";
    $stmt = $specific_db_conn->prepare($sql);
    $stmt->execute(array($group_name, $group_name, $group_name, $group_name, $group_name, $workspace_id, $company_id, $branch_id, $book_id));
    $act_groupinfo = $stmt->fetchAll();
    if ($act_groupinfo[0]['total'] >= 1) {
        errorreturn("Unable to delete group name because of the presence of sub groups1.");
    } else {

        // check here if it is used in any ledgerdetails in ledger_parent_group
        $sql = "SELECT count(*) as total FROM  inventory_stockdetails WHERE parent_group = ? and workspace_id = ? and company_id =? and branch_id =? and book_id =? ";
        $stmt = $specific_db_conn->prepare($sql);
        $stmt->execute(array($group_name, $workspace_id, $company_id, $branch_id, $book_id));
        $act_ledger = $stmt->fetchAll();
        if ($act_ledger[0]['total'] >= 1) {
            errorreturn("Unable to delete group name because of the presence in ledger details.");
        }
    }

    $sql = "DELETE FROM inventory_groups_info WHERE id=? and workspace_id = ?  and company_id =? and branch_id =? and book_id =? ";
    $stmt = $specific_db_conn->prepare($sql);
    $stmt->execute(array($group_id, $workspace_id, $company_id, $branch_id, $book_id));
    $act_group = $stmt->rowCount();
    if ($act_group == 1) {
        return "Delete group  Successfully";
    } else {
        errorreturn("Unable to delete group name because of the presence of sub groups.");
    }
}

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

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

    $success['data'] = deleteGroupInfo($specific_db_conn, $group_id, $workspace_id, $company_id, $branch_id, $book_id);
    successreturn($success);
}
