<?php
/**
 * Bootstrap provider for PrimeLink.
 *
 * @package PrimeLink
 */

namespace PrimeLink;

use PrimeLink\Core\Plugin;

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

final class Bootstrap {

    /**
     * Initialize plugin.
     *
     * @return void
     */
    public function init() {
        add_action( 'init', array( $this, 'load_textdomain' ), 0 );

        // Late init like WPIE, to ensure WC & dependencies are ready.
        add_action( 'init', array( Plugin::class, 'init' ), 9999 );

        // Allow XML uploads (needed for XPath imports).
        add_filter( 'upload_mimes', array( $this, 'allow_xml_uploads' ) );
        add_filter( 'wp_check_filetype_and_ext', array( $this, 'force_xml_filetypes' ), 10, 4 );
        add_filter( 'cron_schedules', array( $this, 'add_custom_schedules' ) );

        add_action( 'mt_primelink_import_tick', function( $import_id ) {
        \PrimeLink\Modules\Imports\Service\ImportRunner::tick( $import_id );
    } );
        add_action( 'mt_primelink_import_start_scheduled', function( $import_id ) {
        \PrimeLink\Modules\Imports\Service\ImportRunner::start( $import_id );
    } );
        // Ensure scheduled imports kick off even if WP-Cron lags: check on admin hits.
        add_action( 'admin_init', function() {
            \PrimeLink\Modules\Imports\Service\ImportRunner::maybe_start_schedules();
        } );

        // Export scheduled actions
        add_action( 'mt_primelink_export_start_scheduled', function( $export_id ) {
            $drafts = get_option( 'mt_primelink_export_drafts', array() );
            $draft = $drafts[ $export_id ] ?? null;
            if ( $draft ) {
                \PrimeLink\Modules\Exports\Service\ExportRunner::start( $export_id, $draft, true );
            }
        } );
        add_action( 'mt_primelink_export_tick', function( $export_id ) {
            \PrimeLink\Modules\Exports\Service\ExportRunner::tick( $export_id );
        } );
        // Ensure scheduled exports kick off even if WP-Cron lags: check on admin hits.
        add_action( 'admin_init', function() {
            \PrimeLink\Modules\Exports\Service\ExportRunner::maybe_start_schedules();
        } );

        // Daily cleanup of finished imports if configured.
        add_action( 'mt_primelink_cleanup_cron', array( $this, 'cleanup_finished_imports' ) );
        if ( ! wp_next_scheduled( 'mt_primelink_cleanup_cron' ) ) {
            wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'mt_primelink_cleanup_cron' );
        }

        // Periodic license verification (once per day)
        add_action( 'admin_init', array( $this, 'verify_license_periodically' ), 5 );

    }

    /**
     * Load translations.
     *
     * @return void
     */
    public function load_textdomain() {
        load_plugin_textdomain(
            'primelink',
            false,
            dirname( MT_PRIMELINK_BASENAME ) . '/languages'
        );
    }

    /**
     * Add weekly/monthly schedules for automation.
     */
    public function add_custom_schedules( $schedules ) {
        if ( ! isset( $schedules['weekly'] ) ) {
            $schedules['weekly'] = array(
                'interval' => 7 * DAY_IN_SECONDS,
                'display'  => __( 'Once Weekly', 'primelink' ),
            );
        }
        if ( ! isset( $schedules['monthly'] ) ) {
            $schedules['monthly'] = array(
                'interval' => 30 * DAY_IN_SECONDS,
                'display'  => __( 'Once Monthly', 'primelink' ),
            );
        }
        return $schedules;
    }

    /**
     * Ensure XML files are allowed for upload/validation.
     *
     * @param array $mimes Existing mime types.
     *
     * @return array
     */
    public function allow_xml_uploads( $mimes ) {
        $mimes['xml'] = 'application/xml';
        // Some servers use text/xml; include it to be safe.
        $mimes['xsl'] = 'text/xml';
        $mimes['json'] = 'application/json';
        return $mimes;
    }

    /**
     * Force XML/XSL/JSON types to be recognized, avoids "not allowed" errors.
     */
    public function force_xml_filetypes( $data, $file, $filename, $mimes ) {
        $ext = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) );
        if ( in_array( $ext, array( 'xml', 'xsl', 'json' ), true ) ) {
            // Provide sane defaults if WP could not detect them.
            if ( empty( $data['type'] ) ) {
                $data['type'] = $ext === 'json' ? 'application/json' : 'application/xml';
            }
            if ( empty( $data['ext'] ) ) {
                $data['ext'] = $ext;
            }
            $data['proper_filename'] = $filename;
        }
        return $data;
    }

    public function cleanup_finished_imports() {
        $settings = get_option( 'mt_primelink_settings', array() );
        $days = isset( $settings['cleanup_days'] ) ? absint( $settings['cleanup_days'] ) : 0;
        if ( $days < 1 ) {
            $days = 0;
        }
        $retention = isset( $settings['source_retention_days'] ) ? absint( $settings['source_retention_days'] ) : 0;

        $cutoff = time() - ( DAY_IN_SECONDS * $days );
        $drafts = get_option( 'mt_primelink_import_drafts', array() );
        if ( ! is_array( $drafts ) ) {
            return;
        }

        foreach ( $drafts as $id => $draft ) {
            $created = isset( $draft['created_at'] ) ? strtotime( $draft['created_at'] ) : 0;
            $state   = get_option( 'mt_primelink_import_state_' . absint( $id ), array() );
            $finished = ( $state['status'] ?? '' ) === 'finished';

            if ( $finished && $created && $created < $cutoff ) {
                unset( $drafts[ $id ] );
                delete_option( 'mt_primelink_import_state_' . absint( $id ) );
            }
        }

        update_option( 'mt_primelink_import_drafts', $drafts, false );

        // Cleanup old source files
        if ( $retention > 0 ) {
            $upload_dir = wp_upload_dir();
            $dir = trailingslashit( $upload_dir['basedir'] ) . 'primelink/';
            if ( is_dir( $dir ) ) {
                $iterator = new \DirectoryIterator( $dir );
                $cut = time() - ( DAY_IN_SECONDS * $retention );
                foreach ( $iterator as $fileinfo ) {
                    if ( $fileinfo->isDot() || ! $fileinfo->isFile() ) {
                        continue;
                    }
                    if ( $fileinfo->getMTime() < $cut ) {
                        @unlink( $fileinfo->getPathname() );
                    }
                }
            }
        }
    }

    /**
     * Verify license periodically (once per day).
     *
     * @return void
     */
    public function verify_license_periodically() {
        if ( ! is_admin() ) {
            return;
        }

        $transient_key = 'mt_primelink_license_verify_daily';
        $last_check = get_transient( $transient_key );
        
        if ( $last_check !== false ) {
            return; // Already checked today
        }

        // Perform time-based license verification
        if ( class_exists( '\PrimeLink\Helpers\EnvatoHelper' ) ) {
            \PrimeLink\Helpers\EnvatoHelper::verify_license( true );
        }

        // Cache for 24 hours
        set_transient( $transient_key, true, DAY_IN_SECONDS );
    }
}
