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

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

//valdation file
require_once $base_path . 'user_management/authenticate.php';
require_once $base_path . 'modules/accounting/groups_ledgers/functions/group_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();

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['group_name']) or !checkIfIssetAndNotEmpty($postdata['group_name']) or !isset($postdata['parent_ledgerhead']) or !checkIfIssetAndNotEmpty($postdata['parent_ledgerhead'])
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;



if ($postdata['function_type'] == "create_group") {
    
    $function_code = $postdata['function_type'];
    $company_id = trim($postdata['company_id']);
    $branch_id = trim($postdata['branch_id']);
    $book_id = trim($postdata['book_id']);
    $group_name = trim($postdata['group_name']);
    $parent_ledgerhead = trim($postdata['parent_ledgerhead']);

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

    //the below variables are to be assigned by database data
    $main_ledgerhead = null; // cannot be null
    $parent_lvl1 = null; // can be null
    $parent_lvl2 = null;
    $parent_lvl3 = null;
    $parent_lvl4 = null;
    $parent_lvl5 = null;

    // things to do after this point
    #1. check if the group_name entered == ledgerheads_basic, then give error
    $res = $conn->prepare("SELECT ledgerhead_name FROM  act_ledgerheads_basic WHERE ledgerhead_name = ?  ");
    $res->execute(array($group_name));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        // return error that group name cannot be equal to any existing ledgerheads or group names
        errorreturn("Group name cannot be equal to any existing ledgerheads or group names");
    }

    // things to do after this point
    #1. check if the group_name entered == ledgerheads_basic, then give error
    $res = $specific_db_conn->prepare("SELECT group_name FROM  act_group_info WHERE group_name = ? and workspace_id = ? and company_id =? and branch_id =? and book_id =?");
    $res->execute(array($group_name, $workspace_id, $company_id, $branch_id, $book_id));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        // return error that group name cannot be equal to any existing ledgerheads or group names
        errorreturn("Group name cannot be equal to any existing ledgerheads or group names");
    }

    try {

        #1. You are receiving group name, parent_ledgerhead.
        #2. Check if the parent_ledgerhead exists in ledgerhead basics, if yes main_ledgerhead = parent_ledgerhead, no parent level needs to be filled
        #3. If not, then Select group_name, main_ledgerhead, parent_lvl1...parent_lvl5 from group_info where group_name = $parent_ledgerhead
        #4. The row found is used to set variables.
        #5. $result of third will give us the main_ledgerhead.


        //the below variables are to be assigned by database data
        $main_ledgerhead = null; // cannot be null
        $parent_lvl1 = null; // can be null
        $parent_lvl2 = null;
        $parent_lvl3 = null;
        $parent_lvl4 = null;
        $parent_lvl5 = null;
        // the above variables will be used in both insert and alter query


        $sql1 = "Select ledgerhead_name from  act_ledgerheads_basic where ledgerhead_name = ?";
        $stmt = $conn->prepare($sql1);
        $stmt->execute(array($parent_ledgerhead));
        $result1 = $stmt->fetchAll();

        if (count($result1) == 1) {

            $main_ledgerhead = $parent_ledgerhead;
        } else {

            $sql1 = "Select group_name,main_ledgerhead,parent_lvl1,parent_lvl2,parent_lvl3,parent_lvl4,parent_lvl5 from act_group_info where group_name = ? and workspace_id = ? and company_id =? and branch_id =? and book_id =?";
            $stmt = $specific_db_conn->prepare($sql1);
            $stmt->execute(array($parent_ledgerhead, $workspace_id, $company_id, $branch_id, $book_id));
            $result2 = $stmt->fetchAll();
            // print_r($result2);die();
            foreach ($result2 as $row1) {


                if ($row1['parent_lvl5'] != '') {
                    // errorretutn you have reached maximum no of subgroups allowed inside this lebel
                    errorreturn("you have reached maximum no of subgroups allowed inside this lebel");
                }
                $main_ledgerhead = $row1['main_ledgerhead'];
                $parent_lvl1 = $parent_ledgerhead;
                $parent_lvl2 = $row1['parent_lvl1'];
                $parent_lvl3 = $row1['parent_lvl2'];
                $parent_lvl4 = $row1['parent_lvl3'];
                $parent_lvl5 = $row1['parent_lvl4'];
            }
        }


        $sql = "INSERT INTO act_group_info(workspace_id,company_id,branch_id,book_id,group_name,main_ledgerhead,parent_lvl1,parent_lvl2,parent_lvl3,parent_lvl4, parent_lvl5) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
        $stmt =  $specific_db_conn->prepare($sql);
        $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, $group_name, $main_ledgerhead, $parent_lvl1, $parent_lvl2, $parent_lvl3, $parent_lvl4, $parent_lvl5));

        $id = $specific_db_conn->lastInsertId();

        successreturn(array('group_id' => $id, 'successmsg' => "Successfully Groups added"));
    } catch (Exception $e) {
        echo 'Exception -> ';
        var_dump($e->getMessage());
    }
} else if ($postdata['function_type'] == "alter_group") {
     if (!isset($postdata['company_id']) or !checkIfIssetAndNotEmpty($postdata['group_id'])) {
            errorreturn('Error in updating the group.');
        } else {
            $id = $postdata['group_id'];
        }
        

    $function_code = $postdata['function_type'];
    $company_id = $postdata['company_id'];
    $branch_id = $postdata['branch_id'];
    $book_id = $postdata['book_id'];
   
    $group_name = trim($postdata['group_name']);
    $parent_ledgerhead = trim($postdata['parent_ledgerhead']);
    $main_ledgerhead = null; // cannot be null
    $parent_lvl1 = null; // can be null
    $parent_lvl2 = null;
    $parent_lvl3 = null;
    $parent_lvl4 = null;
    $parent_lvl5 = null;
    
    $confirmed_role_user = validatePrimaryAccess($conn, $workspace_id, $role, $userid, ['superadmin', 'admin', null]);
    // $confirmed_role_user = validatePrimaryAccess($conn, $workspace_id, $company_id, $branch_id, null, $role, $userid, $function_code, ['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);
        }
    }

    $sql_count = "Select id,company_id,branch_id,workspace_id,group_name from act_group_info where id = ? and  workspace_id  =? and company_id =? and branch_id =? and book_id =?";
    $stmt_count = $specific_db_conn->prepare($sql_count);
    $stmt_count->execute(array($id, $workspace_id, $company_id, $branch_id, $book_id));
    $result_count = $stmt_count->fetchAll();
    if (count($result_count) < 1) {
        errorreturn("Group Info not exists.");
    }


    $res = $specific_db_conn->prepare("SELECT * FROM act_group_info WHERE id != ? and  workspace_id  =? and company_id =? and branch_id =? and book_id =? and group_name= ? ");
    $res->execute(array($id, $workspace_id, $company_id, $branch_id, $book_id, $group_name));
    $result1 = $res->fetchAll();
    // print_r($result1);
    if (count($result1) >= 1) {
        errorreturn("Group Name already exists");
    }


    $sql1 = "Select group_name from act_group_info where id = ? and  workspace_id  =? and company_id =? and branch_id =? and book_id =?";
    $stmt = $specific_db_conn->prepare($sql1);
    $stmt->execute(array($id, $workspace_id, $company_id, $branch_id, $book_id));
    $result1 = $stmt->fetchAll();

    $existing_group_name = $result1[0]['group_name'];


    $sql1 = "Select ledgerhead_name from  act_ledgerheads_basic where ledgerhead_name = ?";
    $stmt = $conn->prepare($sql1);
    $stmt->execute(array($parent_ledgerhead));
    $result1 = $stmt->fetchAll();

    if (count($result1) == 1) {
        $main_ledgerhead = $parent_ledgerhead;
    } else {

        $sql1 = "Select group_name,main_ledgerhead,parent_lvl1,parent_lvl2,parent_lvl3,parent_lvl4,parent_lvl5 from act_group_info where group_name =? and workspace_id = ? and company_id =? and branch_id =? and book_id =?";
        $stmt = $specific_db_conn->prepare($sql1);
        $stmt->execute(array($parent_ledgerhead, $workspace_id, $company_id, $branch_id, $book_id));
        $result2 = $stmt->fetchAll();
        // print_r($result2);
        foreach ($result2 as $row1) {

            $main_ledgerhead = $row1['main_ledgerhead'];
            $parent_lvl1 = $parent_ledgerhead;
            $parent_lvl2 = $row1['parent_lvl1'];
            $parent_lvl3 = $row1['parent_lvl2'];
            $parent_lvl4 = $row1['parent_lvl3'];
            $parent_lvl5 = $row1['parent_lvl4'];
        }
    }

    $sql = "UPDATE act_group_info SET group_name =?,main_ledgerhead = ?,parent_lvl1 =?,parent_lvl2 =?,parent_lvl3 =?,parent_lvl4=?,parent_lvl5=? WHERE id=? and workspace_id  =? and company_id =? and branch_id =? and book_id =?";
    $specific_db_conn->prepare($sql)->execute(array($group_name, $main_ledgerhead, $parent_lvl1, $parent_lvl2, $parent_lvl3, $parent_lvl4, $parent_lvl5, $id, $workspace_id, $company_id, $branch_id, $book_id));


    $sql = "UPDATE act_ledgerdetails SET ledger_parent_group =?,ledger_main_ledgerhead = ? where ledger_parent_group =? and workspace_id  =? and company_id =? and branch_id =? and book_id =?";
    $specific_db_conn->prepare($sql)->execute(array($group_name, $main_ledgerhead, $existing_group_name, $workspace_id, $company_id, $branch_id, $book_id));

    //update parent level group
    if ($existing_group_name != $group_name) {
        $i = 0;
        for ($i = 1; $i <= 5; $i++) {

            $field = 'parent_lvl' . $i;
            $sql = "UPDATE act_group_info SET " . $field . "=? WHERE workspace_id  =? and company_id =? and branch_id =? and book_id =? and " . $field . "=?";
            $specific_db_conn->prepare($sql)->execute(array($group_name, $workspace_id, $company_id, $branch_id, $book_id, $existing_group_name));
        }
    }

    successreturn("Updated group info Successfully");
}
