<?php

 /**
 * =============================================================================
 * @package			    Blue Raven (Free Version)
 * @Plugin URI			https://enterrahost.com/plugins/blue-raven
 * 
 * @Author			    EnterraHost
 * @Author URI			https://enterrahost.com
 * @License			    GPL-2.0-or-later
 *  
 * @Copyright			(c) 2025 EnterraHost
 * @File Description	Blue Raven Installer DB table creation
 * 
 * =============================================================================
 * 
 * || INDEX:
 * ||   - INSTALLER FUNCTION
 * ||   - CREATE TABLES
 * ||   - CREATE CONFIG TABLE
 * ||   - CREATE VALUES TABLE
 * ||   - CREATE PRODUCTS TABLE
 * ||   - CREATE MESSAGE TABLE
 * ||   - LOGGING TABLE
 * ||   - SEED DEFULT TABLES
 * || 
 * =============================================================================
 */

if ( ! defined( 'ABSPATH' ) ) exit;

/*
============================================================
    INSTALLER FUNCTION
============================================================
*/

class BlueRaven_Installer {
    
    /**
     * Executes the main logic or process of the class.
     * This function serves as the entry point to initiate operations.
     */
    public function run() {
        $this->create_tables();
        $this->seed_default_data();
    }
    
/*
============================================================
    CREATE TABLES
============================================================
*/
    
    /**
     * Creates the necessary database tables for the plugin/module.
     * Called during activation or initialization.
     */
    private function create_tables() {

        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

/*      
============================================================
    CREATE CONFIG TABLE
============================================================
*/

    ## ============ This table is in place to store configirations needed for the back end plugin needs, such as error_logging_email_address ============ ##
    
        $brConfig = "CREATE TABLE {$wpdb->prefix}BlueRavenConfig (
            id BIGINT(20) NOT NULL AUTO_INCREMENT,
            setting VARCHAR(255) NOT NULL,
            value LONGTEXT NOT NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY setting_key (setting)
        ) {$charset_collate};";
    
        dbDelta($brConfig);

/*      
============================================================
    CREATE VALUES TABLE
============================================================
*/

    /* ============ Store Settings ============ */ 
    
        $brValues = "CREATE TABLE {$wpdb->prefix}BlueRavenValues (
            id BIGINT(20) NOT NULL AUTO_INCREMENT,
            setting VARCHAR(255) NOT NULL,
            value LONGTEXT NOT NULL,
            enabled TINYINT(1) NOT NULL DEFAULT 0,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY setting_key (setting)
        ) {$charset_collate}";
            
        dbDelta($brValues);

/*      
============================================================
    CREATE PRODUCTS TABLE
============================================================
*/
  
    /* ============ This table is in place to save each product genersation  ============ */
    
        $products_table_version = '0.1';
        $products_table_name = $wpdb->prefix . 'BlueRavenProducts';
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $products_table_name)) == $products_table_name;
        $charset_collate = $wpdb->get_charset_collate();
        
        $productSQL = "CREATE TABLE $products_table_name (
            id BIGINT(20) NOT NULL AUTO_INCREMENT,
            woo_product_id BIGINT(20) DEFAULT NULL,
            title VARCHAR(255) DEFAULT NULL,
            slug VARCHAR(255) DEFAULT NULL,
            description LONGTEXT DEFAULT NULL,
            short_description TEXT DEFAULT NULL,
            sku VARCHAR(100) DEFAULT NULL,
            category VARCHAR(255) DEFAULT NULL,
            thumbnail VARCHAR(255) DEFAULT NULL,
            price DECIMAL(15,4) DEFAULT NULL,
            cost DECIMAL(15,4) DEFAULT NULL,
            status VARCHAR(20) NOT NULL DEFAULT 'draft',
            meta_title VARCHAR(255) DEFAULT NULL,
            meta_description TEXT DEFAULT NULL,
            meta_keywords TEXT DEFAULT NULL,
            favorite BOOLEAN DEFAULT FALSE,
            pending BOOLEAN DEFAULT FALSE,
            notification TEXT DEFAULT NULL,
            request_json LONGTEXT DEFAULT NULL,
            create_json LONGTEXT DEFAULT NULL,
            attributes_json LONGTEXT DEFAULT NULL,
            product_CSV LONGTEXT DEFAULT NULL,
            variations_CSV LONGTEXT DEFAULT NULL,
            created_at DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
            updated_at DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
            
            PRIMARY KEY (id),
            UNIQUE KEY woo_product_id (woo_product_id),
            KEY status (status),
            KEY price (price),
            KEY sku (sku),
            KEY title (title(191)),
            KEY category (category),
            KEY created_at (created_at),
            KEY updated_at (updated_at)
        ) $charset_collate;";
        
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        
        if (!$table_exists) {
            dbDelta($productSQL);
            update_option('blueraven_products_db_version', $products_table_version);
            
        } else {
            $current_version = get_option('blueraven_products_db_version');
            
            if ($current_version !== $products_table_version) {
                dbDelta($productSQL);
                update_option('blueraven_products_db_version', $products_table_version);
                error_log("Updated table $products_table_name to version $products_table_version");
            }
        }

