<?php
/**
 * Plugin Name:       Order Flow
 * Plugin URI:        https://xionweb.xyz/
 * Description:       Streamline your WooCommerce orders – capture abandoned checkouts, block fake or duplicate orders, validate customer data, and send accurate server-side events to Facebook Pixel for better ad performance.
 * Version:           1.9.0
 * Author:            Xionweb
 * Author URI:        https://xionweb.com/
 * License:           GPL v2 or later
 * Text Domain:       orderflow
 * Domain Path:       /languages/
 * Requires at least: 5.8
 * Requires PHP:      7.4
 */


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


// Check if WooCommerce is active
if ( ! in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    // Add admin notice if WooCommerce is not active
    add_action( 'admin_notices', 'orderflow_woocommerce_missing_notice' );
    return; // Stop plugin initialization
}

/**
 * Display admin notice when WooCommerce is not active
 */
function orderflow_woocommerce_missing_notice() {
    ?>
    <div class="error">
        <p><?php
            printf(
                __( 'Order Flow requires WooCommerce to be installed and active. You can download %s here.', 'orderflow' ),
                '<a href="https://wordpress.org/plugins/woocommerce/" target="_blank">WooCommerce</a>'
            );
            ?></p>
    </div>
    <?php
}

if ( ! class_exists( 'orderflow' ) ) {

    final class orderflow {
        private static $rendered = false;

        /**
         * orderflow constructor.
         */
        private function __construct() {
            $this->define_constants();

            register_activation_hook( __FILE__, array( $this, 'activate' ) );
            register_deactivation_hook( __FILE__, array( $this, 'deactivate' ) );
            add_action( 'plugins_loaded', array( $this, 'init_plugin' ) );
            add_action( 'plugins_loaded', array( $this, 'load_text_domain' ) );
            //add_filter('the_content', [$this, 'override_checkout_content'], 20);
        }

        /**
         * Initializes a single instance
         */
        public static function init() {
            static $instance = false;

            if ( ! $instance ) {
                $instance = new self();
            }

            return $instance;
        }

        /**
         * Plugin text domain loaded
         */
        public function load_text_domain() {
            load_plugin_textdomain( 'orderflow', false, ADS_PLUGIN_PATH . 'languages/' );
        }

        /**
         * Define plugin path and url constants
         */
        public function define_constants() {

            define( 'ADS_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
            define( 'ADS_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
            define( 'ADS_ADMIN_ASSETS_URL', plugin_dir_url( __FILE__ ) . 'assets/admin/' );
            define( 'ADS_API_URL', 'https://plugin.bappy.xyz/' );
            define( 'ADS_VERSION', '1.9.0' );
        }

        /**
         * Init plugin
         */
        public function init_plugin() {

            
            // require files or autoloader here
             require_once ADS_PLUGIN_PATH . 'autoloader.php';
             require_once ADS_PLUGIN_PATH . 'includes/functions.php';
             \orderflow\Init::setup();
        }


        public function override_checkout_content($content) {

            // only frontend
            if (is_admin()) {
                return $content;
            }

            // only checkout page
            if (!is_checkout()) {
                return $content;
            }

            // prevent infinite loop
            if (self::$rendered) {
                return $content;
            }

            self::$rendered = true;

            // ensure WooCommerce loaded
            if (!function_exists('WC')) {
                return $content;
            }

            return do_shortcode('[woocommerce_checkout]');
        }

        /***
         * Do Stuff Plugin activation
         */
        /**
         * Plugin activation handler
         * Creates required database tables and flushes rewrite rules
         */
        public function activate() {
            global $wpdb;

            // Define table names
            $customers_table = $wpdb->prefix . 'ads_customers_data';
            $orders_table = $wpdb->prefix . 'ads_incomplete_orders_tracker';

            // Get charset collation
            $charset_collate = $wpdb->get_charset_collate();

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

            // Create customers data table
            $this->create_customers_data_table($customers_table, $charset_collate);

            // Create incomplete orders tracker table
            $this->create_incomplete_orders_table($orders_table, $charset_collate);

            // Flush rewrite rules
            flush_rewrite_rules();
        }

        /**
         * Plugin deactivation handler
         */
        public function deactivate() {
            // Clear any transients if needed
            delete_transient('orderflow_license_last_sync');
        }

        /**
         * Creates the customers data table
         *
         * @param string $table_name Table name
         * @param string $charset_collate Charset collation
         */
        private function create_customers_data_table($table_name, $charset_collate) {
            global $wpdb;

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

            // Create / Sync table (NO inline PRIMARY KEY)
            $sql = "CREATE TABLE IF NOT EXISTS {$table_name} (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                data_type VARCHAR(255) NOT NULL,
                data_value VARCHAR(255) NOT NULL UNIQUE,
                data_courier_history LONGTEXT NULL,
                data_courier_history_last_update_time DATETIME NULL,
                data_access VARCHAR(255) NOT NULL DEFAULT 'allowed',
                PRIMARY KEY (id)
            ) {$charset_collate};";

            dbDelta($sql);

            // Run DB upgrades (version based)
            $installed_db_version = get_option('orderflow_db_version', '1.0.0');

            if (version_compare($installed_db_version, '1.1.0', '<')) {

                // Ensure column is LONGTEXT (safe even if already LONGTEXT)
                $wpdb->query("
                    ALTER TABLE {$table_name}
                    MODIFY data_courier_history LONGTEXT
                ");

                update_option('orderflow_db_version', '1.1.0');
            }
        }



        /**
         * Creates the incomplete orders tracker table
         *
         * @param string $table_name Table name
         * @param string $charset_collate Charset collation
         */
        private function create_incomplete_orders_table($table_name, $charset_collate) {
            $sql = "CREATE TABLE {$table_name} (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        order_id bigint(20) NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        recovered_at datetime DEFAULT NULL,
        status_from varchar(50) DEFAULT NULL,
        status_to varchar(50) DEFAULT NULL,
        order_total decimal(10,2) DEFAULT NULL,
        user_id bigint(20) DEFAULT 0,
        email varchar(255) NOT NULL,
        billing_first_name varchar(100) DEFAULT NULL,
        billing_last_name varchar(100) DEFAULT NULL,
        billing_phone varchar(20) DEFAULT NULL,
        billing_address_1 varchar(255) DEFAULT NULL,
        billing_state varchar(100) DEFAULT NULL,
        note text DEFAULT NULL,
        PRIMARY KEY (id),
        UNIQUE KEY order_id (order_id),
        KEY created_at (created_at),
        KEY recovered_at (recovered_at)
    ) {$charset_collate};";

            dbDelta($sql);
        }
    }

}

/**
 * Initializes the main plugin
 *
 * @return \orderflow
 */
function orderflow() {
    return orderflow::init();
}

/**
 * Kick off the plugin
 */
orderflow();

// add_action('init', function () {
//     wp_cache_set('test_key', 'hello', 'test_group', 3600);
//     error_log('CACHE VALUE: ' . print_r(wp_cache_get('test_key', 'test_group'), true));
// });