<?php

namespace Pagup\MassPingTool\Controllers;

use Pagup\MassPingTool\Core\Option;
use Pagup\MassPingTool\Core\Plugin;
use Pagup\MassPingTool\Core\Request;
use Pagup\MassPingTool\Traits\Helpers;
class SettingsController {
    use Helpers;
    protected $log_table = MPT_LOG_TABLE;

    public function add_settings() {
        add_menu_page(
            __( 'Mass Ping Tool for SEO', 'mass-ping-tool-for-seo' ),
            __( 'Mass Ping Tool', 'mass-ping-tool-for-seo' ),
            'manage_options',
            MPT_NAME,
            array(&$this, 'page'),
            'dashicons-rss'
        );
    }

    public function page() {
        global $wpdb;
        $safe = ["allow", "settings", "faq"];
        if ( isset( $_POST['update'] ) ) {
            // check if user is authorised
            if ( function_exists( 'current_user_can' ) && !current_user_can( 'manage_options' ) ) {
                die( 'Sorry, not allowed...' );
            }
            check_admin_referer( 'mpt__settings', 'mpt__nonce' );
            if ( !isset( $_POST['mpt__nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['mpt__nonce'] ) ), 'mpt__settings' ) ) {
                die( 'Sorry, not allowed. Nonce doesn\'t verify' );
            }
            $post_types = isset( $_POST['post_types'] ) ? wp_unslash( $_POST['post_types'] ) : [];
            $options = [
                'enable'          => Request::post( 'enable', $safe ),
                'post_types'      => Request::array( $post_types ),
                'limit'           => Request::post( 'limit', $safe ),
                'remove_settings' => Request::post( 'remove_settings', $safe ),
            ];
            // Clear cron if user downgrades from premium
            wp_clear_scheduled_hook( 'mpt_auto_update_services' );
            update_option( 'mass-ping-tool-for-seo', $options );
            $ping_list = isset( $_POST['ping_sites'] ) ? sanitize_textarea_field( wp_unslash( $_POST['ping_sites'] ) ) : '';
            update_option( "ping_sites", $ping_list );
            // update options
            echo '<div class="notice notice-success is-dismissible"><p><strong>' . esc_html__( 'Settings saved.', 'mass-ping-tool-for-seo' ) . '</strong></p></div>';
        }
        $ping = new \Pagup\MassPingTool\Controllers\PingController();
        if ( isset( $_POST['update_services'] ) ) {
            if ( function_exists( 'current_user_can' ) && !current_user_can( 'manage_options' ) ) {
                die( 'Sorry, not allowed...' );
            }
            check_admin_referer( 'mpt__settings', 'mpt__nonce' );
            if ( !isset( $_POST['mpt__nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['mpt__nonce'] ) ), 'mpt__settings' ) ) {
                die( 'Sorry, not allowed. Nonce doesn\'t verify' );
            }
            $api = $ping->api( 'https://agenceseo.ca/wp-json/mass-ping/v1/services' );
            update_option( 'mpt-ping-services', $api );
            update_option( "mpt-last-update", time() );
            echo '<div class="notice notice-success is-dismissible"><p><strong>' . esc_html__( 'Servers list updated successfully', 'mass-ping-tool-for-seo' ) . '</strong></p></div>';
        }
        // PING NOW
        if ( isset( $_POST['pinging'] ) ) {
            // check if user is authorised
            if ( function_exists( 'current_user_can' ) && !current_user_can( 'manage_options' ) ) {
                die( 'Sorry, not allowed...' );
            }
            check_admin_referer( 'mpt__settings', 'mpt__nonce' );
            if ( !isset( $_POST['mpt__nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['mpt__nonce'] ) ), 'mpt__settings' ) ) {
                die( 'Sorry, not allowed. Nonce doesn\'t verify' );
            }
            $pingme_posts = $wpdb->get_results( "SELECT id, meta_key FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.id = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_pingme'" );
            if ( !empty( $pingme_posts ) ) {
                $i = 0;
                foreach ( $pingme_posts as $post ) {
                    $i = $i + 60;
                    $time = time() + $i;
                    $log = [
                        "message" => "Forced Ping: This will be pinged at {$time}",
                    ];
                    $this->schedule_event( $post->id, $time, $log );
                    // wp_schedule_single_event( $time, 'mass_ping', array($post->id), true);
                }
                echo '<div class="notice notice-success is-dismissible"><p style="font-size: 18px;"><strong>' . count( $pingme_posts ) . esc_html__( ' Post(s) are scheduled to ping (forced), each after 1 minute.', 'mass-ping-tool-for-seo' ) . '</strong></p></div>';
            } else {
                echo '<div class="notice notice-success is-dismissible"><p style="font-size: 18px;"><strong>' . esc_html__( ' Nothing to ping at the moment.', 'mass-ping-tool-for-seo' ) . '</strong></p></div>';
            }
        }
        $ping_sites = get_option( "ping_sites" );
        $options = new Option();
        // Get logs for Ping Log Report
        $logs = $wpdb->get_results( "SELECT * FROM {$this->log_table} ORDER BY updated_at DESC", OBJECT );
        // Get Scheduled posts from Logs table
        $time = time();
        $scheduled_posts = $wpdb->get_results( "SELECT * FROM {$this->log_table} WHERE time > {$time}" );
        //Set active class for navigation tabs
        $active_tab = ( isset( $_GET['tab'] ) && in_array( $_GET['tab'], $safe ) ? sanitize_key( $_GET['tab'] ) : 'settings' );
        $get_pro = sprintf( wp_kses( __( '<a href="%s">Get Pro version</a> to enable', 'mass-ping-tool-for-seo' ), array(
            'a' => array(
                'href'   => array(),
                'target' => array(),
            ),
        ) ), esc_url( 'admin.php?page=' . MPT_NAME . '-pricing' ) );
        $services = get_option( 'mpt-ping-services' );
        $pro_count = ( isset( $services->pro_services ) && !empty( $services->pro_services ) ? $services->pro_services : "" );
        $free_count = ( isset( $services->free_services ) && !empty( $services->free_services ) ? $services->free_services : "" );
        $post_types = $this->cpts( ['attachment'] );
        // Auto update schedule options
        $auto_update_options = [
            ''       => __( 'Disabled', 'mass-ping-tool-for-seo' ),
            '1week'  => __( 'Every 1 Week', 'mass-ping-tool-for-seo' ),
            '2weeks' => __( 'Every 2 Weeks', 'mass-ping-tool-for-seo' ),
            '3weeks' => __( 'Every 3 Weeks', 'mass-ping-tool-for-seo' ),
            '4weeks' => __( 'Every 4 Weeks', 'mass-ping-tool-for-seo' ),
        ];
        if ( defined( 'MPT_DEBUG_MODE' ) && MPT_DEBUG_MODE && current_user_can( 'manage_options' ) ) {
            $auto_update_options['5min'] = __( 'Every 5 Minutes (Test)', 'mass-ping-tool-for-seo' );
            echo '<div class="notice notice-warning" style="border-left-color: #ff6b6b;">';
            echo '<p><strong>🔧 DEBUG MODE ACTIVE</strong> - Remember to disable before production!</p>';
            echo '</div>';
        }
        if ( $active_tab == 'settings' ) {
            return Plugin::view( 'settings', compact(
                'active_tab',
                'ping_sites',
                'options',
                'post_types',
                'logs',
                'scheduled_posts',
                'services',
                'pro_count',
                'free_count',
                'get_pro',
                'auto_update_options'
            ) );
        }
        if ( $active_tab == 'faq' ) {
            return Plugin::view( "faq", compact( 'active_tab' ) );
        }
    }

    /**
     * Schedule auto update services based on selected interval
     */
    private function schedule_auto_update( $schedule ) {
        // Add debug logging
        error_log( "MPT: Attempting to schedule: {$schedule}" );
        $intervals = [
            '1week'  => 'mpt_1week',
            '2weeks' => 'mpt_2weeks',
            '3weeks' => 'mpt_3weeks',
            '4weeks' => 'mpt_4weeks',
        ];
        if ( defined( 'MPT_DEBUG_MODE' ) && MPT_DEBUG_MODE ) {
            $intervals['5min'] = 'mpt_5min';
        }
        if ( isset( $intervals[$schedule] ) ) {
            $cron_schedule = $intervals[$schedule];
            wp_clear_scheduled_hook( 'mpt_auto_update_services' );
            $result = wp_schedule_event( time() + 60, $cron_schedule, 'mpt_auto_update_services' );
            if ( $result === false ) {
                error_log( "MPT: Failed to schedule cron for {$schedule} using {$cron_schedule}" );
                error_log( "MPT: Available schedules: " . print_r( wp_get_schedules(), true ) );
            } else {
                error_log( "MPT: Successfully scheduled cron for {$schedule} using {$cron_schedule}" );
                $next_run = wp_next_scheduled( 'mpt_auto_update_services' );
                if ( $next_run ) {
                    error_log( "MPT: Verified - next run at: " . date( 'Y-m-d H:i:s', $next_run ) );
                } else {
                    error_log( "MPT: ERROR - Cron was not actually scheduled!" );
                }
            }
            return $result;
        } else {
            error_log( "MPT: Unknown schedule: {$schedule}" );
            error_log( "MPT: Available intervals: " . print_r( array_keys( $intervals ), true ) );
            return false;
        }
    }

    /**
     * Auto update services via cron (Premium only)
     */
    public function auto_update_services() {
        return false;
        // Use the exact same logic as the manual update button
        $ping = new \Pagup\MassPingTool\Controllers\PingController();
        $api = $ping->api( 'https://agenceseo.ca/wp-json/mass-ping/v1/services-pro-RsORYdEntileD' );
        if ( $api ) {
            update_option( 'mpt-ping-services', $api );
            update_option( "mpt-last-update", time() );
            return true;
        }
        return false;
    }

    // Add this temporary method to your SettingsController for testing
    public function debug_api_call() {
        echo "<div style='background: #fff3cd; padding: 15px; margin: 10px 0; border-radius: 6px;'>";
        echo "<h4>🔍 API Debug Test</h4>";
        $ping = new \Pagup\MassPingTool\Controllers\PingController();
        // Test the premium API
        $api_url = 'https://agenceseo.ca/wp-json/mass-ping/v1/services-pro-RsORYdEntileD';
        echo "<p><strong>Testing API:</strong> {$api_url}</p>";
        // Test direct wp_remote_get
        $response = wp_remote_get( $api_url );
        if ( is_wp_error( $response ) ) {
            echo "<p style='color: red;'><strong>❌ WP Remote Error:</strong> " . $response->get_error_message() . "</p>";
        } else {
            $response_code = wp_remote_retrieve_response_code( $response );
            $response_body = wp_remote_retrieve_body( $response );
            echo "<p><strong>📊 Response Code:</strong> {$response_code}</p>";
            echo "<p><strong>📄 Response Length:</strong> " . strlen( $response_body ) . " characters</p>";
            echo "<p><strong>📋 Response Preview:</strong></p>";
            echo "<pre style='background: #f8f9fa; padding: 10px; border-radius: 4px; overflow-x: auto;'>";
            echo htmlspecialchars( substr( $response_body, 0, 500 ) );
            if ( strlen( $response_body ) > 500 ) {
                echo "\n... (truncated)";
            }
            echo "</pre>";
            // Test JSON decode
            $json_data = json_decode( $response_body );
            if ( $json_data ) {
                echo "<p style='color: green;'><strong>✅ JSON Valid:</strong> Data can be decoded</p>";
                echo "<p><strong>🔍 JSON Structure:</strong></p>";
                echo "<pre style='background: #f8f9fa; padding: 10px; border-radius: 4px;'>";
                print_r( $json_data );
                echo "</pre>";
            } else {
                echo "<p style='color: red;'><strong>❌ JSON Invalid:</strong> Cannot decode response</p>";
            }
        }
        // Test using plugin's api method
        echo "<hr style='margin: 15px 0;'>";
        echo "<p><strong>Testing Plugin's API Method:</strong></p>";
        $api_result = $ping->api( $api_url );
        if ( $api_result ) {
            echo "<p style='color: green;'><strong>✅ Plugin API Method:</strong> Success</p>";
            echo "<pre style='background: #f8f9fa; padding: 10px; border-radius: 4px;'>";
            print_r( $api_result );
            echo "</pre>";
        } else {
            echo "<p style='color: red;'><strong>❌ Plugin API Method:</strong> Failed</p>";
        }
        echo "</div>";
    }

    /**
     * Debug function to check cron status
     * Add this temporarily to your settings page for testing
     */
    public function debug_cron_status() {
        echo "<div style='background: #f0f0f0; padding: 15px; margin: 20px 0; border-radius: 4px;'>";
        echo "<h3>🔍 Cron Debug Information</h3>";
        // Check if cron is scheduled
        $next_run = wp_next_scheduled( 'mpt_auto_update_services' );
        if ( $next_run ) {
            echo "<p><strong>✅ Auto Update Cron:</strong> Scheduled</p>";
            echo "<p><strong>⏰ Next Run:</strong> " . date( 'F j, Y, g:i a', $next_run ) . " (" . human_time_diff( $next_run ) . ")</p>";
        } else {
            echo "<p><strong>❌ Auto Update Cron:</strong> Not scheduled</p>";
        }
        // Check current setting
        $options = get_option( 'mass-ping-tool-for-seo' );
        $auto_update = ( isset( $options['auto_update_services'] ) ? $options['auto_update_services'] : 'Not set' );
        echo "<p><strong>📋 Current Setting:</strong> {$auto_update}</p>";
        // Show all Mass Ping related crons
        $crons = _get_cron_array();
        echo "<p><strong>📅 All MPT Crons:</strong></p><ul>";
        foreach ( $crons as $time => $cron ) {
            foreach ( $cron as $hook => $details ) {
                if ( strpos( $hook, 'mpt' ) !== false ) {
                    echo "<li>{$hook} - " . date( 'F j, Y, g:i a', $time ) . "</li>";
                }
            }
        }
        echo "</ul>";
        // Check if premium
        $is_premium = ( mpt__fs()->can_use_premium_code__premium_only() ? 'Yes' : 'No' );
        echo "<p><strong>💎 Premium Status:</strong> {$is_premium}</p>";
        echo "</div>";
    }

    /**
     * Manual cron trigger for testing
     */
    public function trigger_cron_manually() {
        echo "<div class='notice notice-error'><p>Premium required for auto-update</p></div>";
        return;
        echo "<div class='notice notice-info'><p>🚀 Manually triggering auto-update...</p></div>";
        // Log before
        $before = get_option( 'mpt-last-update' );
        // Trigger the function
        $this->auto_update_services();
        // Log after
        $after = get_option( 'mpt-last-update' );
        if ( $after > $before ) {
            echo "<div class='notice notice-success'><p>✅ Auto-update successful! Updated from " . date( 'g:i a', $before ) . " to " . date( 'g:i a', $after ) . "</p></div>";
        } else {
            echo "<div class='notice notice-warning'><p>⚠️ Auto-update may have failed - no timestamp change</p></div>";
        }
    }

}
