<?php

namespace CodeClouds\Unify\Models;

/**
 * License for pro.
 * @package CodeClouds\Unify
 */
class ProLicense
{
    protected $table_name = 'unify_options_data'; 
    protected $wpdb;
    
	public function __construct() {
        global $wpdb;
        $this->wpdb = $wpdb;
        $this->table_name = $this->wpdb->prefix . 'unify_options_data'; // Table name with prefix
    }
    
    /**
     * Static method for plugin activation
     * This should be called from register_activation_hook
     */
    public static function activate() {
        $instance = new self();
        $instance->createTable();
    }

	/**
	 * Create Table 
	 * Note: Database schema changes should only be performed during plugin activation/upgrade
	 * This method should be called from register_activation_hook or upgrade routines
	*/
    public function createTable()
	{
        $charset_collate = $this->wpdb->get_charset_collate();
        $table_name_escaped = esc_sql($this->table_name);
        $table_check_query = $this->wpdb->prepare("SHOW TABLES LIKE %s", $this->wpdb->esc_like($this->table_name));
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $table_check_query contains a properly prepared statement
        if ($this->wpdb->get_var($table_check_query) != $this->table_name ) {
            $sql = "CREATE TABLE {$table_name_escaped} (
                id mediumint(9) NOT NULL AUTO_INCREMENT,
                option_key varchar(255) NOT NULL,
                option_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 option_key (option_key)
            ) $charset_collate;";

            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange
            dbDelta($sql); // Create the table
            
            // Update cache to reflect table now exists
            wp_cache_set($table_exists_cache_key, true, 'unify_pro_license', 3600);
            return true;
        }
        return false;
	}

	public function saveData($option_key, $proLicenseFromOptionTable) {
        // Direct database call is necessary for custom table insert
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $result = $this->wpdb->insert($this->table_name, [
            'option_key' => $option_key,
            'option_value' => serialize($proLicenseFromOptionTable)
        ]);
        
        // Clear cache after insert
        $cache_key = 'unify_license_' . md5($option_key);
        wp_cache_delete($cache_key, 'unify_pro_license');
        
        return $result;
    }

    public function fetchData($option_key) {
        $table_name_escaped = esc_sql($this->table_name);
        $sql = "SELECT * FROM {$table_name_escaped} WHERE option_key = %s";
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql contains static SQL with placeholder, safe for prepare()
        $prepared_query = $this->wpdb->prepare($sql, $option_key);
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $prepared_query contains a properly prepared statement
        return $this->wpdb->get_row($prepared_query);
    }

    public function update($id, $option_key, $proLicenseFromOptionTable) {
        // Direct database call is necessary for custom table update
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $result = $this->wpdb->update($this->table_name, [
           'option_key' => $option_key,
			'option_value' => serialize($proLicenseFromOptionTable)
        ], ['id' => $id]);
        
        // Clear cache after update
        $cache_key = 'unify_license_' . md5($option_key);
        wp_cache_delete($cache_key, 'unify_pro_license');
        
        return $result;
    }

    public function delete($id) {
        // Get option_key before deletion for cache clearing
        global $wpdb;
        $cache_key_lookup = 'unify_license_lookup_' . $id;
        $option_key = wp_cache_get($cache_key_lookup, 'unify_pro_license');
        
        if (false === $option_key) {
            // Direct database call is necessary for custom table query to get option_key
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $option_key = $wpdb->get_var($wpdb->prepare("SELECT option_key FROM {$wpdb->prefix}unify_options_data WHERE id = %d", $id));
            wp_cache_set($cache_key_lookup, $option_key, 'unify_pro_license', 300); // Cache for 5 minutes
        }
        
        // Direct database call is necessary for custom table delete
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $result = $this->wpdb->delete($this->table_name, ['id' => $id]);
        
        // Clear cache after delete
        if ($option_key) {
            $cache_key = 'unify_license_' . md5($option_key);
            wp_cache_delete($cache_key, 'unify_pro_license');
            wp_cache_delete($cache_key_lookup, 'unify_pro_license');
        }
        
        return $result;
    }

    public function deleteAll($option_key) {
        $table_check_query = $this->wpdb->prepare("SHOW TABLES LIKE %s", $this->wpdb->esc_like($this->table_name));
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $table_check_query contains a properly prepared statement
        if ($this->wpdb->get_var($table_check_query) == $this->table_name) {
            $delete = $this->wpdb->delete($this->table_name, ['option_key' => $option_key]);
            return $delete;
        }
        return false;
    }
}