<?php
/**
 * Free plugin bootstrap.
 *
 * @package SwairishXHeaderBarNotificationOffer
 */

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

class SwairishX_Plugin {
    private static $instance;
    private $registry;
    private $storage;
    private $renderer;
    private $admin;

    public static function instance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        $this->registry = new SwairishX_Registry();
        $this->storage = new SwairishX_Storage();

        add_action('init', array($this, 'register_capabilities'), 5);
        add_action('init', array('SwairishX_Storage', 'register_post_type'));
        $integrations = new SwairishX_Integrations($this->storage);
        $integrations->hooks();
        $this->renderer = new SwairishX_Renderer($this->storage);
        $this->renderer->hooks();
        $this->admin = new SwairishX_Admin($this->storage, $this->registry, $this->renderer);

        add_action('wp_ajax_swairishx_track', array($this, 'track'));
        add_action('wp_ajax_nopriv_swairishx_track', array($this, 'track'));
        add_action('swairishx_cleanup', array($this, 'cleanup'));
        add_filter('cron_schedules', array($this, 'cron_schedules'));
        add_filter('plugin_action_links_' . plugin_basename(SWAIRISHX_FILE), array($this, 'action_links'));
    }

    public function registry() {
        return $this->registry;
    }

    public function storage() {
        return $this->storage;
    }

    public function renderer() {
        return $this->renderer;
    }

    public function admin() {
        return $this->admin;
    }

    public function register_capabilities() {
        $this->register_free_capabilities();
        do_action('swairishx_register_capabilities', $this->registry);
    }

    private function register_free_capabilities() {
        $notifications = array(
            'sales_alert' => __('Sales alert', 'swairish-header-bar-offer-notifications'),
            'discount_alert' => __('Discount alert', 'swairish-header-bar-offer-notifications'),
            'blog_comments_alert' => __('Comment alert', 'swairish-header-bar-offer-notifications'),
            'wordpress_review_alert' => __('WordPress review alert', 'swairish-header-bar-offer-notifications'),
            'wordpress_download_count_alert' => __('WordPress download alert', 'swairish-header-bar-offer-notifications'),
            'notification_bar' => __('Header notification bar', 'swairish-header-bar-offer-notifications'),
        );
        foreach ($notifications as $id => $label) {
            $this->registry->register('notification', $id, array('label' => $label, 'package' => 'free'));
        }

        $integrations = array(
            'manual' => __('Manual content', 'swairish-header-bar-offer-notifications'),
            'woocommerce' => 'WooCommerce',
            'easy_digital_downloads' => 'Easy Digital Downloads',
            'givewp' => 'GiveWP',
            'tutor_lms' => 'Tutor LMS',
            'contact_form_7' => 'Contact Form 7',
            'ninja_forms' => 'Ninja Forms',
            'wpforms' => 'WPForms',
            'wordpress_comments' => __('WordPress comments', 'swairish-header-bar-offer-notifications'),
            'wordpress_org' => 'WordPress.org',
        );
        foreach ($integrations as $id => $label) {
            $this->registry->register('integration', $id, array('label' => $label, 'package' => 'free'));
        }

        foreach (array('signal', 'paper', 'contrast') as $theme) {
            $this->registry->register('theme', $theme, array('label' => ucwords($theme), 'package' => 'free'));
        }
    }

    public function track() {
        check_ajax_referer('swairishx_public_tracking', 'token');
        $campaign_id = isset($_POST['campaignId']) ? absint($_POST['campaignId']) : 0;
        $event = isset($_POST['event']) ? sanitize_key(wp_unslash($_POST['event'])) : '';
        $config = $campaign_id ? $this->storage->get_campaign($campaign_id) : null;
        if (!$config || 'publish' !== get_post_status($campaign_id) || empty($config['tracking'])) {
            wp_send_json_error(array('message' => __('Unknown campaign.', 'swairish-header-bar-offer-notifications')), 404);
        }
        if (!in_array($event, array('impression', 'click', 'dismiss'), true)) {
            wp_send_json_error(array('message' => __('Unknown tracking event.', 'swairish-header-bar-offer-notifications')), 400);
        }
        $this->storage->record_stat($campaign_id, $event);
        wp_send_json_success();
    }

    public function cleanup() {
        global $wpdb;
        $events = $wpdb->prefix . 'swairishx_events';
        $stats = $wpdb->prefix . 'swairishx_stats';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Scheduled retention cleanup for plugin-owned data.
        $wpdb->query($wpdb->prepare('DELETE FROM %i WHERE occurred_at < (UTC_TIMESTAMP() - INTERVAL 90 DAY)', $events));
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Scheduled retention cleanup for plugin-owned data.
        $wpdb->query($wpdb->prepare('DELETE FROM %i WHERE stat_date < (UTC_DATE() - INTERVAL 730 DAY)', $stats));
    }

    public function action_links($links) {
        array_unshift($links, '<a href="' . esc_url(admin_url('admin.php?page=swairishx')) . '">' . esc_html__('Dashboard', 'swairish-header-bar-offer-notifications') . '</a>');
        return $links;
    }

    public function cron_schedules($schedules) {
        $schedules['swairishx_six_hours'] = array('interval' => 6 * HOUR_IN_SECONDS, 'display' => __('Every six hours', 'swairish-header-bar-offer-notifications'));
        return $schedules;
    }

    public static function activate() {
        self::instance();
        SwairishX_Storage::register_post_type();
        SwairishX_Storage::install_tables();
        if (!wp_next_scheduled('swairishx_cleanup')) {
            wp_schedule_event(time() + HOUR_IN_SECONDS, 'daily', 'swairishx_cleanup');
        }
        if (!wp_next_scheduled('swairishx_sync_wordpress_org')) {
            wp_schedule_event(time() + MINUTE_IN_SECONDS, 'swairishx_six_hours', 'swairishx_sync_wordpress_org');
        }
        flush_rewrite_rules(false);
    }

    public static function deactivate() {
        wp_clear_scheduled_hook('swairishx_cleanup');
        wp_clear_scheduled_hook('swairishx_sync_wordpress_org');
        flush_rewrite_rules(false);
    }
}
