<?php

/**
 * Sibs Plugin Installation process.
 *
 * This file is used for creating tables while installing the plugins.
 * Copyright (c) SIBS
 *
 * @located at  /
 */
require_once plugin_dir_path(__FILE__) . '/vendor/autoload.php';

if (! defined('ABSPATH')) {
    exit; // Prevent direct access
}

/**
 * Activation process.
 */
function sibs_activation_process()
{
    create_sibs_table();
}

/**
 * Uninstallation process.
 */
function sibs_deactivation_process()
{
}

/**
 * Uninstallation process.
 */
function sibs_uninstallation_process()
{
    delete_sibs_options();
}

/**
 * Creates Sibs tables while activating the plugins
 * Calls from the hook "register_activation_hook".
 */
function create_sibs_table()
{
    global $wpdb;

    $prefix          = $wpdb->prefix;
    $charset_collate = $wpdb->get_charset_collate();
    $wpdb->hide_errors();

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    $sibs_db_version = get_option(Sibs2\sibsConstants::SIBS_PLUGIN_PREFIX . '_db_version');

    if (empty($sibs_db_version) || $sibs_db_version !== SIBS_VERSION) {
        createSibsTransactionTable($prefix, $charset_collate);
        createSibsRecurringTable($prefix, $charset_collate);
        createSibsTokenizationTable($prefix, $charset_collate);

        if (empty($sibs_db_version)) {
            add_option(Sibs2\sibsConstants::SIBS_PLUGIN_PREFIX . '_db_version', SIBS_VERSION);
        } elseif ($sibs_db_version !== SIBS_VERSION) {
            update_option(Sibs2\sibsConstants::SIBS_PLUGIN_PREFIX . '_db_version', SIBS_VERSION);
        }
    }

    $table_name  = $wpdb->base_prefix . 'sibs_transaction';
    $query       = $wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table_name));

    if ($wpdb->get_var($query) == $table_name) {
        $query          = "SELECT * FROM `$table_name`";
        $results        = $wpdb->get_results($query, ARRAY_A);
        $tmp            = [];
        foreach ($results as $order) {
            $tablePrefix = $wpdb->prefix . Sibs2\sibsConstants::SIBS_PLUGIN_PREFIX;
            $tableName   = "{$tablePrefix}_transaction";
            $import      = migrateInsert($tableName, $order['order_no'], $order);
            $tmp[]       = $import;
        }
    }

    $table_name = $wpdb->base_prefix . 'sibs_payment_information';
    $query      = $wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table_name));

    if ($wpdb->get_var($query) == $table_name) {
        $query   = "SELECT * FROM `$table_name`";
        $results = $wpdb->get_results($query, ARRAY_A);
        $tmp     = [];
    }
}

/**
 * Deletes Sibs settings values from wp_options tables
 * Calls from the hook "register_deactivation_hook".
 */
function delete_sibs_options()
{
    global $wpdb;

    $option_name        = Sibs2\sibsConstants::SIBS_PLUGIN_PREFIX;
    $delete_options_sql = "DELETE
		FROM `{$wpdb->options}`
		WHERE `option_name` LIKE '%{$option_name}%'
	";

    $wpdb->query($delete_options_sql);
}

function createSibsTransactionTable($prefix, $charset_collate)
{
    $pending_status  = Sibs2\sibsConstants::WOOCOMMERCE_ORDER_STATUS_PENDING;
    $tablePrefix     = $prefix . Sibs2\sibsConstants::SIBS_PLUGIN_PREFIX;
    $transaction_sql = "CREATE TABLE IF NOT EXISTS `{$tablePrefix}_transaction` (
		`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
		`customer_id` BIGINT(20) UNSIGNED DEFAULT NULL,
		`order_no` BIGINT(20) UNSIGNED NOT NULL,
		`reference_id` VARCHAR(32) NOT NULL,
		`captured_id` VARCHAR(100) NULL,
		`refunded_id` VARCHAR(100) NULL,
		`payment_id` VARCHAR(100) NOT NULL,
		`payment_type` VARCHAR(50) NOT NULL,
		`payment_brand` VARCHAR(100) NOT NULL,
		`payment_status` VARCHAR(30) NOT NULL DEFAULT '{$pending_status}',
		`date` DATETIME NOT NULL,
		`currency` CHAR(3) NOT NULL,
		`amount` DECIMAL(17,2) NOT NULL,
		`additional_information` LONGTEXT NULL,
		`refund_status` VARCHAR(100) NULL,
		`refunded_amount` DECIMAL(17,2) NOT NULL DEFAULT '0',
		`refund_information` LONGTEXT NULL,
		`capture_status` VARCHAR(100) NULL,
		`captured_amount` DECIMAL(17,2) NOT NULL DEFAULT '0',
		`capture_information` LONGTEXT NULL,
		`active` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1',
		PRIMARY KEY (`id`),
    UNIQUE KEY (`order_no`),
		UNIQUE KEY (`reference_id`),
		UNIQUE KEY (`captured_id`),
		UNIQUE KEY (`refunded_id`),
		KEY (`customer_id`)
	) $charset_collate;";

    dbDelta($transaction_sql);
}

function createSibsRecurringTable($prefix, $charset_collate)
{
    $tablePrefix   = $prefix . Sibs2\sibsConstants::SIBS_PLUGIN_PREFIX;
    $recurring_sql = "CREATE TABLE IF NOT EXISTS `{$tablePrefix}_payment_information` (
		`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
		`cust_id` BIGINT(20) NOT NULL,
		`reg_id` VARCHAR(32),
		`payment_group` VARCHAR(6),
		`brand` VARCHAR(100),
		`holder` VARCHAR(100) NULL DEFAULT NULL,
		`email` VARCHAR(100) NULL DEFAULT NULL,
		`last4digits` VARCHAR(4),
		`expiry_month` VARCHAR(2),
		`expiry_year` VARCHAR(4),
		`server_mode` VARCHAR(4) NOT NULL,
		`channel_id` VARCHAR(32) NOT NULL,
		`payment_default` BOOLEAN NOT NULL DEFAULT '0',
		PRIMARY KEY (`id`),
		UNIQUE KEY(`cust_id`, `last4digits`, `expiry_month`, `expiry_year`)
	) $charset_collate;";

    dbDelta($recurring_sql);
}

