<?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/transaction_management/functions/get_transaction_uniqueid.php';
require_once $base_path . 'modules/accounting/global_settings/transaction_settings/function_renumber_automatic_transaction.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['setting_id']) or !checkIfIssetAndNotEmpty($postdata['setting_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['transaction_numbering_system']) or !isset($postdata['transaction_numbering_system'])
    or !isset($postdata['prefix_financial_year']) or !isset($postdata['additional_transaction_prefix']) 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;




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


    $function_code = $postdata['function_type'];
    $setting_id = trim($postdata['setting_id']);
    $company_id = trim($postdata['company_id']);
    $branch_id = trim($postdata['branch_id']);
    $book_id = trim($postdata['book_id']);

    $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, null, null, null,  $postdata['function_type']);
        }
    }

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

    $transaction_numbering_system = $postdata['transaction_numbering_system']; //Automatic / Manual / Automatic Override Manual

    $manual_transactiontypes = $transaction_numbering_system['manual'];
    $automatic_transactiontypes = $transaction_numbering_system['automatic'];


    $prefix_financial_year = trim($postdata['prefix_financial_year']);
    // check should only be 1 / 0
    if ($prefix_financial_year != 1 and $prefix_financial_year != 0) {
        errorreturn('Unable to update transaction settings.');
    }

    $res = $specific_db_conn->prepare("SELECT transaction_numbering_system, additional_transaction_prefix, prefix_financial_year FROM act_book_settings WHERE id = ? and workspace_id =? and company_id = ? and branch_id = ? and book_id = ? ");
    $res->execute(array($setting_id, $workspace_id, $company_id, $branch_id, $book_id));
    $result1 = $res->fetchAll();
    if (count($result1) != 1) {
        errorreturn("Book setting does not exist.");
    } else {
        $existing_transaction_numbering_system = json_decode($result1[0]['transaction_numbering_system'], true);

        $existing_manual_transactiontypes = $existing_transaction_numbering_system['manual'];
        $existing_automatic_transactiontypes = $existing_transaction_numbering_system['automatic'];

        $existing_additional_transaction_prefix = $result1[0]['additional_transaction_prefix'];
        $existing_prefix_financial_bool = $result1[0]['prefix_financial_year'];
    }

    try {
        // Set the isolation level to READ COMMITTED
        $specific_db_conn->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");

        // Begin a transaction
        $specific_db_conn->beginTransaction();

        foreach ($transactiontypes_array_settings as $transactiontype) {
            if (!in_array($transactiontype, [...$manual_transactiontypes, ...$automatic_transactiontypes])) {
                errorreturn('Transaction could not be identified.');
            }
        }

        foreach ($transactiontypes_array_settings as $transactiontype) {
            if (in_array($transactiontype, $manual_transactiontypes)) {
                if (in_array($transactiontype, $existing_automatic_transactiontypes)) {
                    try {
                        // earlier it was automatic
                        // make transactions and store it thereby
                        if (!empty($additional_transaction_prefix)) {
                            if ($existing_prefix_financial_bool == 1) {
                                $sql = "UPDATE act_transactiondata SET unique_id = CONCAT('$existing_additional_transaction_prefix', financial_year, '/', unique_id, '', transaction_type_suffix), financial_year = ?, transaction_type_suffix = ? WHERE workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and transactiontype = ?";
                            } else {
                                $sql = "UPDATE act_transactiondata SET unique_id = CONCAT('$existing_additional_transaction_prefix', '/', unique_id, '', transaction_type_suffix), financial_year = ?, transaction_type_suffix = ? WHERE workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and transactiontype = ?";
                            }
                        } else {
                            if ($existing_prefix_financial_bool == 1) {
                                $sql = "UPDATE act_transactiondata SET unique_id = CONCAT(financial_year, '/', unique_id, '', transaction_type_suffix), financial_year = ?, transaction_type_suffix = ? WHERE workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and transactiontype = ?";
                            } else {
                                $sql = "UPDATE act_transactiondata SET unique_id = CONCAT(unique_id, '', transaction_type_suffix), financial_year = ?, transaction_type_suffix = ? WHERE workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and transactiontype = ?";
                            }
                        }
                        $update_transaction_uniqueid = $specific_db_conn->prepare($sql);
                        $update_transaction_uniqueid->execute(array(null, null, $workspace_id, $company_id, $branch_id, $book_id, $transactiontype));
                    } catch (Exception $e) {
                        errorreturn('Here');
                    }
                }
            } else  if (in_array($transactiontype, $automatic_transactiontypes)) {
                if (in_array($transactiontype, $existing_automatic_transactiontypes)) {
                    if ($prefix_financial_year != $existing_prefix_financial_bool) {
                        if ($prefix_financial_year == 0) {
                            // set all financial year transactions to null
                            $sql = "UPDATE act_transactiondata SET financial_year = ? WHERE workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and transactiontype = ?";
                            $update_transaction_uniqueid = $specific_db_conn->prepare($sql);
                            $update_transaction_uniqueid->execute(array(null, $workspace_id, $company_id, $branch_id, $book_id, $transactiontype));

                            // this also means we need to renumber unique_ids
                            if (!renumberAutomaticTransaction($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $transactiontype)) {
                                $specific_db_conn->rollBack();
                                errorreturn('Error in updating transaction settings.');
                            }
                        } else {
                            // set financial year for all transactions
                            if (!updateFinancialYearTransactions($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $transactiontype)) {
                                $specific_db_conn->rollBack();
                                errorreturn('Error in updating transaction settings.');
                            }

                            if (!renumberAutomaticTransaction($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $transactiontype)) {
                                $specific_db_conn->rollBack();
                                errorreturn('Error in updating transaction settings.');
                            }
                        }
                    }
                } else {
                    // change from manual to automatic
                    // FINANCIAL YEAR, TRANSACTION TYPE SUFFIX, RENUMBER
                    // set financial year for all transactions
                    if ($prefix_financial_year == 1) {
                        if (!updateFinancialYearTransactions($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $transactiontype)) {
                            $specific_db_conn->rollBack();
                            errorreturn('Error in updating transaction settings 1.');
                        }
                    }

                    $sql = "UPDATE act_transactiondata set transaction_type_suffix = ? where transactiontype = ? and  workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and transactiontype = ?";
                    $update_transactiontype_suffix = $specific_db_conn->prepare($sql);
                    $transaction_type_suffix = extractFirstWords($transactiontype);
                    $update_transactiontype_suffix->execute(array($transaction_type_suffix, $transactiontype, $workspace_id, $company_id, $branch_id, $book_id, $transactiontype));


                    if (!renumberAutomaticTransaction($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $transactiontype)) {
                        $specific_db_conn->rollBack();
                        errorreturn('Error in updating transaction settings.');
                    }
                }
            }
        }


        $sql = "UPDATE act_book_settings SET transaction_numbering_system = ?,prefix_financial_year = ?, additional_transaction_prefix = ? WHERE id = ? and workspace_id = ? and company_id = ? and branch_id = ? and book_id = ?";
        $array_params = [
            json_encode(array("manual" => $manual_transactiontypes, "automatic" => $automatic_transactiontypes)), $prefix_financial_year, $additional_transaction_prefix, $setting_id, $workspace_id, $company_id, $branch_id, $book_id
        ];

        $update = $specific_db_conn->prepare($sql);
        $update->execute($array_params);

        $specific_db_conn->commit();
        successreturn("Book transaction settings updated successfully");
    } catch (PDOException $e) {
        $specific_db_conn->rollBack();
        errorreturn($e->getMessage());
    }
}
