<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-review-responder.php
// Description: AI draft generation and reply posting for Review Responder module - NUCLEAR+++
// Last Edited: 2026-05-17
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

final class ReviewResponder
{
    // Google Business Profile reply endpoint (v4)
    private const REPLY_API = 'https://mybusiness.googleapis.com/v4';

    // --------------------------------------------------
    // Public: register AJAX hooks
    // --------------------------------------------------
    public static function init(): void
    {
        add_action('wp_ajax_amai_review_generate_draft',   [self::class, 'ajaxGenerateDraft']);
        add_action('wp_ajax_amai_review_post_reply',       [self::class, 'ajaxPostReply']);
        add_action('wp_ajax_amai_review_ignore',           [self::class, 'ajaxIgnore']);
        add_action('wp_ajax_amai_review_save_settings',    [self::class, 'ajaxSaveSettings']);
    }

    // --------------------------------------------------
    // Public: generate an AI draft for a review row
    // Returns the draft string or null on failure
    // --------------------------------------------------
    public static function generateDraft(int $rowId): ?string
    {
        global $wpdb;

        $table = $wpdb->prefix . 'amai_reviews';
        $row   = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM {$table} WHERE id = %d LIMIT 1", $rowId),
            ARRAY_A
        );

        if (!is_array($row)) {
            return null;
        }

        $businessName = self::getBusinessName();
        $tone         = (string) get_option('amai_review_reply_tone', 'professional');
        $stars        = (int) $row['star_rating'];
        $reviewerName = (string) $row['reviewer_name'];
        $comment      = isset($row['comment']) ? (string) $row['comment'] : '';

        $toneGuide = match ($tone) {
            'warm'     => 'warm and appreciative',
            'friendly' => 'friendly and conversational',
            default    => 'professional and courteous',
        };

        if ($comment !== '') {
            $prompt = "You are writing a Google Business Profile review response on behalf of {$businessName}. "
                . "The reviewer left a {$stars}-star review. Their name is {$reviewerName}. "
                . "Their review says: \"{$comment}\". "
                . "Write a {$toneGuide} response that: acknowledges their specific feedback, thanks them by first name if appropriate, "
                . "addresses any concerns raised (if negative), and invites them back if positive. "
                . "Keep it under 150 words. Do not use generic filler phrases. "
                . "Do not invent services or features the business does not mention. "
                . "Return only the response text with no preamble.";
        } else {
            $prompt = "You are writing a Google Business Profile review response on behalf of {$businessName}. "
                . "The reviewer left a {$stars}-star rating with no written comment. Their name is {$reviewerName}. "
                . "Write a {$toneGuide} response that thanks them for taking the time to leave a rating. "
                . "Keep it under 80 words. Do not use generic filler phrases. "
                . "Return only the response text with no preamble.";
        }

        $draft = self::callAi($prompt);
        if ($draft === null || $draft === '') {
            return null;
        }

        $draft = trim($draft);

        // Store the draft
        $wpdb->update(
            $table,
            ['ai_draft' => $draft],
            ['id' => $rowId],
            ['%s'],
            ['%d']
        );