/*      
============================================================
    CREATE MESSAGE TABLE
============================================================
*/
        
    /* ============  This table is in place to save each product genersation ============ */ ###

        $messages_table_version = '0.1';
        $messages_table_name = $wpdb->prefix . 'BlueRavenMessages';
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $messages_table_name)) == $messages_table_name;
        $charset_collate = $wpdb->get_charset_collate();

        $messagesSQL = "CREATE TABLE $messages_table_name (
            id BIGINT(20) NOT NULL AUTO_INCREMENT,
            title VARCHAR(255) NOT NULL,
            shortcode VARCHAR(100) DEFAULT NULL,
            form TEXT DEFAULT NULL,
            messages TEXT DEFAULT NULL,
            bot_prevention TEXT DEFAULT NULL,
            email_to VARCHAR(255) DEFAULT NULL,
            email_from VARCHAR(255) DEFAULT NULL,
            reply_to VARCHAR(255) DEFAULT NULL,
            subject VARCHAR(255) DEFAULT NULL,
            template TEXT DEFAULT NULL,
            status VARCHAR(20) NOT NULL DEFAULT 'active',
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
            
            PRIMARY KEY (id),
            UNIQUE KEY shortcode (shortcode),
            KEY title (title(191)),
            KEY status (status),
            KEY created_at (created_at),
            KEY updated_at (updated_at)
        ) $charset_collate;";
        
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        
        if (!$table_exists) {
            dbDelta($messagesSQL);
            update_option('blueraven_messages_db_version', $messages_table_version);
            
        } else {
            $current_version = get_option('blueraven_messages_db_version');
            
            if ($current_version !== $messages_table_version) {
                dbDelta($messagesSQL);
                update_option('blueraven_messages_db_version', $messages_table_version);
                error_log("Updated table $messages_table_name to version $messages_table_version");
            }
        }

/*      
============================================================
    LOGGING TABLE
============================================================
*/
        
    /* ============  This table is in place to save errors and logs ============ */ ###


        $messages_table_version = '0.1';
        $messages_table_name    = $wpdb->prefix . 'BlueRavenLogs';
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $messages_table_name)) === $messages_table_name;
        $charset_collate = $wpdb->get_charset_collate();

        if (!$table_exists) {
            $sql = "CREATE TABLE $messages_table_name (
                id mediumint(9) NOT NULL AUTO_INCREMENT,
                type varchar(20) NOT NULL,
                file varchar(2083) NOT NULL,
                context varchar(2083) NOT NULL,
                description text NOT NULL,
                created_at datetime DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY  (id)
            ) $charset_collate;";

            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
            dbDelta($sql);
        }
    }
    
/*
============================================================
    SEED DEFULT TABLES
============================================================
*/


    /**
     * Inserts default data into the database tables after creation.
     * Useful for initializing settings, sample entries, or configuration values.
     */
    private function seed_default_data() {
        global $wpdb;
        
    ## ============ Seed BlueRavenConfig ============ ##
        
        $url = 'https://portal.enterrahost.com/terraConfigDefaults.php?fetchdefults=true';
        $response = wp_remote_get($url);
        
        ### Is there an error ?
        
        if (is_wp_error($response)) {
            BlueRaven_SendError("SUPER ERROR", "blue-raven/includes/installer.php", "Seed BlueRavenConfig", 'Failed to fetch default settings: ' . $response->get_error_message(), true);
            error_log('Failed to fetch default settings: ' . $response->get_error_message());
            return;
        }
        
        $body = wp_remote_retrieve_body($response);
        $defaultsForTerraConfig = json_decode($body, true);
        
        ### Is JSON ?
        
        if (!is_array($defaultsForTerraConfig)) {
            BlueRaven_SendError("SUPER ERROR", "blue-raven/includes/installer.php", "Seed BlueRavenConfig", 'Invalid JSON response from ' . $url, true);
            error_log('Invalid JSON response from ' . $url);
            return;
        }
        
        foreach ($defaultsForTerraConfig as $data) {
            
            ### Is valid structure ?
            
            if (!isset($data['setting'], $data['value'])) {
                BlueRaven_SendError("SUPER ERROR", "blue-raven/includes/installer.php", "Seed BlueRavenConfig", 'Invalid data structure in fetched defaults' . $url, true);
                error_log('Invalid data structure in fetched defaults');
                continue;
            }
        
            $setting = sanitize_text_field($data['setting']);
            $exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->prefix}BlueRavenConfig WHERE setting = %s", $setting));

    ## ============ Seed TerraConfig ============ ##
    
            if (!$exists) {
                $wpdb->insert(
                    "{$wpdb->prefix}BlueRavenConfig",
                    [
                        'setting'    => $setting,
                        'value'      => sanitize_text_field($data['value']),
                        'created_at' => current_time('mysql'),
                        'updated_at' => current_time('mysql')
                    ],
                    ['%s', '%s', '%s', '%s']
                );
            }
        }
    }
}

