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

class Trendly_AI_Post_Admin {
    public function add_menu() : void {
        $hook = add_menu_page(
            __( 'Trendly AI', 'trendly-ai-post' ),
            __( 'Trendly AI', 'trendly-ai-post' ),
            'manage_options',
            'trendly-ai-post',
            [ $this, 'render_settings_page' ],
            'dashicons-admin-site-alt3',
            65
        );

        add_submenu_page(
            'trendly-ai-post',
            __( 'Generate Content', 'trendly-ai-post' ),
            __( 'Generate Content', 'trendly-ai-post' ),
            'manage_options',
            'trendly-ai-post-generate',
            [ $this, 'render_generate_page' ]
        );
    }

    public function enqueue_assets( $hook ) : void {
        if ( strpos( $hook, 'trendly-ai-post' ) === false ) return;
        wp_enqueue_style( 'trendly-ai-admin', TRENDLY_AI_POST_URL . 'admin/css/admin.css', [], TRENDLY_AI_POST_VERSION );
        wp_enqueue_script( 'trendly-ai-admin', TRENDLY_AI_POST_URL . 'admin/js/admin.js', [ 'jquery' ], TRENDLY_AI_POST_VERSION, true );
        wp_localize_script( 'trendly-ai-admin', 'TrendlyAI', [
            'ajaxUrl' => admin_url( 'admin-ajax.php' ),
            'nonce'   => wp_create_nonce( 'trendly_ai_admin_nonce' ),
        ] );
    }

    public function register_settings() : void {
        register_setting( 'trendly_ai_post_options_group', 'trendly_ai_post_options', [ $this, 'sanitize_options' ] );
    }

    public function sanitize_options( $opts ) {
        $clean = [];
        $clean['gemini_api_key'] = isset($opts['gemini_api_key']) ? sanitize_text_field( $opts['gemini_api_key'] ) : '';
        $clean['pexels_api_key'] = isset($opts['pexels_api_key']) ? sanitize_text_field( $opts['pexels_api_key'] ) : '';
        $clean['region'] = isset($opts['region']) ? sanitize_text_field( $opts['region'] ) : 'IN';
        $clean['default_length'] = isset($opts['default_length']) ? sanitize_text_field( $opts['default_length'] ) : 'medium';
        $clean['default_category'] = isset($opts['default_category']) ? intval( $opts['default_category'] ) : 0;
        $clean['default_author'] = isset($opts['default_author']) ? intval( $opts['default_author'] ) : get_current_user_id();
        $clean['autoschedule_enabled'] = empty($opts['autoschedule_enabled']) ? 0 : 1;
        $clean['autoschedule_frequency'] = isset($opts['autoschedule_frequency']) ? sanitize_text_field( $opts['autoschedule_frequency'] ) : 'daily-1';
        $clean['autoschedule_time'] = isset($opts['autoschedule_time']) ? sanitize_text_field( $opts['autoschedule_time'] ) : '09:00';

        // Update cron schedule
        $this->update_schedule( $clean );

        return $clean;
    }

    private function update_schedule( array $opts ) : void {
        // Clear existing schedule
        $timestamp = wp_next_scheduled( 'trendly_ai_post_cron' );
        if ( $timestamp ) wp_unschedule_event( $timestamp, 'trendly_ai_post_cron' );

        if ( empty( $opts['autoschedule_enabled'] ) ) return;

        // Parse frequency: daily-1 or daily-2
        $per_day = 1;
        if ( $opts['autoschedule_frequency'] === 'daily-2' ) $per_day = 2;

        $time = $opts['autoschedule_time'];
        // Compute first run at specified time using site timezone without using date()
        $tz  = wp_timezone();
        $now = new DateTimeImmutable( 'now', $tz );
        $parts = explode( ':', $time );
        $hour = isset( $parts[0] ) ? (int) $parts[0] : 9;
        $min  = isset( $parts[1] ) ? (int) $parts[1] : 0;
        $first = $now->setTime( $hour, $min, 0 );
        if ( $first->getTimestamp() <= time() ) {
            $first = $first->modify( '+1 day' );
        }
        $first_timestamp = $first->getTimestamp();
        wp_schedule_event( $first_timestamp, 'daily', 'trendly_ai_post_cron' );
        if ( $per_day === 2 ) {
            wp_schedule_event( $first_timestamp + 12 * HOUR_IN_SECONDS, 'daily', 'trendly_ai_post_cron' );
        }
    }

