<?php

/**
 * Plugin Name: CartNinja Recovery for WooCommerce
 * Description: Recover abandoned WooCommerce carts with email, SMS, and automated reminder workflows.
 * Version: 1.1.1
 * Author: Krishna Gajera
 * Author URI: https://profiles.wordpress.org/krishnagajera/
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: cartninja-recovery-for-woocommerce
 * Domain Path: /languages
 * Requires at least: 6.0
 * Requires PHP: 7.4
 * Requires Plugins: woocommerce
 * WC requires at least: 7.0
 * WC tested up to: 9.0
 *
 *
 * @package CartNinjaRecovery
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
if ( function_exists( 'cartninja_fs' ) ) {
    if ( is_admin() && file_exists( __DIR__ . '/pro' ) ) {
        $free_plugin = 'cartninja-recovery-for-woocommerce/cartninja-recovery-for-woocommerce.php';
        if ( !function_exists( 'is_plugin_active' ) || !function_exists( 'deactivate_plugins' ) ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        if ( function_exists( 'is_plugin_active' ) && is_plugin_active( $free_plugin ) ) {
            deactivate_plugins( $free_plugin, true );
        }
    }
    $cartninja_existing_fs = cartninja_fs();
    if ( is_object( $cartninja_existing_fs ) && method_exists( $cartninja_existing_fs, 'set_basename' ) ) {
        $cartninja_existing_fs->set_basename( true, __FILE__ );
    }
    return;
}
define( 'CARTNINJA_VERSION', '1.1.1' );
define( 'CARTNINJA_PLUGIN_FILE', __FILE__ );
define( 'CARTNINJA_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'CARTNINJA_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'CARTNINJA_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
if ( function_exists( 'cartninja_fs' ) ) {
    cartninja_fs()->set_basename( false, __FILE__ );
} else {
    require_once CARTNINJA_PLUGIN_DIR . 'includes/class-cartninja-loader.php';
    require_once CARTNINJA_PLUGIN_DIR . 'includes/class-cartninja-activator.php';
    require_once CARTNINJA_PLUGIN_DIR . 'includes/class-cartninja-deactivator.php';
    require_once CARTNINJA_PLUGIN_DIR . 'includes/class-cartninja-i18n.php';
    if ( file_exists( CARTNINJA_PLUGIN_DIR . 'includes/class-cartninja-license.php' ) ) {
        require_once CARTNINJA_PLUGIN_DIR . 'includes/class-cartninja-license.php';
    }
    require_once CARTNINJA_PLUGIN_DIR . 'includes/cart/class-cartninja-cart-session.php';
    require_once CARTNINJA_PLUGIN_DIR . 'includes/cart/class-cartninja-cart-tracker.php';
    require_once CARTNINJA_PLUGIN_DIR . 'includes/cart/class-cartninja-cart-recovery.php';
    require_once CARTNINJA_PLUGIN_DIR . 'includes/notifications/class-cartninja-notification-manager.php';
    require_once CARTNINJA_PLUGIN_DIR . 'includes/notifications/class-cartninja-sms-sender.php';
    require_once CARTNINJA_PLUGIN_DIR . 'includes/notifications/class-cartninja-email-sender.php';
    require_once CARTNINJA_PLUGIN_DIR . 'includes/gateways/class-cartninja-twilio-gateway.php';
    require_once CARTNINJA_PLUGIN_DIR . 'includes/scheduler/class-cartninja-scheduler.php';
    require_once CARTNINJA_PLUGIN_DIR . 'includes/privacy/class-cartninja-privacy.php';
    require_once CARTNINJA_PLUGIN_DIR . 'admin/class-cartninja-admin.php';
    require_once CARTNINJA_PLUGIN_DIR . 'public/class-cartninja-public.php';
    add_action( 'plugins_loaded', array('CARTNINJA_Activator', 'maybe_upgrade') );
    register_activation_hook( __FILE__, array('CARTNINJA_Activator', 'activate') );
    register_deactivation_hook( __FILE__, array('CARTNINJA_Deactivator', 'deactivate') );
    function cartninja_fs_uninstall_cleanup() {
        global $wpdb;
        $tables = array($wpdb->prefix . 'cartninja_notifications', $wpdb->prefix . 'cartninja_carts');
        if ( cartninja_is_premium_build() ) {
            $tables[] = $wpdb->prefix . 'cartninja_sequences';
            $tables[] = $wpdb->prefix . 'cartninja_sequence_steps';
            $tables[] = $wpdb->prefix . 'cartninja_cart_sequence_progress';
        }
        foreach ( $tables as $table ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->query( "DROP TABLE IF EXISTS {$table}" );
        }
        $coupon_ids = $wpdb->get_col( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s", '_cartninja_cart_id' ) );
        foreach ( $coupon_ids as $coupon_id ) {
            wp_delete_post( absint( $coupon_id ), true );
        }
        if ( function_exists( 'as_unschedule_all_actions' ) ) {
            as_unschedule_all_actions( 'cartninja_mark_cart_abandoned' );
            as_unschedule_all_actions( 'cartninja_send_cart_notification' );
            as_unschedule_all_actions( 'cartninja_run_sequence_step' );
        }
        wp_clear_scheduled_hook( 'cartninja_mark_cart_abandoned' );
        wp_clear_scheduled_hook( 'cartninja_send_cart_notification' );
        wp_clear_scheduled_hook( 'cartninja_run_sequence_step' );
        wp_clear_scheduled_hook( 'cartninja_cleanup_tracking_data' );
        delete_option( 'cartninja_settings' );
        delete_option( 'cartninja_db_version' );
        delete_option( 'cartninja_suppression_stats' );
    }

    final class CARTNINJA_Plugin {
        private $loader;

        private $scheduler;

        private $notification_manager;

        private $cart_tracker;

        private $cart_recovery;

        private $privacy;

        private $admin;

        private $public;

        private $sequence_runner;

        private $sequence_builder;

        private $exit_intent;

        public function __construct() {
            $this->loader = new CARTNINJA_Loader();
            $this->scheduler = new CARTNINJA_Scheduler();
            $this->load_pro_placeholders();
            $gateway = new CARTNINJA_Twilio_Gateway();
            if ( cartninja_is_premium_unlocked() ) {
                if ( class_exists( 'CARTNINJA_Gateway_Factory' ) ) {
                    $gateway = CARTNINJA_Gateway_Factory::make();
                }
            }
            $sms_sender = new CARTNINJA_SMS_Sender($gateway);
            $email_sender = new CARTNINJA_Email_Sender();
            $this->notification_manager = new CARTNINJA_Notification_Manager($sms_sender, $email_sender, $this->scheduler);
            $session = new CARTNINJA_Cart_Session();
            $this->cart_tracker = new CARTNINJA_Cart_Tracker($session, $this->scheduler, $this->notification_manager);
            $this->cart_recovery = new CARTNINJA_Cart_Recovery();
            $this->privacy = new CARTNINJA_Privacy();
            $this->admin = new CARTNINJA_Admin($this->notification_manager, $this->cart_tracker);
            $this->public = new CARTNINJA_Public();
            $this->sequence_runner = null;
            $this->sequence_builder = null;
            $this->exit_intent = null;
            if ( cartninja_is_premium_build() ) {
                $this->sequence_runner = ( class_exists( 'CARTNINJA_Sequence_Runner' ) ? new CARTNINJA_Sequence_Runner() : null );
                $this->sequence_builder = ( class_exists( 'CARTNINJA_Sequence_Builder' ) ? new CARTNINJA_Sequence_Builder() : null );
                $this->exit_intent = ( class_exists( 'CARTNINJA_Exit_Intent' ) ? new CARTNINJA_Exit_Intent() : null );
            }
            $this->define_i18n_hooks();
            $this->define_admin_hooks();
            $this->define_public_hooks();
            $this->define_cart_hooks();
            $this->define_scheduler_hooks();
            $this->define_core_hooks();
        }

        public function run() {
            $this->loader->run();
        }

        private function load_pro_placeholders() {
            if ( cartninja_is_premium_build() ) {
                cartninja_load_vendor_autoload();
                $pro_files = array(CARTNINJA_PLUGIN_DIR . 'pro/class-cartninja-pro-loader.php');
                foreach ( $pro_files as $pro_file ) {
                    if ( file_exists( $pro_file ) ) {
                        include_once $pro_file;
                    }
                }
            }
        }

        private function define_i18n_hooks() {
            $i18n = new CARTNINJA_I18n();
            $this->loader->add_action( 'plugins_loaded', $i18n, 'load_plugin_textdomain' );
        }

        private function define_admin_hooks() {
            $this->loader->add_action( 'admin_menu', $this->admin, 'register_menu' );
            $this->loader->add_action( 'admin_init', $this->admin, 'register_settings' );
            $this->loader->add_action( 'admin_notices', $this->admin, 'maybe_show_woocommerce_notice' );
            $this->loader->add_action( 'admin_enqueue_scripts', $this->admin, 'enqueue_assets' );
            $this->loader->add_filter( 'plugin_action_links_' . CARTNINJA_PLUGIN_BASENAME, $this->admin, 'add_plugin_action_links' );
            $this->loader->add_filter(
                'plugin_row_meta',
                $this->admin,
                'add_plugin_row_meta',
                10,
                4
            );
            $this->loader->add_filter(
                'plugin_auto_update_setting_html',
                $this->admin,
                'add_plugin_auto_update_setting',
                10,
                3
            );
            $this->loader->add_action( 'wp_ajax_cartninja_send_test_sms', $this->admin, 'ajax_send_test_sms' );
            $this->loader->add_action( 'wp_ajax_cartninja_send_test_email', $this->admin, 'ajax_send_test_email' );
            $this->loader->add_action( 'wp_ajax_cartninja_get_cart_details', $this->admin, 'ajax_get_cart_details' );
            $this->loader->add_action( 'admin_post_cartninja_delete_cart', $this->admin, 'handle_delete_cart' );
            $this->loader->add_action( 'admin_post_cartninja_run_cleanup', $this->admin, 'handle_run_cleanup' );
            $this->loader->add_action( 'admin_post_cartninja_resend_notification', $this->admin, 'handle_resend_notification' );
            if ( $this->sequence_builder ) {
                $this->loader->add_action( 'wp_ajax_cartninja_save_sequence', $this->sequence_builder, 'ajax_save_sequence' );
                $this->loader->add_action( 'wp_ajax_cartninja_set_active_sequence', $this->sequence_builder, 'ajax_set_active_sequence' );
                $this->loader->add_action( 'wp_ajax_cartninja_delete_sequence', $this->sequence_builder, 'ajax_delete_sequence' );
                $this->loader->add_action( 'wp_ajax_cartninja_reorder_steps', $this->sequence_builder, 'ajax_reorder_steps' );
            }
        }

        private function define_public_hooks() {
            $this->loader->add_action( 'wp_enqueue_scripts', $this->public, 'enqueue_assets' );
            $this->loader->add_action(
                'woocommerce_review_order_before_submit',
                $this->public,
                'render_checkout_consent',
                9
            );
            $this->loader->add_action( 'wp_ajax_cartninja_capture_checkout_fields', $this->cart_tracker, 'ajax_capture_checkout_fields' );
            $this->loader->add_action( 'wp_ajax_nopriv_cartninja_capture_checkout_fields', $this->cart_tracker, 'ajax_capture_checkout_fields' );
            if ( cartninja_is_premium_unlocked() ) {
                if ( $this->exit_intent ) {
                    $this->loader->add_action( 'wp_enqueue_scripts', $this->exit_intent, 'enqueue_popup_assets' );
                }
            }
        }

        private function define_cart_hooks() {
            $this->loader->add_action( 'init', $this->cart_tracker, 'maybe_sync_overdue_carts' );
            $this->loader->add_action( 'init', $this->cart_tracker, 'maybe_schedule_cleanup' );
            $this->loader->add_action( 'woocommerce_cart_updated', $this->cart_tracker, 'track_current_cart' );
            $this->loader->add_action(
                'woocommerce_after_calculate_totals',
                $this->cart_tracker,
                'track_cart_totals',
                20,
                1
            );
            $this->loader->add_action(
                'woocommerce_checkout_order_processed',
                $this->cart_recovery,
                'mark_order_recovered',
                10,
                1
            );
            $this->loader->add_action(
                'woocommerce_thankyou',
                $this->cart_recovery,
                'mark_order_recovered',
                10,
                1
            );
            $this->loader->add_action( 'template_redirect', $this->cart_recovery, 'maybe_restore_cart_from_token' );
            if ( cartninja_is_premium_unlocked() ) {
                if ( $this->sequence_runner ) {
                    $this->loader->add_action(
                        'woocommerce_thankyou',
                        $this->sequence_runner,
                        'stop_sequence_for_cart',
                        10,
                        1
                    );
                }
            }
        }

        private function define_scheduler_hooks() {
            $this->loader->add_action(
                'cartninja_mark_cart_abandoned',
                $this->cart_tracker,
                'mark_cart_abandoned',
                10,
                1
            );
            $this->loader->add_action(
                'cartninja_send_cart_notification',
                $this->notification_manager,
                'process_scheduled_notification',
                10,
                2
            );
            $this->loader->add_action( 'cartninja_cleanup_tracking_data', $this->cart_tracker, 'run_scheduled_cleanup' );
            if ( cartninja_is_premium_unlocked() ) {
                if ( $this->sequence_runner ) {
                    $this->loader->add_action(
                        'cartninja_run_sequence_step',
                        $this->sequence_runner,
                        'run_step',
                        10,
                        3
                    );
                }
            }
        }

        private function define_core_hooks() {
            $this->loader->add_action( 'before_woocommerce_init', $this, 'declare_woocommerce_compatibility' );
            $this->loader->add_action( 'admin_init', $this->privacy, 'add_privacy_policy_content' );
            $this->loader->add_filter( 'wp_privacy_personal_data_exporters', $this->privacy, 'register_exporter' );
            $this->loader->add_filter( 'wp_privacy_personal_data_erasers', $this->privacy, 'register_eraser' );
        }

        public function declare_woocommerce_compatibility() {
            if ( class_exists( '\\Automattic\\WooCommerce\\Utilities\\FeaturesUtil' ) ) {
                \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', CARTNINJA_PLUGIN_FILE, true );
            }
        }

    }

    if ( !function_exists( 'cartninja_fs' ) ) {
        if ( !class_exists( 'CARTNINJA_Freemius_Stub' ) ) {
            class CARTNINJA_Freemius_Stub {
                public function add_action( $hook_name, $callback ) {
                    unset($hook_name, $callback);
                }

                public function set_basename( $is_premium, $file ) {
                    unset($is_premium, $file);
                }

            }

        }
        function cartninja_fs() {
            global $cartninja_fs;
            if ( !isset( $cartninja_fs ) ) {
                $composer_autoload = CARTNINJA_PLUGIN_DIR . 'vendor/autoload.php';
                if ( !file_exists( $composer_autoload ) ) {
                    $cartninja_fs = new CARTNINJA_Freemius_Stub();
                    return $cartninja_fs;
                }
                require_once $composer_autoload;
                if ( !function_exists( 'fs_dynamic_init' ) ) {
                    $cartninja_fs = new CARTNINJA_Freemius_Stub();
                    return $cartninja_fs;
                }
                $cartninja_fs = fs_dynamic_init( array(
                    'id'               => '27914',
                    'slug'             => 'cartninja-recovery-for-woocommerce',
                    'type'             => 'plugin',
                    'public_key'       => 'pk_7ec81b19b852a83bf3ab8d9997b37',
                    'is_premium'       => false,
                    'premium_suffix'   => 'Pro',
                    'has_addons'       => false,
                    'has_paid_plans'   => true,
                    'is_org_compliant' => true,
                    'trial'            => array(
                        'days'               => 3,
                        'is_require_payment' => true,
                    ),
                    'menu'             => array(
                        'slug'       => 'cartninja-dashboard',
                        'first-path' => 'admin.php?page=cartninja-dashboard',
                        'support'    => false,
                    ),
                    'is_live'          => true,
                ) );
            }
            return $cartninja_fs;
        }

        function cartninja_is_premium_build() {
            $freemius = cartninja_fs();
            $method = 'is' . '__premium_only';
            return is_object( $freemius ) && method_exists( $freemius, $method ) && (bool) $freemius->{$method}();
        }

        function cartninja_is_premium_unlocked() {
            if ( !cartninja_is_premium_build() ) {
                return false;
            }
            $freemius = cartninja_fs();
            $method = 'can' . '_use' . '_premium' . '_code' . '__premium_only';
            return is_object( $freemius ) && method_exists( $freemius, $method ) && (bool) $freemius->{$method}();
        }

        function cartninja_vendor_dependencies_available() {
            $required_vendor_files = array(CARTNINJA_PLUGIN_DIR . 'pro/vendor/autoload.php', CARTNINJA_PLUGIN_DIR . 'pro/vendor/netflie/whatsapp-cloud-api/src/WhatsAppCloudApi.php');
            foreach ( $required_vendor_files as $required_vendor_file ) {
                if ( !file_exists( $required_vendor_file ) ) {
                    return false;
                }
            }
            return true;
        }

        function cartninja_load_vendor_autoload() {
            if ( !cartninja_vendor_dependencies_available() ) {
                return false;
            }
            require_once CARTNINJA_PLUGIN_DIR . 'pro/vendor/autoload.php';
            return true;
        }

        if ( cartninja_fs() ) {
            cartninja_fs()->add_action( 'after_uninstall', 'cartninja_fs_uninstall_cleanup' );
            do_action( 'cartninja_fs_loaded' );
        }
    }
    function cartninja_run_plugin() {
        $plugin = new CARTNINJA_Plugin();
        $plugin->run();
    }

    cartninja_run_plugin();
}