<?php

namespace Sipago\WooCommerce\SipagoCheckout\Helpers;

use Sipago\WooCommerce\SipagoCheckout\Models\Inscription;
use Sipago\WooCommerce\SipagoCheckout\Models\Transaction;

class DatabaseTableInstaller
{
    const TABLE_VERSION_OPTION_KEY = 'sipagopay_orders_table_version';
    const LATEST_TABLE_VERSION = 4;

    public static function isUpgraded(): bool
    {
        $version = (int) get_site_option(static::TABLE_VERSION_OPTION_KEY, 0);
        if ($version >= static::LATEST_TABLE_VERSION) {
            return true;
        }

        return false;
    }

    public static function install(): bool
    {
        return static::createTables();
    }

    public static function createTables(): bool
    {
        global $wpdb;
        require_once ABSPATH.'wp-admin/includes/upgrade.php';
        $charset_collate = $wpdb->get_charset_collate();


        $transactionTableName = Transaction::getTableName();

        $sql = "CREATE TABLE `{$transactionTableName}` (
            `id` bigint(20) NOT NULL AUTO_INCREMENT,
            `order_id` varchar(60) NOT NULL,
            `buy_order` varchar(60) NOT NULL,
            `child_buy_order` varchar(60),
            `commerce_code` varchar(60),
            `child_commerce_code` varchar(60),
            `amount` float(20) NOT NULL,
            `token` varchar(100),
            `sipago_status` varchar(100),
            `session_id` varchar(100),
            `status` varchar(50) NOT NULL,
            `sipago_response` LONGTEXT,
            `product` varchar(30),
            `environment` varchar(20),
            `created_at` TIMESTAMP NOT NULL  DEFAULT NOW(),
            PRIMARY KEY (id)
        ) $charset_collate";

//  `amount` bigint(20) NOT NULL,
        dbDelta($sql);
  
        $inscriptionsTableName = Inscription::getTableName();
        $sql = "CREATE TABLE `{$inscriptionsTableName}` (
            `id` bigint(20) NOT NULL AUTO_INCREMENT,
            `token` varchar(100) NOT NULL,
            `username` varchar(100),
            `email` varchar(50) NOT NULL,
            `user_id` bigint(20),
            `token_id` bigint(20),
            `order_id` bigint(20),
            `pay_after_inscription` TINYINT(1) DEFAULT 0,
            `finished` TINYINT(1) NOT NULL DEFAULT 0,
            `response_code` varchar(50),
            `authorization_code` varchar(50),
            `card_type` varchar(50),
            `card_number` varchar(50),
            `from` varchar(50),
            `status` varchar(50) NOT NULL,
            `environment` varchar(20),
            `commerce_code` varchar(60),
            `sipago_response` LONGTEXT,
            `created_at` TIMESTAMP NOT NULL  DEFAULT NOW(),
            PRIMARY KEY (id)
        ) $charset_collate";

        dbDelta($sql);

        $success = empty($wpdb->last_error);
        if ($success) {
            update_site_option(static::TABLE_VERSION_OPTION_KEY, static::LATEST_TABLE_VERSION);
        } else {
            $log = new LogHandler();
            $log->logError('Error creating sipago tables');
            $log->logError($wpdb->last_error);

            add_settings_error('sipago_pay_orders_table_error', '', 'Sipago: Error creando tabla sipagopay_orders: '.$wpdb->last_error, 'error');
            settings_errors('sipago_pay_orders_table_error');
        }

        return $success;
    }

    public static function deleteTable()
    {
        global $wpdb;
        $table_name = Transaction::getTableName();
        $sql = "DROP TABLE IF EXISTS `$table_name`";
        $wpdb->query($sql);
        delete_option(static::TABLE_VERSION_OPTION_KEY);
    }

    public static function createTableIfNeeded()
    {
        if (!static::isUpgraded()) {
            return static::install();
        }

        return null;
    }
}