    public function ajax_test_api_keys() : void {
        check_ajax_referer( 'trendly_ai_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( [ 'message' => __( 'Permission denied', 'trendly-ai-post' ) ] );
        $opts = get_option( 'trendly_ai_post_options', [] );
        $ok = ! empty( $opts['gemini_api_key'] ) && ! empty( $opts['pexels_api_key'] );
        wp_send_json_success( [ 'configured' => $ok ] );
    }

    public function remove_admin_footer( $footer_text ) {
        // Aggressive but safe footer removal within our admin page
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if ( $screen && strpos( $screen->id, 'trendly-ai-post' ) !== false ) {
            return '';
        }
        return $footer_text;
    }

    public function render_settings_page() : void {
        if ( ! current_user_can( 'manage_options' ) ) return;
        $opts = get_option( 'trendly_ai_post_options', [] );
        include TRENDLY_AI_POST_PATH . 'admin/partials/admin-display.php';
    }

    public function ajax_generate_draft() : void {
        check_ajax_referer( 'trendly_ai_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => __( 'Permission denied', 'trendly-ai-post' ) ] );
        }

        $opts    = get_option( 'trendly_ai_post_options', [] );
        $region  = $opts['region'] ?? 'IN';
        $length  = $opts['default_length'] ?? 'medium';
        $api     = new Trendly_AI_Post_API_Handler();
        $topics  = $api->fetch_trending_topics( $region, 10 );
        if ( empty( $topics ) ) {
            wp_send_json_error( [ 'message' => __( 'No trending topics available right now.', 'trendly-ai-post' ) ] );
        }

        $dup = new Trendly_AI_Post_Duplicate();
        $topic = '';
        foreach ( $topics as $t ) {
            if ( ! $dup->title_exists( $t ) ) { $topic = $t; break; }
        }
        if ( empty( $topic ) ) {
            $topic = $topics[0]; // fallback
        }

        $gen = new Trendly_AI_Post_Post_Generator();
        $default_images = intval( $opts['default_image_count'] ?? 1 );
        if ( $default_images < 1 ) { $default_images = 1; }
        if ( $default_images > 4 ) { $default_images = 4; }
        $post_id = $gen->generate_single_post( $topic, $length, 'draft', $default_images );
        if ( empty( $post_id ) ) {
            wp_send_json_error( [ 'message' => __( 'Failed to create draft.', 'trendly-ai-post' ) ] );
        }

        $edit_link = get_edit_post_link( $post_id, '' );
        $permalink = get_permalink( $post_id );
        $preview   = get_preview_post_link( $post_id );
        wp_send_json_success( [
            'post_id'      => $post_id,
            'edit_link'    => $edit_link,
            'permalink'    => $permalink,
            'preview_link' => $preview,
            'title'        => get_the_title( $post_id ),
        ] );
    }

    public function render_generate_page() : void {
        if ( ! current_user_can( 'manage_options' ) ) return;
        $opts = get_option( 'trendly_ai_post_options', [] );
        include TRENDLY_AI_POST_PATH . 'admin/partials/generate.php';
    }

    public function ajax_fetch_trends() : void {
        check_ajax_referer( 'trendly_ai_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => __( 'Permission denied', 'trendly-ai-post' ) ] );
        }
        $region = isset($_POST['region']) ? sanitize_text_field( wp_unslash( $_POST['region'] ) ) : 'IN';
        $api    = new Trendly_AI_Post_API_Handler();
        $topics = $api->fetch_trending_topics( $region, 20 );
        if ( empty( $topics ) ) {
            wp_send_json_error( [ 'message' => __( 'No trending topics available right now. Please try a different region or try again later.', 'trendly-ai-post' ) ] );
        }
        wp_send_json_success( [ 'topics' => array_values( $topics ) ] );
    }

    public function ajax_generate_from_topic() : void {
        check_ajax_referer( 'trendly_ai_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => __( 'Permission denied', 'trendly-ai-post' ) ] );
        }
        $topic  = isset($_POST['topic']) ? sanitize_text_field( wp_unslash( $_POST['topic'] ) ) : '';
        $length = isset($_POST['length']) ? sanitize_text_field( wp_unslash( $_POST['length'] ) ) : 'medium';
        $images = isset($_POST['images']) ? max(1, (int) $_POST['images']) : 1;
        $status = isset($_POST['status']) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : 'draft';
        if ( $status !== 'publish' ) { $status = 'draft'; }
        if ( empty( $topic ) ) {
            wp_send_json_error( [ 'message' => __( 'Missing topic.', 'trendly-ai-post' ) ] );
        }
        $gen = new Trendly_AI_Post_Post_Generator();
        $post_id = $gen->generate_single_post( $topic, $length, $status, $images );
        if ( empty( $post_id ) ) {
            wp_send_json_error( [ 'message' => __( 'Failed to create draft.', 'trendly-ai-post' ) ] );
        }
        wp_send_json_success( [
            'post_id'      => $post_id,
            'edit_link'    => get_edit_post_link( $post_id, '' ),
            'permalink'    => get_permalink( $post_id ),
            'preview_link' => get_preview_post_link( $post_id ),
            'title'        => get_the_title( $post_id ),
        ] );
    }
}