<?php
/**
 * Activator — DB tables, default options, /returns/ page, scheduled events.
 *
 * @package WPNest_Returns_For_WooCommerce
 */

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

class WPNest_RFW_Activator {

    const OPTION_DB_VERSION = 'wpnest_rfw_db_version';
    const OPTION_PAGE_ID    = 'wpnest_rfw_page_id';

    public static function activate() {
        self::create_tables();
        self::set_defaults();
        self::create_returns_page();
        self::schedule_events();
        flush_rewrite_rules();
    }

    public static function maybe_upgrade_db() {
        if ( get_option( self::OPTION_DB_VERSION ) !== WPNEST_RFW_DB_VERSION ) {
            self::create_tables();
        }
    }

    private static function create_tables() {
        global $wpdb;

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

        $charset_collate = $wpdb->get_charset_collate();
        $requests_table  = wpnest_rfw_requests_table();
        $log_table       = wpnest_rfw_status_log_table();
        $items_table     = wpnest_rfw_request_items_table();

        $sql_requests = "CREATE TABLE {$requests_table} (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            order_id BIGINT(20) UNSIGNED NOT NULL,
            customer_id BIGINT(20) UNSIGNED DEFAULT NULL,
            order_key VARCHAR(64) NOT NULL DEFAULT '',
            status VARCHAR(50) NOT NULL DEFAULT 'pending',
            reason TEXT NULL,
            has_returned TINYINT(1) NOT NULL DEFAULT 0,
            is_digital TINYINT(1) NOT NULL DEFAULT 0,
            bank_account VARCHAR(255) DEFAULT NULL,
            attachment_path VARCHAR(500) DEFAULT NULL,
            pdf_path VARCHAR(500) DEFAULT NULL,
            pdf_token CHAR(64) DEFAULT NULL,
            deadline_at DATETIME NULL,
            ip_hash VARCHAR(64) NOT NULL DEFAULT '',
            created_at DATETIME NOT NULL,
            updated_at DATETIME NOT NULL,
            PRIMARY KEY  (id),
            KEY idx_order_id (order_id),
            KEY idx_customer_id (customer_id),
            KEY idx_status_created (status, created_at),
            KEY idx_created (created_at)
        ) {$charset_collate};";

        $sql_log = "CREATE TABLE {$log_table} (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            request_id BIGINT(20) UNSIGNED NOT NULL,
            old_status VARCHAR(50) DEFAULT NULL,
            new_status VARCHAR(50) NOT NULL,
            changed_by BIGINT(20) UNSIGNED DEFAULT NULL,
            note TEXT NULL,
            changed_at DATETIME NOT NULL,
            PRIMARY KEY  (id),
            KEY idx_request_changed (request_id, changed_at)
        ) {$charset_collate};";

        $sql_items = "CREATE TABLE {$items_table} (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            request_id BIGINT(20) UNSIGNED NOT NULL,
            order_item_id BIGINT(20) UNSIGNED NOT NULL,
            product_id BIGINT(20) UNSIGNED NOT NULL,
            variation_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
            qty SMALLINT(5) UNSIGNED NOT NULL DEFAULT 1,
            reason_code VARCHAR(40) NOT NULL DEFAULT '',
            reason_text TEXT NULL,
            PRIMARY KEY  (id),
            KEY idx_request_id (request_id),
            KEY idx_order_item_id (order_item_id)
        ) {$charset_collate};";

        dbDelta( $sql_requests );
        dbDelta( $sql_log );
        dbDelta( $sql_items );

        update_option( self::OPTION_DB_VERSION, WPNEST_RFW_DB_VERSION );
    }

    private static function set_defaults() {
        $defaults = array(
            'wpnest_rfw_enabled'                     => 1,
            'wpnest_rfw_withdrawal_window_days'      => 14,
            // Leave empty so the (translated) default kicks in via class-frontend.php::button_label().
            'wpnest_rfw_button_label'                => '',
            'wpnest_rfw_merchant_email'              => '',
            'wpnest_rfw_delete_data_on_uninstall'    => 0,
            'wpnest_rfw_show_on_my_account'          => 1,
            'wpnest_rfw_show_on_view_order'          => 1,
            'wpnest_rfw_show_on_returns_page'        => 1,
            'wpnest_rfw_notify_customer_on_status'   => 1,
            'wpnest_rfw_excluded_statuses'           => array( 'cancelled', 'failed', 'refunded', 'trash' ),
            'wpnest_rfw_exclude_digital_with_waiver' => 1,
            'wpnest_rfw_exclude_customized'          => 0,
            'wpnest_rfw_exclude_subscriptions'       => 1,
            'wpnest_rfw_excluded_product_ids'        => array(),
            'wpnest_rfw_installed_at'                => time(),
        );

        foreach ( $defaults as $key => $value ) {
            if ( false === get_option( $key ) ) {
                add_option( $key, $value );
            }
        }
    }

    private static function create_returns_page() {
        $existing_id = (int) get_option( self::OPTION_PAGE_ID );
        if ( $existing_id > 0 && get_post( $existing_id ) ) {
            return;
        }

        $page_id = wp_insert_post(
            array(
                'post_title'   => __( 'Returns', 'wpnest-returns-for-woocommerce' ),
                'post_name'    => 'returns',
                'post_status'  => 'publish',
                'post_type'    => 'page',
                'post_content' => '[wpnest_rfw_returns_page]',
            ),
            true
        );

        if ( ! is_wp_error( $page_id ) && $page_id > 0 ) {
            update_option( self::OPTION_PAGE_ID, (int) $page_id );
        }
    }

    private static function schedule_events() {
        if ( ! wp_next_scheduled( 'wpnest_rfw_daily_cleanup' ) ) {
            wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'wpnest_rfw_daily_cleanup' );
        }
    }
}

/**
 * Daily cleanup hook — extension point for Pro and future Free maintenance.
 * In Free v1.0.0 this is a no-op; the action exists so Pro can hook in.
 */
add_action(
    'wpnest_rfw_daily_cleanup',
    function () {
        do_action( 'wpnest_rfw_run_daily_cleanup' );
    }
);
