<?php
/**
 * ================================================================
 * DRIPBOX LINK CHECKER - AJAX ENDPOINTS (UPDATED FOR AUTOMATION)
 * ================================================================
 */

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

class DripBox_Link_Checker_AJAX {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        // Start scan
        add_action('wp_ajax_dripbox_start_scan', [$this, 'start_scan']);
        
        // Check single link (batch processing)
        add_action('wp_ajax_dripbox_check_link', [$this, 'check_link']);
        
        // Get scan status
        add_action('wp_ajax_dripbox_get_scan_status', [$this, 'get_scan_status']);
        
        // Clear results
        add_action('wp_ajax_dripbox_clear_results', [$this, 'clear_results']);
        
        // Save scan results to database
        add_action('wp_ajax_dripbox_save_results', [$this, 'save_results']);
        
        // Recheck single link
        add_action('wp_ajax_dripbox_recheck_single', [$this, 'recheck_single']);

        // === NOVO: Save Automation Settings ===
        add_action('wp_ajax_dripbox_save_automation_settings', [$this, 'save_automation_settings']);
    }
    
    /**
     * Start scan - Find all links
     */
    public function start_scan() {
        check_ajax_referer('dripbox_link_checker', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized'], 403);
        }
        
        $scanner = DripBox_Link_Checker_Scanner::get_instance();
        $links = $scanner->find_all_links();
        
        set_transient('dripbox_scan_links', $links, HOUR_IN_SECONDS);
        set_transient('dripbox_scan_start_time', time(), HOUR_IN_SECONDS);
        
        wp_send_json_success([
            'total_links' => count($links),
            'links' => $links,
            'message' => 'Found ' . count($links) . ' links to check'
        ]);
    }
    
    /**
     * Check single link
     */
    public function check_link() {
        check_ajax_referer('dripbox_link_checker', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized'], 403);
        }
        
        $url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        $post_title = isset($_POST['post_title']) ? sanitize_text_field($_POST['post_title']) : '';
        $post_url = isset($_POST['post_url']) ? esc_url_raw($_POST['post_url']) : '';
        
        if (empty($url)) {
            wp_send_json_error(['message' => 'Invalid URL'], 400);
        }
        
        $license_key = get_option('dripbox_license_key', '');
        $current_domain = parse_url(get_site_url(), PHP_URL_HOST);
        $is_server = ($current_domain === 'getdripbox.com');
        
        if ($is_server) {
            if (!function_exists('dripbox_server_verify_link')) {
                wp_send_json_error(['message' => 'Server function not found', 'status' => 'error'], 500);
            }
            $body = dripbox_server_verify_link($url);
        } else {
            if (empty($license_key)) {
                wp_send_json_error(['message' => 'License key missing', 'status' => 'error'], 400);
            }
            
            $response = wp_remote_post('https://getdripbox.com/wp-json/dripbox/v1/check-link', [
                'timeout' => 15,
                'headers' => ['Content-Type' => 'application/json'],
                'body' => json_encode(['license_key' => $license_key, 'url' => $url])
            ]);
            
            if (is_wp_error($response)) {
                wp_send_json_error(['message' => 'Connection error: ' . $response->get_error_message(), 'status' => 'error'], 500);
            }
            
            $body = json_decode(wp_remote_retrieve_body($response), true);
            if (isset($body['code']) && $body['code'] === 'forbidden') {
                wp_send_json_error(['message' => 'License validation failed', 'status' => 'error'], 403);
            }
        }
        
        $result = array_merge($body, [
            'post_id' => $post_id,
            'post_title' => $post_title,
            'post_url' => $post_url,
            'url' => $url
        ]);
        
        wp_send_json_success($result);
    }

    public function get_scan_status() {
        check_ajax_referer('dripbox_link_checker', 'nonce');
        if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Unauthorized'], 403);
        $db = DripBox_Link_Checker_DB::get_instance();
        wp_send_json_success($db->get_results());
    }

    public function clear_results() {
        check_ajax_referer('dripbox_link_checker', 'nonce');
        if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Unauthorized'], 403);
        
        $db = DripBox_Link_Checker_DB::get_instance();
        $db->clear_results();
        delete_transient('dripbox_scan_links');
        delete_transient('dripbox_scan_start_time');
        
        wp_send_json_success(['message' => 'Results cleared']);
    }

    public function save_results() {
        check_ajax_referer('dripbox_link_checker', 'nonce');
        if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Unauthorized'], 403);
        
        $results_json = isset($_POST['results']) ? $_POST['results'] : '';
        $duration = isset($_POST['duration']) ? intval($_POST['duration']) : 0;
        
        if (empty($results_json)) wp_send_json_error(['message' => 'No results'], 400);
        $results = json_decode(stripslashes($results_json), true);
        if (!is_array($results)) wp_send_json_error(['message' => 'Invalid format'], 400);
        
        $db = DripBox_Link_Checker_DB::get_instance();
        $db->save_results($results);
        $db->update_scan_duration($duration);
        
        wp_send_json_success(['message' => 'Saved']);
    }

    public function recheck_single() {
        check_ajax_referer('dripbox_link_checker', 'nonce');
        if (!current_user_can('manage_options')) wp_send_json_error(['message' => 'Unauthorized'], 403);
        
        $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        $post_title = isset($_POST['post_title']) ? sanitize_text_field($_POST['post_title']) : '';
        $post_url = isset($_POST['post_url']) ? esc_url_raw($_POST['post_url']) : '';
        $old_url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
        
        if (empty($post_id)) wp_send_json_error(['message' => 'Invalid post ID'], 400);
        
        $scanner = DripBox_Link_Checker_Scanner::get_instance();
        $post_links = $scanner->extract_links_from_post($post_id);
        
        $current_url = null;
        foreach ($post_links as $link) {
            if ($link['url'] === $old_url) {
                $current_url = $link['url'];
                break;
            }
        }
        if (empty($current_url) && !empty($post_links)) $current_url = $post_links[0]['url'];
        if (empty($current_url)) wp_send_json_error(['message' => 'No link found'], 400);
        
        $current_domain = parse_url(get_site_url(), PHP_URL_HOST);
        $is_server = ($current_domain === 'getdripbox.com');
        
        if ($is_server) {
            if (!function_exists('dripbox_server_verify_link')) wp_send_json_error(['message' => 'Server error'], 500);
            $body = dripbox_server_verify_link($current_url);
        } else {
            $license_key = get_option('dripbox_license_key', '');
            if (empty($license_key)) wp_send_json_error(['message' => 'License missing'], 400);
            
            $response = wp_remote_post('https://getdripbox.com/wp-json/dripbox/v1/check-link', [
                'timeout' => 15, 'headers' => ['Content-Type' => 'application/json'],
                'body' => json_encode(['license_key' => $license_key, 'url' => $current_url])
            ]);
            
            if (is_wp_error($response)) wp_send_json_error(['message' => 'Connection error'], 500);
            $body = json_decode(wp_remote_retrieve_body($response), true);
        }
        
        $db = DripBox_Link_Checker_DB::get_instance();
        $all_data = $db->get_results();
        $results = $all_data['results'];
        $updated = false;
        
        foreach ($results as $key => $result) {
            if ($result['url'] === $old_url || $result['post_id'] === $post_id) {
                $results[$key] = array_merge($body, [
                    'post_id' => $post_id, 'post_title' => $post_title,
                    'post_url' => $post_url, 'url' => $current_url
                ]);
                $updated = true;
                break;
            }
        }
        
        if (!$updated) {
            $results[] = array_merge($body, [
                'post_id' => $post_id, 'post_title' => $post_title,
                'post_url' => $post_url, 'url' => $current_url
            ]);
        }
        
        $db->save_results($results);
        
        $result = array_merge($body, [
            'post_id' => $post_id, 'post_title' => $post_title,
            'post_url' => $post_url, 'url' => $current_url,
            'url_changed' => ($current_url !== $old_url)
        ]);
        
        wp_send_json_success($result);
    }

    /**
     * === NOVO: SAVE AUTOMATION SETTINGS ===
     * Salva as opções dos toggles e agenda o Cron Job
     */
    public function save_automation_settings() {
        check_ajax_referer('dripbox_link_checker', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized'], 403);
        }
        
        $setting = isset($_POST['setting']) ? sanitize_text_field($_POST['setting']) : '';
        $value = isset($_POST['value']) ? intval($_POST['value']) : 0;
        
        if ($setting === 'scan') {
            update_option('dripbox_auto_scan_enabled', $value);
            
            // Agenda ou remove o Cron
            if ($value === 1) {
                if (!wp_next_scheduled('dripbox_weekly_scan_event')) {
                    wp_schedule_event(time(), 'weekly', 'dripbox_weekly_scan_event');
                }
            } else {
                $timestamp = wp_next_scheduled('dripbox_weekly_scan_event');
                if ($timestamp) {
                    wp_unschedule_event($timestamp, 'dripbox_weekly_scan_event');
                }
            }
        } elseif ($setting === 'email') {
            update_option('dripbox_email_alerts_enabled', $value);
        }
        
        wp_send_json_success(['message' => 'Settings saved']);
    }

}