        return $draft;
    }

    // --------------------------------------------------
    // Public: post a reply to Google and mark as replied
    // --------------------------------------------------
    public static function postReply(int $rowId, string $replyText, string $accessToken, string $locationId): bool
    {
        global $wpdb;

        $table = $wpdb->prefix . 'amai_reviews';
        $row   = $wpdb->get_row(
            $wpdb->prepare("SELECT review_id FROM {$table} WHERE id = %d LIMIT 1", $rowId),
            ARRAY_A
        );

        if (!is_array($row) || ($row['review_id'] ?? '') === '') {
            return false;
        }

        $url = self::REPLY_API . '/' . $locationId . '/reviews/' . rawurlencode($row['review_id']) . '/reply';

        $response = wp_remote_request($url, [
            'method'  => 'PUT',
            'timeout' => 20,
            'headers' => [
                'Authorization' => 'Bearer ' . $accessToken,
                'Content-Type'  => 'application/json',
            ],
            'body'    => wp_json_encode(['comment' => $replyText]),
        ]);

        if (is_wp_error($response)) {
            return false;
        }

        $httpCode = (int) wp_remote_retrieve_response_code($response);
        if ($httpCode < 200 || $httpCode >= 300) {
            return false;
        }

        $wpdb->update(
            $table,
            [
                'reply_text' => $replyText,
                'replied_at' => gmdate('Y-m-d H:i:s'),
                'status'     => 'replied',
            ],
            ['id' => $rowId],
            ['%s', '%s', '%s'],
            ['%d']
        );

        return true;
    }

    // --------------------------------------------------
    // AJAX: generate AI draft for a review
    // --------------------------------------------------
    public static function ajaxGenerateDraft(): void
    {
        check_ajax_referer('amai_review_nonce', '_wpnonce');

        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized.'], 403);
        }

        $rowId = isset($_POST['review_id']) ? (int) $_POST['review_id'] : 0;
        if ($rowId <= 0) {
            wp_send_json_error(['message' => 'Invalid review ID.'], 400);
        }

        $draft = self::generateDraft($rowId);
        if ($draft === null) {
            wp_send_json_error(['message' => 'AI draft generation failed. Check your active AI provider.'], 500);
        }

        wp_send_json_success(['draft' => $draft]);
    }

    // --------------------------------------------------
    // AJAX: post a reply to Google
    // --------------------------------------------------
    public static function ajaxPostReply(): void
    {
        check_ajax_referer('amai_review_nonce', '_wpnonce');

        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized.'], 403);
        }

        $rowId     = isset($_POST['review_id']) ? (int) $_POST['review_id'] : 0;
        $replyText = isset($_POST['reply_text']) ? sanitize_textarea_field(wp_unslash($_POST['reply_text'])) : '';

        if ($rowId <= 0 || $replyText === '') {
            wp_send_json_error(['message' => 'Missing review ID or reply text.'], 400);
        }

        $accessToken = GoogleAuth::getAccessToken();
        $locationId  = GoogleAuth::getLocationId();

        if ($accessToken === null || $locationId === null) {
            wp_send_json_error(['message' => 'Google Business Profile is not connected.'], 400);
        }

        $posted = self::postReply($rowId, $replyText, $accessToken, $locationId);
        if (!$posted) {
            wp_send_json_error(['message' => 'Failed to post reply to Google. Please try again.'], 500);
        }

        wp_send_json_success(['message' => 'Reply posted successfully.']);
    }

    // --------------------------------------------------
    // AJAX: ignore a review
    // --------------------------------------------------
    public static function ajaxIgnore(): void
    {
        check_ajax_referer('amai_review_nonce', '_wpnonce');

        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized.'], 403);
        }

        $rowId = isset($_POST['review_id']) ? (int) $_POST['review_id'] : 0;
        if ($rowId <= 0) {
            wp_send_json_error(['message' => 'Invalid review ID.'], 400);
        }

        global $wpdb;
        $wpdb->update(
            $wpdb->prefix . 'amai_reviews',
            ['status' => 'ignored'],
            ['id' => $rowId],
            ['%s'],
            ['%d']
        );

        wp_send_json_success(['message' => 'Review ignored.']);
    }

    // --------------------------------------------------
    // AJAX: save reply mode and tone settings
    // --------------------------------------------------
    public static function ajaxSaveSettings(): void
    {
        check_ajax_referer('amai_review_settings_nonce', '_wpnonce');

        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized.'], 403);
        }

        $mode = isset($_POST['reply_mode']) ? sanitize_key($_POST['reply_mode']) : '';
        $tone = isset($_POST['reply_tone']) ? sanitize_key($_POST['reply_tone']) : '';

        $validModes = ['manual', 'ai_assisted', 'autopilot'];
        $validTones = ['professional', 'warm', 'friendly'];

        if (!in_array($mode, $validModes, true) || !in_array($tone, $validTones, true)) {
            wp_send_json_error(['message' => 'Invalid settings values.'], 400);
        }

        update_option('amai_review_reply_mode', $mode);
        update_option('amai_review_reply_tone', $tone);

        wp_send_json_success(['message' => 'Settings saved.']);
    }

    // --------------------------------------------------
    // Private: call the active AI provider
    // --------------------------------------------------
    private static function callAi(string $prompt): ?string
    {
        $activeProvider = (string) get_option('amai_active_ai_provider', '');
        if ($activeProvider === '') {
            return null;
        }

        $moduleFile = AMAI_PLUGIN_DIR . 'modules/' . $activeProvider . '.php';
        if (!is_file($moduleFile)) {
            return null;
        }

        require_once $moduleFile;

        $suffix    = str_replace('-', '', ucwords(substr($activeProvider, 3), '-'));
        $className = 'AutoMarketerAI\\Modules\\' . $suffix;

        if (!class_exists($className)) {
            return null;
        }

        $module  = new $className();
        $apiKey  = KeyVault::decrypt((string) get_option('amai_api_key_' . $activeProvider, ''));
        $model   = $module->get_default_model();
        $result  = $module->generate_raw($prompt, $apiKey, $model, 512);

        return $result !== '' ? $result : null;
    }

    // --------------------------------------------------
    // Private: get the business name from Google connection
    // --------------------------------------------------
    private static function getBusinessName(): string
    {
        $conn = GoogleAuth::getConnection();
        if (is_array($conn) && isset($conn['business_name']) && $conn['business_name'] !== '') {
            return $conn['business_name'];
        }
        return (string) get_option('blogname', 'our business');
    }
}