<?php

namespace Sibs2;

defined('ABSPATH') || exit;

class sibsGeneralModels
{
    /**
     * Get Registered Payment Detail.
     *
     * @param string $payment_group payment group.
     * @param array  $credentials credentials.
     * @return array
     */
    public static function sibs_get_db_registered_payment($payment_group, $credentials)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_payment_information";
        $query       = "SELECT * FROM `$tableName`
      WHERE `cust_id` = %d
        AND `payment_group` = %s
        AND `server_mode` = %s
        AND `channel_id` = %s
      ORDER BY id";
        $query_prepare = $wpdb->prepare(
            $query,
            get_current_user_id(),
            $payment_group,
            sibsConfig::getEnvironment(),
            $credentials['channel_id']
        );
        $registered_payments = $wpdb->get_results($query_prepare, ARRAY_A);

        return $registered_payments;
    }

    /**
     * Get Registered Payment by Registration Id.
     *
     * @param string $reg_id registration id.
     * @return array
     */
    public static function sibs_get_db_registered_payment_by_regid($reg_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_payment_information";
        $query       = "SELECT * FROM `$tableName`
      WHERE `reg_id` = %s";
        $query_prepare      = $wpdb->prepare($query, $reg_id);
        $registered_payment = $wpdb->get_row($query_prepare, ARRAY_A);

        return $registered_payment;
    }

    /**
     * Get Registration Id.
     *
     * @param int $recurring_id recurring id.
     * @return string
     */
    public static function sibs_get_db_registration_id($recurring_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_payment_information";
        $query       = "SELECT `reg_id` FROM `$tableName`
      WHERE `cust_id` = %s
        AND `id` = %s";
        $query_prepare = $wpdb->prepare($query, get_current_user_id(), $recurring_id);
        $result        = $wpdb->get_row($query_prepare);

        return isset($result->reg_id) ? $result->reg_id : false;
    }

    /**
     * Get Payment default.
     *
     * @param string $payment_group payment group.
     * @param array  $credentials credentials.
     * @return int
     */
    public static function sibs_get_db_payment_default($payment_group, $credentials)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_payment_information";
        $query       = "SELECT * FROM `$tableName` 
      WHERE `cust_id` = %d
        AND `payment_group` = %s
        AND `server_mode` = %s
        AND `channel_id` = %s
        AND `payment_default` = '1'";
        $query_prepare = $wpdb->prepare(
            $query,
            get_current_user_id(),
            $payment_group,
            sibsConfig::getEnvironment(),
            $credentials['channel_id']
        );
        $payment_default = $wpdb->get_results($query_prepare, ARRAY_A);

        return empty($payment_default) ? '1' : '0';
    }

    /**
     * Get order detail.
     *
     * @param int $uid uid.
     * @param int $payment_group payment_group.
     * @return array
     */
    public static function sibs_get_payment_information($uid, $payment_group)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_payment_information";
        $query       = "SELECT * FROM `$tableName`
      WHERE `cust_id` = %d
        AND `payment_group` = %s";
        $query_prepare = $wpdb->prepare($query, $uid, $payment_group);
        $payment_info  = $wpdb->get_results($query_prepare, ARRAY_A);

        return $payment_info;
    }

    /**
     * Check Registered Payment.
     *
     * @param string $registration_id registration id.
     * @return bool
     */
    public static function sibs_is_registered_payment_db($registration_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_payment_information";
        $query       = "SELECT * FROM `$tableName`
      WHERE `reg_id` = %s";
        $query_prepare      = $wpdb->prepare($query, $registration_id);
        $registered_payment = $wpdb->get_results($query_prepare, ARRAY_A);

        return empty($registered_payment) ? false : true;
    }

    /**
     * Get Transactions Log from database.
     *
     * @param int $order_id order id.
     * @return string
     */
    public static function sibs_get_db_transaction_log($order_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $query       = "SELECT * FROM `$tableName`
      WHERE `order_no` = %s";
        $query_prepare = $wpdb->prepare($query, $order_id);
        $result        = $wpdb->get_row($query_prepare, ARRAY_A);

        return $result;
    }

    /**
     * Get Transaction reference_id.
     *
     * @param id reference_id
     * @return string
     */
    public static function sibs_get_db_reference_id($reference_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $query       = "SELECT * FROM `$tableName`
      WHERE `reference_id` = %s";
        $query_prepare = $wpdb->prepare($query, $reference_id);
        $result        = $wpdb->get_row($query_prepare, ARRAY_A);

        return $result;
    }

    /**
     * Get Transactions captured_id.
     *
     * @param id captured_id
     * @return string
     */
    public static function sibs_get_db_captured_id($captured_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $query       = "SELECT * FROM `$tableName`
      WHERE `captured_id` = %s";
        $query_prepare = $wpdb->prepare($query, $captured_id);
        $result        = $wpdb->get_row($query_prepare, ARRAY_A);

        return $result;
    }

    /**
     * Get Transactions refund_id.
     *
     * @param id refunded_id
     * @return string
     */
    public static function sibs_get_db_refunded_id($refunded_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $query       = "SELECT * FROM `$tableName`
      WHERE `refunded_id` = %s";
        $query_prepare = $wpdb->prepare($query, $refunded_id);
        $result        = $wpdb->get_row($query_prepare, ARRAY_A);

        return $result;
    }

    /**
     * Get Transaction order no by reference_id.
     *
     * @param id reference_id
     * @return string
     */
    public static function sibs_get_db_order_no_by_reference_id($reference_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $query       = "SELECT `order_no` FROM `$tableName`
      WHERE `reference_id` = '$reference_id'";
        $result = $wpdb->get_var($query);

        return $result;
    }

    /**
     * Get capture information from database.
     *
     * @param int $order_id order id.
     * @return serialize array
     */
    public static function sibs_get_db_capture_information($order_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $query       = "SELECT `capture_information` FROM `$tableName`
      WHERE `order_no` = %s";
        $query_prepare = $wpdb->prepare($query, $order_id);
        $result        = $wpdb->get_row($query_prepare, ARRAY_A);

        return $result;
    }

    /**
     * Get refund information from database.
     *
     * @param int $order_id order id.
     * @return serialize array
     */
    public static function sibs_get_db_refund_information($order_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $query       = "SELECT `refund_information` FROM `$tableName`
      WHERE `order_no` = %s";
        $query_prepare = $wpdb->prepare($query, $order_id);
        $result        = $wpdb->get_row($query_prepare, ARRAY_A);

        return $result;
    }

    /**
     * Get capture status information from database.
     *
     * @param int $order_id order id.
     * @return result_status
     */
    public static function sibs_get_db_capture_status($order_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $query       = "SELECT `capture_status` FROM `$tableName`
      WHERE `order_no` = %s";
        $query_prepare = $wpdb->prepare($query, $order_id);
        $result        = $wpdb->get_row($query_prepare);

        return isset($result->capture_status) ? $result->capture_status : false;
    }

    /**
     * Get refund status information from database.
     *
     * @param int $order_id order id.
     * @return result_status
     */
    public static function sibs_get_db_refund_status($order_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $query       = "SELECT `refund_status` FROM `$tableName`
      WHERE `order_no` = %s";
        $query_prepare = $wpdb->prepare($query, $order_id);
        $result        = $wpdb->get_row($query_prepare);

        return isset($result->refund_status) ? $result->refund_status : false;
    }

    /**
     * Get refund id from database.
     *
     * @param int $order_id order id.
     * @return int $id refund id
     */
    public static function sibs_get_db_id_for_refund_operation($order_id)
    {
        global $wpdb;

        $tableName = "{$wpdb->prefix}posts";
        $query     = "SELECT `ID` FROM `$tableName`
      WHERE `post_type` = 'shop_order_refund'
        AND `post_parent` = %s";
        $query_prepare = $wpdb->prepare($query, $order_id);
        $result        = $wpdb->get_row($query_prepare, ARRAY_A);

        return $result;
    }

    /**
     * Get Last Order Id.
     *
     * @return int
     */
    public static function sibs_get_db_last_order_id()
    {
        global $wpdb;

        $tableName = "{$wpdb->prefix}posts";
        $query     = "SELECT `ID` FROM `$tableName`
      WHERE `post_author` = %d
        AND `post_status` = 'auto-draft'
      ORDER BY `ID` DESC";
        $query_prepare = $wpdb->prepare($query, get_current_user_id());
        $result        = $wpdb->get_row($query_prepare, ARRAY_A);

        return isset($result['ID']) ? $result['ID'] : false;
    }

    /**
     * Get order detail.
     *
     * @param int $order_id order id.
     * @return array
     */
    public static function sibs_get_db_order_detail($order_id)
    {
        global $wpdb;

        $tableName = "{$wpdb->prefix}postmeta";
        $query     = "SELECT * FROM `$tableName`
      WHERE `post_id` = %d AND (
        `meta_key` = '_order_total' OR
        `meta_key` = '_order_currency'
      )";
        $query_prepare = $wpdb->prepare($query, $order_id);
        $order_detail  = $wpdb->get_results($query_prepare, ARRAY_A);

        return $order_detail;
    }

    /**
     * Get order detail.
     *
     * @param int $product_id product id.
     * @return array
     */
    public static function sibs_get_db_product_detail($product_id)
    {
        global $wpdb;

        $tableName = "{$wpdb->prefix}postmeta";
        $query     = "SELECT `meta_key`, `meta_value`
      FROM `$tableName`
      WHERE `post_id` = %d";
        $query_prepare = $wpdb->prepare($query, $product_id);
        $row           = $wpdb->get_results($query_prepare, ARRAY_A);

        $product = [];
        foreach ($row as $products) {
            $product_key           = $products['meta_key'];
            $product[$product_key] = $products['meta_value'];
        }

        return $product;
    }

    /**
     * Get Comments.
     *
     * @param string $order_id order id.
     * @return array
     */
    public static function sibs_get_db_comments_by_order_id($order_id)
    {
        global $wpdb;

        $table = "{$wpdb->prefix}comments";
        $query = "SELECT *
      FROM `$table`
      WHERE `comment_post_ID` = %d
        AND `comment_type` LIKE 'order_note'
    ";
        $query_prepare = $wpdb->prepare($query, $order_id);
        $results       = $wpdb->get_results($query_prepare, ARRAY_A);

        return $results;
    }

    /**
     * Get Current User Card Tokens.
     * @return array
     */
    public static function sibs_get_current_user_card_tokens()
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_card_tokens";
        $query       = "SELECT `token_type`, `value`
      FROM `$tableName`
      WHERE `id_customer` = %s
    ";

        $query_prepare       = $wpdb->prepare($query, get_current_user_id());
        $registered_payments = $wpdb->get_results($query_prepare, ARRAY_A);

        $tokenFunction = function (array $tokenDB) {
            return [
                'tokenType' => $tokenDB['token_type'],
                'value'     => $tokenDB['value'],
            ];
        };

        return array_map($tokenFunction, $registered_payments);
    }

    /**
     * Get Unprocessed Webhook call.
     *
     * @return array
     */
    public static function sibs_get_db_unprocessed_webhook_call()
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_webhook_retry";
        $query       = "SELECT * FROM `$tableName`
      WHERE `processed_qty` <= " . sibsConstants::SIBS_WEBHOOK_RETRY_QTY .
    " AND `processed_at` IS NULL
      AND `created_at` < '" . sibsConfig::getStoreCurrentTime('Y-m-d H:i:s', strtotime('-5 minutes')) . "'";
        $query_prepare             = $wpdb->prepare($query);
        $unprocessed_webhook_calls = $wpdb->get_results($query_prepare, ARRAY_A);

        return $unprocessed_webhook_calls ?? [];
    }

    /**
     * Get Webhook call by payload.
     *
     * @param string $payload.
     * @return array
     */
    public static function sibs_get_db_webhook_call_by_payload($payload)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_webhook_retry";
        $query       = "SELECT * FROM `$tableName`
      WHERE `payload` = %s";
        $query_prepare      = $wpdb->prepare($query, $payload);
        $webhook_call       = $wpdb->get_row($query_prepare, ARRAY_A);

        return $webhook_call;
    }

    // UPDATE

    /**
     * Update Registered Payment.
     *
     * @param int   $recurring_id recurring id.
     * @param array $registered_payment registered payment.
     */
    public static function sibs_update_db_registered_payment($recurring_id, $registered_payment)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_payment_information";
        $data        = [
            'brand'           => $registered_payment['payment_brand'],
            'holder'          => $registered_payment['holder'],
            'email'           => $registered_payment['email'],
            'last4digits'     => $registered_payment['last_4_digits'],
            'expiry_month'    => $registered_payment['expiry_month'],
            'expiry_year'     => $registered_payment['expiry_year'],
            'server_mode'     => sibsConfig::getEnvironment(),
            'channel_id'      => $registered_payment['channel_id'],
            'reg_id'          => $registered_payment['registration_id'],
            'payment_default' => $registered_payment['payment_default'],
        ];
        $where       = ['id' => $recurring_id];
        $dataFormat  = ['%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'];
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update Default Payment.
     *
     * @param array  $query query.
     * @param string $payment_group payment group.
     * @param array  $credentials credentials.
     */
    public static function sibs_update_db_default_payment($query, $payment_group, $credentials)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_payment_information";
        $data        = ['payment_default' => $query['payment_default']];
        $where       = [
            $query['field'] => $query['value'],
            'cust_id'       => get_current_user_id(),
            'payment_group' => $payment_group,
            'server_mode'   => sibsConfig::getEnvironment(),
            'channel_id'    => $credentials['channel_id'],
        ];
        $dataFormat  = ['%d'];
        $whereFormat = ['%d', '%d', '%s', '%s'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update capture status.
     *
     * @param int    $order_id
     * @param string $capture_status
     */
    public static function sibs_update_capture_status($order_id, $capture_status)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $data        = ['capture_status' => $capture_status];
        $where       = ['order_no' => $order_id];
        $dataFormat  = ['%s'];
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update refund status.
     *
     * @param int    $order_id
     * @param string $refund_status
     */
    public static function sibs_update_refund_status($order_id, $refund_status)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $data        = ['refund_status' => $refund_status];
        $where       = ['order_no' => $order_id];
        $dataFormat  = ['%s'];
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update capture amount.
     *
     * @param int    $order_id
     * @param float  $amount
     */
    public static function sibs_update_db_capture_amount($order_id, $amount)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $data        = ['captured_amount' => $amount];
        $where       = ['order_no' => $order_id];
        $dataFormat  = ['%d'];
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update refund amount.
     *
     * @param int    $order_id
     * @param float  $amount
     */
    public static function sibs_update_db_refund_amount($order_id, $amount)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $data        = ['refunded_amount' => $amount];
        $where       = ['order_no' => $order_id];
        $dataFormat  = ['%d'];
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update Payment Status at Transactions Log.
     *
     * @param int    $order_id order id.
     * @param array  $data payment status.
     */
    public static function sibs_update_db_transaction($order_id, $data)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $where       = ['order_no' => $order_id];
        $dataFormat  = null;
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update Payment Status at Transactions Log.
     *
     * @param int    $order_id order id.
     * @param array  $data payment status.
     */
    public static function sibs_update_db_transaction_by_reference_id($reference_id, $data)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $where       = ['reference_id' => $reference_id];
        $dataFormat  = null;
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update Payment Status at Transactions Log.
     *
     * @param int    $order_id order id.
     * @param string $payment_status payment status.
     */
    public static function sibs_update_db_transaction_log_status($order_id, $payment_status)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $data        = ['payment_status' => $payment_status];
        $where       = ['order_no' => $order_id];
        $dataFormat  = ['%s'];
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update Order Payment Status and Reference Id on Backoffice Operation responses.
     *
     * @param int    $order_id order id.
     * @param string $payment_status payment status.
     * @param string $reference_id new reference identifier.
     */
    public static function sibs_update_db_transaction_log_status_and_reference_id($order_id, $payment_status, $reference_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $data        = [
            'payment_status' => $payment_status,
            'reference_id'   => $reference_id,
        ];
        $where       = ['order_no' => $order_id];
        $dataFormat  = ['%s', '%d'];
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update Reference Id on Refund Backoffice Operation responses.
     *
     * @param int    $order_id order id.
     * @param string $reference_id new reference identifier.
     */
    public static function sibs_update_db_transaction_log_reference_id($order_id, $reference_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $data        = ['refunded_id' => $reference_id];
        $where       = ['order_no' => $order_id];
        $dataFormat  = ['%s'];
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update addicional information with refund items on Capture Backoffice Operation responses.
     *
     * @param int    $order_id order id.
     * @param string $refund_items captured items
     */
    public static function sibs_update_db_transaction_log_capture_information($order_id, $capture_items)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $data        = ['capture_information' => $capture_items];
        $where       = ['order_no' => $order_id];
        $dataFormat  = ['%s'];
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update addicional information with refund items on Refund Backoffice Operation responses.
     *
     * @param int    $order_id order id.
     * @param string $refund_items refunded items
     */
    public static function sibs_update_db_transaction_log_refund_information($order_id, $refund_items)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_transaction";
        $data        = ['refund_information' => $refund_items];
        $where       = ['order_no' => $order_id];
        $dataFormat  = ['%s'];
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update Payment Status at database wp_post
     * Update wp_post post_status if change payment status at backend.
     *
     * @param int    $order_id order id.
     * @param string $payment_status payment status.
     */
    public static function sibs_update_db_posts_status($order_id, $payment_status)
    {
        global $wpdb;

        $tableName   = "{$wpdb->prefix}posts";
        $data        = ['post_status' => $payment_status];
        $where       = ['ID' => $order_id];
        $dataFormat  = ['%s'];
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update capture amount.
     *
     * @param int    $post_id
     * @param string $meta_key
     * @param string $meta_value
     */
    public static function sibs_update_db_postmeta($post_id, $meta_key, $meta_value)
    {
        global $wpdb;

        $tableName = "{$wpdb->prefix}postmeta";
        $data      = ['meta_value' => $meta_value];
        $where     = [
            'post_id'  => $post_id,
            'meta_key' => $meta_key,
        ];
        $dataFormat  = ['%s'];
        $whereFormat = ['%d', '%s'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    /**
     * Update Webhook Calls.
     *
     * @param int $webhook_id.
     * @param array $webhook.
     */
    public static function sibs_update_db_webhook_calls($webhook_id, $webhook)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_webhook_retry";

        $data        = [];
        $dataFormat  = [];

        if (isset($webhook['notification_id'])) {
            $data['notification_id'] = $webhook['notification_id'];
            $dataFormat[]            = '%s';
        }

        if (isset($webhook['decoded_payload'])) {
            $data['decoded_payload'] = json_encode($webhook['decoded_payload']);
            $dataFormat[]            = '%s';
        }

        if (isset($webhook['exception'])) {
            $data['exception'] = $webhook['exception'];
            $dataFormat[]      = '%s';
        }

        if (isset($webhook['arrived'])) {
            $data['arrived'] = $webhook['arrived'];
            $dataFormat[]    = '%s';
        }

        if (isset($webhook['processed_qty'])) {
            $data['processed_qty'] = $webhook['processed_qty'];
            $dataFormat[]          = '%s';
        }

        if (isset($webhook['processed_at'])) {
            $data['processed_at'] = $webhook['processed_at'];
            $dataFormat[]         = '%s';
        }

        $where       = ['id' => $webhook_id];
        $whereFormat = ['%d'];

        return $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );
    }

    // SAVE

    /**
     * Save Registered Payment.
     *
     * @param array $registered_payment registered payment.
     */
    public static function sibs_save_db_registered_payment($registered_payment)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_payment_information";
        $data        = [
            'cust_id'         => get_current_user_id(),
            'payment_group'   => $registered_payment['payment_group'],
            'brand'           => $registered_payment['payment_brand'],
            'holder'          => $registered_payment['holder'],
            'email'           => $registered_payment['email'],
            'last4digits'     => $registered_payment['last_4_digits'],
            'expiry_month'    => $registered_payment['expiry_month'],
            'expiry_year'     => $registered_payment['expiry_year'],
            'server_mode'     => sibsConfig::getEnvironment(),
            'channel_id'      => $registered_payment['channel_id'],
            'reg_id'          => $registered_payment['registration_id'],
            'payment_default' => $registered_payment['payment_default'],
        ];
        $dataFormat = ['%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d'];

        return $wpdb->insert(
            $tableName,
            $data,
            $dataFormat
        );
    }

    /**
     * Save or Update Transaction Log.
     *
     * @param array  $transaction transaction.
     * @param string $additional_info additional info.
     */
    public static function sibs_create_or_update_db_transaction($transaction)
    {
        global $wpdb;

        $hasTransaction = self::sibs_get_db_transaction_log($transaction['order_no']);

        if (! $hasTransaction) {
            $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
            $tableName   = "{$tablePrefix}_transaction";
            $data        = [
                'order_no'                => $transaction['order_no'],
                'customer_id'             => $transaction['customer_id'],
                'reference_id'            => $transaction['reference_id'],
                'captured_id'             => null,
                'refunded_id'             => null,
                'payment_id'              => $transaction['payment_id'],
                'payment_type'            => $transaction['payment_type'],
                'payment_brand'           => $transaction['payment_brand'],
                'payment_status'          => $transaction['payment_status'],
                'date'                    => $transaction['date'],
                'currency'                => $transaction['currency'],
                'amount'                  => $transaction['amount'],
                'additional_information'  => $transaction['additional_information'],
                'capture_status'          => null,
                'captured_amount'         => 0.0,
                'capture_information'     => null,
                'refund_status'           => null,
                'refunded_amount'         => 0.0,
                'refund_information'      => null,
            ];

            $dataFormat = [
                '%d', '%d', '%s', '%s', '%s',
                '%s', '%s', '%s', '%s', '%s',
                '%s', '%s', '%s', '%s', '%s',
                '%s', '%s', '%s', '%s',
            ];

            if (! empty($transaction['formConfig'])) {
                $data['formConfig'] = $transaction['formConfig'];
                $dataFormat[]       = '%s';
            }

            if (! empty($transaction['signature'])) {
                $data['signature'] = $transaction['signature'];
                $dataFormat[]      = '%s';
            }

            if (! empty($transaction['spg_style'])) {
                $data['spg_style'] = $transaction['spg_style'];
                $dataFormat[]      = '%s';
            }

            if (! empty($transaction['formContext'])) {
                $data['formContext'] = $transaction['formContext'];
                $dataFormat[]        = '%s';
            }

            return $wpdb->insert(
                $tableName,
                $data,
                $dataFormat
            );
        } else {
            return self::sibs_update_db_transaction($transaction['order_no'], $transaction);
        }
    }

    /**
     * Save Order Notes
     * save order notes ( database : wp_comment ) if change payment status at backend.
     *
     * @param array $comments commments.
     */
    public static function sibs_save_db_order_notes($comments)
    {
        global $wpdb;

        $tableName = "{$wpdb->prefix}comments";
        $data      = [
            'comment_post_ID'      => $comments['order_id'],
            'comment_author'       => $comments['author'],
            'comment_author_email' => $comments['email'],
            'comment_date'         => sibsConfig::getStoreCurrentTime(),
            'comment_date_gmt'     => sibsConfig::getStoreCurrentTime('Y-m-d H:i:s', false, true),
            'comment_content'      => $comments['content'],
            'comment_approved'     => '1',
            'comment_agent'        => 'WooCommerce',
            'comment_type'         => 'order_note',
        ];
        $dataFormat = ['%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'];

        return $wpdb->insert(
            $tableName,
            $data,
            $dataFormat
        );
    }

    /**
     * Save Webhook Calls
     * save webhook calls when recieve a new webhook.
     *
     * @param array $webhook.
     */
    public static function sibs_save_db_webhook_calls($webhook)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_webhook_retry";
        $data        = [
            'url'        => $webhook['url'],
            'headers'    => json_encode($webhook['headers']),
            'payload'    => $webhook['payload'],
            'created_at' => sibsConfig::getStoreCurrentTime(),
        ];
        $dataFormat = ['%s', '%s', '%s', '%s'];

        $inserted = $wpdb->insert(
            $tableName,
            $data,
            $dataFormat
        );

        return $inserted ? $wpdb->insert_id : false;
    }

    // SAVE OR UPDATE

    /**
     * Save or update Token
     * save or update token ( database : wp_comment ) if change payment status at backend.
     *
     * @param array $token token.
     */
    public static function sibs_save_or_update_db_token($token)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_card_tokens";
        $data        = [
            'id_customer'            => get_current_user_id(),
            'value'                  => isset($token['value']) ? $token['value'] : '',
            'expire_date_example'    => 'PL',
        ];

        if (isset($token['tokenName'])) {
            $data['token_name'] = $token['tokenName'];
        }

        if (isset($token['tokenType'])) {
            $data['token_type'] = $token['tokenType'];
        }

        if (isset($token['maskedPAN'])) {
            $data['masked_pan'] = $token['maskedPAN'];
        }

        if (isset($token['expireDate'])) {
            $data['expire_date'] = $token['expireDate'];
        }

        $where = [
            'id_customer'    => get_current_user_id(),
            'value'          => $data['value'],
        ];
        $dataFormat  = ['%d', '%s', '%s', '%s', '%s', '%s', '%s'];
        $whereFormat = ['%s'];

        $result = $wpdb->update(
            $tableName,
            $data,
            $where,
            $dataFormat,
            $whereFormat
        );

        if ($result === false || $result < 1) {
            return $wpdb->insert($tableName, $data, $dataFormat);
        }

        return $result;
    }

    // DELETE

    /**
     * Delete Registered Payment.
     *
     * @param int $recurring_id recurring id.
     */
    public static function sibs_delete_db_registered_payment($recurring_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_payment_information";
        $where       = ['id' => $recurring_id];
        $whereFormat = ['%d'];

        return $wpdb->delete(
            $tableName,
            $where,
            $whereFormat
        );
    }

    /**
     * Delete Registered Payment by Registration Id.
     *
     * @param string $registration_id registration id.
     */
    public static function sibs_delete_db_registered_payment_by_regid($registration_id)
    {
        global $wpdb;

        $tablePrefix = $wpdb->prefix . sibsConstants::SIBS_PLUGIN_PREFIX;
        $tableName   = "{$tablePrefix}_payment_information";
        $where       = ['reg_id' => $registration_id];
        $whereFormat = ['%s'];

        return $wpdb->delete(
            $tableName,
            $where,
            $whereFormat
        );
    }
}