function createSibsTokenizationTable($prefix, $charset_collate)
{
    $tablePrefix      = $prefix . Sibs2\sibsConstants::SIBS_PLUGIN_PREFIX;
    $tokenization_sql = "CREATE TABLE IF NOT EXISTS `{$tablePrefix}_card_tokens` (
		`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
		`id_customer` BIGINT(20) UNSIGNED NOT NULL,
		`token_name` VARCHAR(100) NOT NULL,
		`token_type` VARCHAR(32) NOT NULL,
		`value` VARCHAR(100) NOT NULL,
		`masked_pan` VARCHAR(32) NOT NULL,
		`expire_date` VARCHAR(32) NOT NULL,
		`expire_date_example` VARCHAR(6) NOT NULL,
		PRIMARY KEY (`id`),
		UNIQUE KEY(`value`)
	) $charset_collate;";

    dbDelta($tokenization_sql);
}

function migrate_payment_type($name)
{
    $tmp = [
        'PA' => 'AUTH',
        'DB' => 'PURS',
    ];

    return $tmp[$name] ?? 'AUTH';
}

function migrate_payment_status($status, $type)
{
    $tmp = ($type == 'PA') ? [
        'wc-sibs-processing'  => 'wc-authorized',
        'wc-payment-accepted' => 'wc-authorized',
        'wc-payment-captured' => 'wc-processing',
    ] : [
        'wc-sibs-processing'  => 'wc-processing',
        'wc-payment-accepted' => 'wc-processing',
        'wc-payment-captured' => 'wc-processing',
    ];

    return $tmp[$status] ?? $status;
}

function migrateInsert_payment_information($table_name, $cust_id, $data)
{
    global $wpdb;

    $query         = "SELECT * FROM `$table_name` WHERE `cust_id` = %s";
    $query_prepare = $wpdb->prepare($query, $cust_id);
    $result        = $wpdb->get_row($query_prepare, ARRAY_A);

    if ($result === null) {
        $data        = [
            'cust_id'         => $data['cust_id'],
            'payment_group'   => $data['payment_group'],
            'brand'           => $data['payment_brand'],
            'holder'          => $data['holder'],
            'email'           => $data['email'],
            'last4digits'     => $data['last_4_digits'],
            'expiry_month'    => $data['expiry_month'],
            'expiry_year'     => $data['expiry_year'],
            'server_mode'     => $data['server_mode'],
            'channel_id'      => $data['channel_id'],
            'reg_id'          => $data['registration_id'],
            'payment_default' => $data['payment_default'],
        ];
        $dataFormat = ['%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d'];

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

    return $data['cust_id'];
}

function migrateInsert($table_name, $order_id, $data)
{
    global $wpdb;

    $query         = "SELECT * FROM `$table_name` WHERE `order_no` = %s";
    $query_prepare = $wpdb->prepare($query, $order_id);
    $result        = $wpdb->get_row($query_prepare, ARRAY_A);

    if ($result === null) {
        $data        = [
            'order_no'                => $data['order_no'],
            'customer_id'             => $data['customer_id'],
            'reference_id'            => $data['reference_id'],
            'captured_id'             => $data['captured_id'] ?? null,
            'refunded_id'             => $data['refunded_id'] ?? null,
            'payment_id'              => str_replace('sibs_', 'sibs_stg_', $data['payment_id']),
            'payment_type'            => migrate_payment_type($data['payment_type']), //PA => AUTH   DB => PURS
            'payment_brand'           => $data['payment_brand'],
            'payment_status'          => migrate_payment_status($data['payment_status'], $data['payment_type']),
            'date'                    => $data['date'],
            'currency'                => $data['currency'],
            'amount'                  => $data['amount'],
            'additional_information'  => $data['additional_information'],
            'capture_status'          => $data['capture_status'] ?? null,
            'captured_amount'         => $data['captured_amount'] ?? 0.00,
            'capture_information'     => $data['capture_information'] ?? null,
            'refund_status'           => $data['refund_status'],
            'refunded_amount'         => $data['refunded_amount'],
            'refund_information'      => $data['refund_information'],
        ];
        $dataFormat = ['%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'];

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

    return $data['order_no'];
}
