<?php

/**
 * Plugin activation routines.
 *
 * @package CartNinjaRecovery
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class CARTNINJA_Activator {
    const DB_VERSION = '2.2.0';

    public static function activate() {
        self::create_tables();
        self::create_default_options();
    }

    public static function maybe_upgrade() {
        $current_version = get_option( 'cartninja_db_version', '0.0.0' );
        if ( version_compare( $current_version, self::DB_VERSION, '<' ) ) {
            self::create_tables();
            self::create_default_options();
            self::migrate_security_defaults( $current_version );
        }
    }

    private static function create_tables() {
        global $wpdb;
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        $charset_collate = $wpdb->get_charset_collate();
        $carts_table = $wpdb->prefix . 'cartninja_carts';
        $notifications_table = $wpdb->prefix . 'cartninja_notifications';
        $sequences_table = $wpdb->prefix . 'cartninja_sequences';
        $steps_table = $wpdb->prefix . 'cartninja_sequence_steps';
        $progress_table = $wpdb->prefix . 'cartninja_cart_sequence_progress';
        $sql_carts = "CREATE TABLE {$carts_table} (\n\t\t\tid BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t\tsession_id VARCHAR(255) NOT NULL,\n\t\t\tuser_id BIGINT UNSIGNED NULL,\n\t\t\temail VARCHAR(255) NULL,\n\t\t\tphone VARCHAR(20) NULL,\n\t\t\tcountry_code VARCHAR(5) NOT NULL DEFAULT '+91',\n\t\t\tcustomer_ip VARCHAR(45) NULL,\n\t\t\tcustomer_country_code VARCHAR(2) NULL,\n\t\t\tcustomer_country_name VARCHAR(100) NULL,\n\t\t\tcustomer_ip_hash VARCHAR(64) NULL,\n\t\t\tuser_agent_hash VARCHAR(64) NULL,\n\t\t\ttracking_status ENUM('tracked','suppressed') NOT NULL DEFAULT 'tracked',\n\t\t\tsuppression_reason VARCHAR(50) NULL,\n\t\t\tcart_contents LONGTEXT NOT NULL,\n\t\t\tcart_total DECIMAL(10,2) NOT NULL DEFAULT 0.00,\n\t\t\tcurrency VARCHAR(10) NOT NULL DEFAULT '',\n\t\t\tstatus ENUM('active','abandoned','recovering','recovered','lost') NOT NULL DEFAULT 'active',\n\t\t\trecovery_token VARCHAR(64) NOT NULL,\n\t\t\trecovery_expires_at DATETIME NULL,\n\t\t\tcontact_consent TINYINT(1) NOT NULL DEFAULT 0,\n\t\t\tconsented_at DATETIME NULL,\n\t\t\tconsent_source VARCHAR(30) NULL,\n\t\t\tcoupon_code VARCHAR(50) NULL,\n\t\t\trecovered_order_id BIGINT UNSIGNED NULL,\n\t\t\tcart_updated_at DATETIME NOT NULL,\n\t\t\tabandoned_at DATETIME NULL,\n\t\t\trecovered_at DATETIME NULL,\n\t\t\tcreated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\t\tPRIMARY KEY  (id),\n\t\t\tUNIQUE KEY session_id (session_id),\n\t\t\tUNIQUE KEY recovery_token (recovery_token),\n\t\t\tKEY status (status),\n\t\t\tKEY tracking_status (tracking_status),\n\t\t\tKEY customer_country_code (customer_country_code),\n\t\t\tKEY customer_ip_hash (customer_ip_hash),\n\t\t\tKEY recovery_expires_at (recovery_expires_at),\n\t\t\tKEY email (email(191)),\n\t\t\tKEY cart_updated_at (cart_updated_at)\n\t\t) {$charset_collate};";
        $notification_channels = "'sms','email'";
        $step_channels = "'sms','email'";
        $sql_notifications = "CREATE TABLE {$notifications_table} (\n\t\t\tid BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t\tcart_id BIGINT UNSIGNED NOT NULL,\n\t\t\tchannel ENUM({$notification_channels}) NOT NULL DEFAULT 'sms',\n\t\t\trecipient VARCHAR(255) NOT NULL,\n\t\t\tmessage_sent TEXT NOT NULL,\n\t\t\tstatus ENUM('pending','sent','failed','clicked') NOT NULL DEFAULT 'pending',\n\t\t\tgateway_message_id VARCHAR(255) NULL,\n\t\t\terror_message TEXT NULL,\n\t\t\tscheduled_at DATETIME NOT NULL,\n\t\t\tsent_at DATETIME NULL,\n\t\t\tclicked_at DATETIME NULL,\n\t\t\tPRIMARY KEY  (id),\n\t\t\tKEY cart_id (cart_id),\n\t\t\tKEY status (status),\n\t\t\tKEY scheduled_at (scheduled_at)\n\t\t) {$charset_collate};";
        $sql_sequences = "CREATE TABLE {$sequences_table} (\n\t\t\tid BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t\tname VARCHAR(255) NOT NULL,\n\t\t\tis_active TINYINT(1) NOT NULL DEFAULT 1,\n\t\t\tcreated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\t\tupdated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\t\tPRIMARY KEY (id)\n\t\t) {$charset_collate};";
        $sql_steps = "CREATE TABLE {$steps_table} (\n\t\t\tid BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t\tsequence_id BIGINT UNSIGNED NOT NULL,\n\t\t\tstep_order SMALLINT UNSIGNED NOT NULL DEFAULT 1,\n\t\t\tdelay_minutes INT UNSIGNED NOT NULL DEFAULT 60,\n\t\t\tchannel ENUM({$step_channels}) NOT NULL DEFAULT 'sms',\n\t\t\tmessage_template TEXT NOT NULL,\n\t\t\tinclude_coupon TINYINT(1) NOT NULL DEFAULT 0,\n\t\t\tcoupon_discount DECIMAL(5,2) NOT NULL DEFAULT 10.00,\n\t\t\tcoupon_type ENUM('percent','fixed_cart') NOT NULL DEFAULT 'percent',\n\t\t\tis_active TINYINT(1) NOT NULL DEFAULT 1,\n\t\t\tPRIMARY KEY (id),\n\t\t\tKEY sequence_id (sequence_id),\n\t\t\tKEY step_order (step_order)\n\t\t) {$charset_collate};";
        $sql_progress = "CREATE TABLE {$progress_table} (\n\t\t\tid BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t\tcart_id BIGINT UNSIGNED NOT NULL,\n\t\t\tsequence_id BIGINT UNSIGNED NOT NULL,\n\t\t\tcurrent_step SMALLINT UNSIGNED NOT NULL DEFAULT 0,\n\t\t\tstatus ENUM('active','completed','stopped') NOT NULL DEFAULT 'active',\n\t\t\tstarted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\t\tPRIMARY KEY (id),\n\t\t\tUNIQUE KEY cart_sequence (cart_id, sequence_id),\n\t\t\tKEY cart_id (cart_id)\n\t\t) {$charset_collate};";
        dbDelta( $sql_carts );
        dbDelta( $sql_notifications );
        dbDelta( $sql_sequences );
        dbDelta( $sql_steps );
        dbDelta( $sql_progress );
        self::migrate_legacy_cart_statuses();
        self::repair_missing_abandoned_dates();
        self::migrate_recovery_security_data();
        update_option( 'cartninja_db_version', self::DB_VERSION );
    }

    private static function create_default_options() {
        $defaults = array(
            'general'    => array(
                'abandonment_threshold'     => 15,
                'lost_threshold_days'       => 30,
                'recovery_link_expiry_days' => 30,
                'recovery_url_base'         => self::get_default_recovery_url(),
                'enable_sms'                => 'yes',
                'enable_email'              => 'yes',
            ),
            'twilio'     => array(
                'account_sid' => '',
                'auth_token'  => '',
                'from_phone'  => '',
            ),
            'message'    => array(
                'sms_template'      => __( 'Hi {{customer_name}}, you left items worth {{cart_total}} in your cart at {{site_name}}. Complete your purchase here: {{cart_url}}', 'cartninja-recovery-for-woocommerce' ),
                'email_subject'     => __( 'Complete your purchase at {{site_name}}', 'cartninja-recovery-for-woocommerce' ),
                'email_heading'     => __( 'You left something behind', 'cartninja-recovery-for-woocommerce' ),
                'email_template'    => __( "Hi {{customer_name}},\n\nYou left items worth {{cart_total}} in your cart at {{site_name}}.", 'cartninja-recovery-for-woocommerce' ),
                'email_button_text' => __( 'Resume your checkout', 'cartninja-recovery-for-woocommerce' ),
                'email_footer_text' => '',
            ),
            'protection' => array(
                'enable_guest_protection' => 'yes',
                'daily_guest_ip_limit'    => 20,
                'short_guest_ip_limit'    => 5,
                'short_window_minutes'    => 15,
                'blocked_ips'             => '',
                'country_filter_mode'     => 'block',
                'blocked_countries'       => '',
                'trust_proxy_headers'     => 'no',
            ),
            'cleanup'    => array(
                'enable_auto_cleanup'       => 'yes',
                'guest_retention_days'      => 30,
                'suppressed_retention_days' => 7,
                'terminal_retention_days'   => 90,
                'keep_order_linked_carts'   => 'no',
            ),
        );
        if ( cartninja_is_premium_build() ) {
            $defaults = wp_parse_args( $defaults, array(
                'gateway'   => array(
                    'provider' => 'twilio',
                ),
                'vonage'    => array(
                    'api_key'    => '',
                    'api_secret' => '',
                    'from'       => '',
                ),
                'sinch'     => array(
                    'service_plan_id' => '',
                    'api_token'       => '',
                    'from'            => '',
                ),
                'plivo'     => array(
                    'auth_id'    => '',
                    'auth_token' => '',
                    'from'       => '',
                ),
                'whatsapp'  => array(
                    'phone_number_id'   => '',
                    'access_token'      => '',
                    'template_name'     => 'abandoned_cart_recovery',
                    'template_language' => 'en_US',
                    'body_variables'    => array(
                        'customer_name',
                        'cart_total',
                        'site_name',
                        'cart_url'
                    ),
                    'enable_whatsapp'   => 'no',
                ),
                'sequences' => array(
                    'active_sequence_id' => 0,
                ),
                'popup'     => array(
                    'enable_popup'               => 'no',
                    'enable_add_to_cart_popup'   => 'no',
                    'headline'                   => __( 'Wait! Don\'t leave your cart behind', 'cartninja-recovery-for-woocommerce' ),
                    'subtext'                    => __( 'Enter your phone and we\'ll send you a reminder', 'cartninja-recovery-for-woocommerce' ),
                    'button_text'                => __( 'Save My Cart', 'cartninja-recovery-for-woocommerce' ),
                    'show_gdpr'                  => 'yes',
                    'gdpr_text'                  => __( 'I agree to receive cart recovery reminders about my cart', 'cartninja-recovery-for-woocommerce' ),
                    'field_message'              => __( 'We only use this to send your cart recovery reminder.', 'cartninja-recovery-for-woocommerce' ),
                    'add_to_cart_headline'       => __( 'Want to save your cart for later?', 'cartninja-recovery-for-woocommerce' ),
                    'add_to_cart_subtext'        => __( 'Enter your email address and we\'ll send you a link to your cart.', 'cartninja-recovery-for-woocommerce' ),
                    'add_to_cart_button_text'    => __( 'Email My Cart', 'cartninja-recovery-for-woocommerce' ),
                    'add_to_cart_show_gdpr'      => 'yes',
                    'add_to_cart_gdpr_text'      => __( 'I agree to receive my cart recovery link by email.', 'cartninja-recovery-for-woocommerce' ),
                    'add_to_cart_field_message'  => __( 'We only use your email to save and send your cart recovery link.', 'cartninja-recovery-for-woocommerce' ),
                    'card_color_type'            => 'gradient',
                    'card_start'                 => '#F0FAFA',
                    'card_end'                   => '#ffffff',
                    'button_color_type'          => 'gradient',
                    'button_start'               => '#0EA5A0',
                    'button_end'                 => '#0C8A86',
                    'pill_background_color'      => '#FFF0EB',
                    'pill_text_color'            => '#FF6B4A',
                    'close_icon_color'           => '#0F2B2B',
                    'close_icon_size'            => 18,
                    'title_color'                => '#0F2B2B',
                    'title_font_size'            => 34,
                    'title_font_family'          => 'inherit',
                    'title_font_style'           => 'normal',
                    'title_font_weight'          => '700',
                    'title_text_transform'       => 'none',
                    'title_letter_spacing'       => 0,
                    'description_color'          => '#4A6F6F',
                    'description_font_size'      => 16,
                    'description_font_family'    => 'inherit',
                    'description_font_style'     => 'normal',
                    'description_font_weight'    => '400',
                    'description_text_transform' => 'none',
                    'description_letter_spacing' => 0,
                    'button_text_color'          => '#ffffff',
                    'button_font_size'           => 15,
                    'button_font_family'         => 'inherit',
                    'button_font_style'          => 'normal',
                    'button_font_weight'         => '700',
                    'button_text_transform'      => 'none',
                    'button_letter_spacing'      => 0,
                ),
            ) );
        }
        $existing = get_option( 'cartninja_settings', array() );
        $merged = wp_parse_args( $existing, $defaults );
        $merged['general'] = wp_parse_args( ( isset( $merged['general'] ) && is_array( $merged['general'] ) ? $merged['general'] : array() ), $defaults['general'] );
        $merged['protection'] = wp_parse_args( ( isset( $merged['protection'] ) && is_array( $merged['protection'] ) ? $merged['protection'] : array() ), $defaults['protection'] );
        $merged['cleanup'] = wp_parse_args( ( isset( $merged['cleanup'] ) && is_array( $merged['cleanup'] ) ? $merged['cleanup'] : array() ), $defaults['cleanup'] );
        update_option( 'cartninja_settings', $merged );
    }

    private static function get_default_recovery_url() {
        $cart_page_id = absint( get_option( 'woocommerce_cart_page_id', 0 ) );
        if ( $cart_page_id > 0 ) {
            $permalink = get_permalink( $cart_page_id );
            if ( !empty( $permalink ) && !is_wp_error( $permalink ) ) {
                return $permalink;
            }
        }
        return home_url( '/cart/' );
    }

    private static function migrate_legacy_cart_statuses() {
        global $wpdb;
        $cart_ids = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}cartninja_carts WHERE status = %s AND abandoned_at IS NULL AND recovered_order_id IS NULL", 'lost' ) );
        if ( empty( $cart_ids ) ) {
            return;
        }
        foreach ( $cart_ids as $cart_id ) {
            $wpdb->update(
                $wpdb->prefix . 'cartninja_carts',
                array(
                    'status' => 'active',
                ),
                array(
                    'id' => absint( $cart_id ),
                ),
                array('%s'),
                array('%d')
            );
        }
    }

    private static function repair_missing_abandoned_dates() {
        global $wpdb;
        $table = $wpdb->prefix . 'cartninja_carts';
        $wpdb->query( "UPDATE {$table}\n\t\t\tSET abandoned_at = cart_updated_at\n\t\t\tWHERE status IN ('abandoned','recovering','recovered','lost')\n\t\t\t\tAND abandoned_at IS NULL\n\t\t\t\tAND cart_updated_at IS NOT NULL" );
    }

    private static function migrate_recovery_security_data() {
        global $wpdb;
        $table = $wpdb->prefix . 'cartninja_carts';
        $wpdb->query( "UPDATE {$table}\n\t\t\tSET recovery_expires_at = DATE_ADD(COALESCE(cart_updated_at, created_at), INTERVAL 30 DAY)\n\t\t\tWHERE recovery_expires_at IS NULL" );
        $wpdb->query( "UPDATE {$table}\n\t\t\tSET customer_ip = NULL\n\t\t\tWHERE customer_ip IS NOT NULL AND customer_ip <> ''" );
    }

    private static function migrate_security_defaults( $previous_version ) {
        if ( version_compare( $previous_version, '2.2.0', '>=' ) ) {
            return;
        }
        $settings = get_option( 'cartninja_settings', array() );
        $general = ( isset( $settings['general'] ) && is_array( $settings['general'] ) ? $settings['general'] : array() );
        $cleanup = ( isset( $settings['cleanup'] ) && is_array( $settings['cleanup'] ) ? $settings['cleanup'] : array() );
        $general['recovery_link_expiry_days'] = max( 1, min( 365, absint( ( isset( $general['recovery_link_expiry_days'] ) ? $general['recovery_link_expiry_days'] : 30 ) ) ) );
        $cleanup['enable_auto_cleanup'] = 'yes';
        $cleanup['keep_order_linked_carts'] = 'no';
        $settings['general'] = $general;
        $settings['cleanup'] = $cleanup;
        update_option( 'cartninja_settings', $settings );
    }

}
