<?php

namespace App\Http\Controllers\Creator;

use App\Http\Controllers\Controller;
use App\Models\AutoReplySetting;
use App\Models\AutoReplySuggestion;
use App\Models\SocialComment;
use App\Models\SocialPost;
use App\Services\ProfanityFilterService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class AutoReplyController extends Controller
{
    /**
     * Display the auto-reply settings page.
     */
    public function settings()
    {
        $user = Auth::user();
        
        // Get or create auto-reply settings for this creator
        $settings = AutoReplySetting::firstOrCreate(
            ['creator_id' => $user->id],
            [
                'enabled' => false,
                'preferred_tone' => 'casual',
                'confidence_threshold' => 80.00,
                'auto_approve_high_confidence' => false,
                'auto_approve_confidence_threshold' => 95.00,
                'rule_based_triggers' => [],
                'excluded_keywords' => [],
                'creator_guidelines' => [],
            ]
        );
        
        return view('creator.auto-replies.settings', compact('settings'));
    }
    
    /**
     * Update auto-reply settings.
     */
    public function updateSettings(Request $request)
    {
        $user = Auth::user();
        
        // Validate request
        $request->validate([
            'enabled' => 'boolean',
            'preferred_tone' => 'required|string|in:casual,friendly,humorous',
            'confidence_threshold' => 'required|numeric|min:0|max:100',
            'auto_approve_high_confidence' => 'boolean',
            'auto_approve_confidence_threshold' => 'required_if:auto_approve_high_confidence,1|numeric|min:0|max:100',
            'excluded_keywords' => 'nullable|array',
            'excluded_keywords.*' => 'string|max:50',
            'creator_guidelines' => 'nullable|array',
            'creator_guidelines.*' => 'string|max:500',
            'exclude_users' => 'nullable|array',
            'exclude_users.*' => 'string|max:50',
            'exclude_mentions' => 'boolean',
            'auto_reply_faq' => 'boolean',
        ]);
        
        // Get or create auto-reply settings for this creator
        $settings = AutoReplySetting::firstOrCreate(
            ['creator_id' => $user->id]
        );
        
        // Prepare rule-based triggers
        $ruleBasedTriggers = [
            'exclude_users' => $request->exclude_users ?? [],
            'exclude_mentions' => $request->boolean('exclude_mentions'),
            'auto_reply_faq' => $request->boolean('auto_reply_faq'),
        ];
        
        // Update settings
        $settings->update([
            'enabled' => $request->boolean('enabled'),
            'preferred_tone' => $request->preferred_tone,
            'confidence_threshold' => $request->confidence_threshold,
            'auto_approve_high_confidence' => $request->boolean('auto_approve_high_confidence'),
            'auto_approve_confidence_threshold' => $request->auto_approve_confidence_threshold ?? 95.00,
            'excluded_keywords' => $request->excluded_keywords ?? [],
            'creator_guidelines' => $request->creator_guidelines ?? [],
            'rule_based_triggers' => $ruleBasedTriggers,
        ]);
        
        return redirect()->back()->with('success', 'Auto-reply settings updated successfully!');
    }
    
    /**
     * Display the auto-reply moderation panel.
     */
    public function index()
    {
        $user = Auth::user();
        
        // Get auto-reply settings
        $settings = AutoReplySetting::where('creator_id', $user->id)->first();
        
        if (!$settings || !$settings->enabled) {
            return redirect()->route('creator.auto-replies.settings')
                ->with('info', 'Please enable auto-reply feature first.');
        }
        
        // Get pending suggestions (not approved and not posted)
        $pendingSuggestions = AutoReplySuggestion::where('creator_id', $user->id)
            ->where('is_approved', false)
            ->where('is_posted', false)
            ->with(['socialComment', 'socialComment.socialPost', 'socialComment.socialAccount'])
            ->orderBy('created_at', 'desc')
            ->paginate(20);
        
        return view('creator.auto-replies.index', compact('pendingSuggestions', 'settings'));
    }
    
    /**
     * Display approved suggestions.
     */
    public function approved()
    {
        $user = Auth::user();
        
        // Get approved suggestions
        $approvedSuggestions = AutoReplySuggestion::where('creator_id', $user->id)
            ->where('is_approved', true)
            ->where('is_posted', false)
            ->with(['socialComment', 'socialComment.socialPost', 'socialComment.socialAccount'])
            ->orderBy('created_at', 'desc')
            ->paginate(20);
        
        return view('creator.auto-replies.approved', compact('approvedSuggestions'));
    }
    
    /**
     * Display posted suggestions.
     */
    public function posted()
    {
        $user = Auth::user();
        
        // Get posted suggestions
        $postedSuggestions = AutoReplySuggestion::where('creator_id', $user->id)
            ->where('is_posted', true)
            ->with(['socialComment', 'socialComment.socialPost', 'socialComment.socialAccount'])
            ->orderBy('posted_at', 'desc')
            ->paginate(20);
        
        return view('creator.auto-replies.posted', compact('postedSuggestions'));
    }
    
    /**
     * Approve an auto-reply suggestion.
     */
    public function approve($id)
    {
        $user = Auth::user();
        
        $suggestion = AutoReplySuggestion::where('creator_id', $user->id)->findOrFail($id);
        
        // Update suggestion status
        $suggestion->update([
            'is_approved' => true,
        ]);
        
        return redirect()->back()->with('success', 'Auto-reply suggestion approved!');
    }
    
    /**
     * Edit an auto-reply suggestion.
     */
    public function edit($id, Request $request)
    {
        $user = Auth::user();
        
        $suggestion = AutoReplySuggestion::where('creator_id', $user->id)->findOrFail($id);
        
        // Validate request
        $request->validate([
            'suggested_reply' => 'required|string|max:500',
        ]);
        
        // Update suggestion
        $suggestion->update([
            'suggested_reply' => $request->suggested_reply,
            'is_approved' => true, // Auto-approve when edited
        ]);
        
        return redirect()->back()->with('success', 'Auto-reply suggestion updated and approved!');
    }
    
    /**
     * Post an approved auto-reply suggestion.
     */
    public function post($id)
    {
        $user = Auth::user();
        
        $suggestion = AutoReplySuggestion::where('creator_id', $user->id)->findOrFail($id);
        
        // Check if already posted
        if ($suggestion->is_posted) {
            return redirect()->back()->with('error', 'This reply has already been posted.');
        }
        
        // Check if approved
        if (!$suggestion->is_approved) {
            return redirect()->back()->with('error', 'This reply needs to be approved first.');
        }
        
        // In a real implementation, this would post to the social media platform
        // For now, we'll just mark it as posted
        try {
            // Simulate posting to social media
            $this->postToSocialMedia($suggestion);
            
            // Update suggestion status
            $suggestion->update([
                'is_posted' => true,
                'posted_at' => now(),
            ]);
            
            return redirect()->back()->with('success', 'Auto-reply posted successfully!');
        } catch (\Exception $e) {
            Log::error("Failed to post auto-reply: " . $e->getMessage());
            return redirect()->back()->with('error', 'Failed to post auto-reply. Please try again.');
        }
    }
    
    /**
     * Simulate posting to social media.
     *
     * @param AutoReplySuggestion $suggestion
     * @return void
     */
    protected function postToSocialMedia($suggestion)
    {
        // In a real implementation, this would:
        // 1. Get the social account for the comment
        // 2. Use the appropriate provider to post the reply
        // 3. Handle any errors or rate limits
        
        // Get creator settings
        $settings = AutoReplySetting::where('creator_id', $suggestion->creator_id)->first();
        
        // Initialize profanity filter
        $profanityFilter = new ProfanityFilterService();
        
        // Set creator-specific words if available
        if (!empty($settings->creator_guidelines)) {
            // Extract creator-specific words from guidelines
            $creatorWords = [];
            foreach ($settings->creator_guidelines as $guideline) {
                // Simple extraction - in a real implementation, this would be more sophisticated
                $words = explode(' ', strtolower($guideline));
                foreach ($words as $word) {
                    $word = trim($word, '.,!?;:"');
                    if (strlen($word) > 3) { // Only consider words longer than 3 characters
                        $creatorWords[] = $word;
                    }
                }
            }
            $profanityFilter->setBrandSpecificWords(array_unique($creatorWords));
        }
        
        // Check if reply contains profanity
        if ($profanityFilter->hasProfanity($suggestion->suggested_reply)) {
            throw new \Exception("Auto-reply contains profanity or creator-sensitive content");
        }
        
        // For now, we'll just simulate the process
        sleep(1); // Simulate API call delay
        
        // Log the action
        Log::info("Posted auto-reply to social media", [
            'suggestion_id' => $suggestion->id,
            'comment_id' => $suggestion->socialComment->id,
            'reply_content' => $suggestion->suggested_reply,
        ]);
    }
    
    /**
     * Skip an auto-reply suggestion.
     */
    public function skip($id)
    {
        $user = Auth::user();
        
        $suggestion = AutoReplySuggestion::where('creator_id', $user->id)->findOrFail($id);
        
        // Delete the suggestion (skip it)
        $suggestion->delete();
        
        return redirect()->back()->with('success', 'Auto-reply suggestion skipped.');
    }
    
    /**
     * Favorite an auto-reply suggestion.
     */
    public function favorite($id)
    {
        $user = Auth::user();
        
        $suggestion = AutoReplySuggestion::where('creator_id', $user->id)->findOrFail($id);
        
        // Update suggestion status
        $suggestion->update([
            'is_approved' => true, // Auto-approve when favorited
        ]);
        
        return redirect()->back()->with('success', 'Auto-reply suggestion favorited!');
    }
}