<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class Trendly_AI_Post {
    protected $loader;
    protected $i18n;
    protected $admin;

    public function __construct() {
        $this->loader = new Trendly_AI_Post_Loader();
        $this->i18n   = new Trendly_AI_Post_i18n();
        $this->admin  = new Trendly_AI_Post_Admin();

        $this->define_hooks();
    }

    private function define_hooks() : void {
        // i18n (auto from WordPress language packs; explicit call avoided for coding standards)

        // Admin
        $this->loader->add_action( 'admin_menu', $this->admin, 'add_menu' );
        $this->loader->add_action( 'admin_init', $this->admin, 'register_settings' );
        $this->loader->add_action( 'admin_enqueue_scripts', $this->admin, 'enqueue_assets' );
        $this->loader->add_action( 'admin_footer_text', $this->admin, 'remove_admin_footer', 999 );
        $this->loader->add_action( 'wp_ajax_trendly_test_api_keys', $this->admin, 'ajax_test_api_keys' );
        $this->loader->add_action( 'wp_ajax_trendly_generate_draft', $this->admin, 'ajax_generate_draft' );
        $this->loader->add_action( 'wp_ajax_trendly_fetch_trends', $this->admin, 'ajax_fetch_trends' );
        $this->loader->add_action( 'wp_ajax_trendly_generate_from_topic', $this->admin, 'ajax_generate_from_topic' );

        // SEO Preview meta box
        $seo = new Trendly_AI_Post_SEO_Preview();
        $this->loader->add_action( 'add_meta_boxes', $seo, 'register_meta_box' );
        $this->loader->add_action( 'save_post', $seo, 'save_meta', 10, 2 );

        // Cron scheduling
        $this->loader->add_action( 'trendly_ai_post_cron', $this, 'run_scheduled_generation' );
    }

    public function run() : void {
        // No-op: hooks already registered in constructor
    }

    public function run_scheduled_generation() : void {
        // Check setting enabled
        $opts = get_option( 'trendly_ai_post_options', [] );
        if ( empty( $opts['autoschedule_enabled'] ) ) {
            return;
        }
        // Delegate to generator
        $generator = new Trendly_AI_Post_Post_Generator();
        $generator->generate_and_publish_from_trends();
    }
}
