<?php

namespace App\Http\Controllers;

use App\Models\Chatbot;
use App\Models\ChatbotSession;
use App\Models\ChatbotConversation;
use App\Models\ChatbotIntent;
use App\Models\Device;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ChatbotController extends Controller
{
    public function list()
    {
        $user = Auth::user();
        $user_id = $user->role === 'admin' ? request('user_id', $user->id) : $user->id;

        $chatbots = Chatbot::with(['user', 'device'])
            ->where('user_id', $user_id)
            ->orderBy('priority', 'desc')
            ->paginate(20);

        $devices = Device::where('user_id', $user_id)->get();

        // Calculate statistics
        $totalIntents = Chatbot::where('user_id', $user_id)->sum('intents');
        $activeIntents = Chatbot::where('user_id', $user_id)->where('is_active', true)->count();
        $totalSessions = ChatbotSession::whereHas('chatbot', function($q) use ($user_id) {
            $q->where('user_id', $user_id);
        })->count();
        $totalConversations = ChatbotConversation::whereHas('session.chatbot', function($q) use ($user_id) {
            $q->where('user_id', $user_id);
        })->count();
        // Use total conversations as responses since sender column doesn't exist
        $totalResponses = $totalConversations;

        // Get intents from database
        $intents = ChatbotIntent::whereHas('chatbot', function($q) use ($user_id) {
            $q->where('user_id', $user_id);
        })->with('chatbot')->orderBy('priority', 'desc')->paginate(20);
        
        // Get active sessions for the sessions tab
        $sessions = ChatbotSession::whereHas('chatbot', function($q) use ($user_id) {
            $q->where('user_id', $user_id);
        })->orderBy('updated_at', 'desc')->paginate(20);

        // Get recent responses/conversations for the responses tab
        $responses = ChatbotConversation::with('session')->whereHas('session.chatbot', function($q) use ($user_id) {
            $q->where('user_id', $user_id);
        })->orderBy('created_at', 'desc')->paginate(20);

        return view('chatbot-list', compact('chatbots', 'devices', 'totalIntents', 'activeIntents', 'totalSessions', 'totalConversations', 'totalResponses', 'intents', 'sessions', 'responses'));
    }

    public function show($id)
    {
        $user = Auth::user();
        $chatbot = Chatbot::with(['sessions.conversations'])->findOrFail($id);

        if ($user->role !== 'admin' && $chatbot->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        return view('chatbot.show', compact('chatbot'));
    }

    public function create()
    {
        $user = Auth::user();
        $devices = Device::where('user_id', $user->id)->get();

        return view('chatbot.create', compact('devices'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'sender' => 'required|string',
            'name' => 'required|string|max:255',
            'type' => 'required|in:rule-based,ai,hybrid',
            'description' => 'nullable|string',
            'fallback_message' => 'required|string',
            'is_active' => 'nullable|boolean',
            'priority' => 'nullable|integer',
        ]);

        $user = Auth::user();

        $chatbot = Chatbot::create([
            'user_id' => $user->id,
            'sender' => $request->sender,
            'name' => $request->name,
            'description' => $request->description,
            'type' => $request->type,
            'is_active' => $request->is_active ?? true,
            'fallback_message' => $request->fallback_message,
            'priority' => $request->priority ?? 0,
            'config' => $request->config ? json_decode($request->config, true) : [],
            'intents' => $request->intents ? json_decode($request->intents, true) : [],
        ]);

        return redirect()->route('chatbot.show', $chatbot->id)
            ->with('success_alert', __('Chatbot created successfully'));
    }

    public function update(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:chatbots,id',
            'name' => 'required|string|max:255',
            'type' => 'required|in:rule-based,ai,hybrid',
            'fallback_message' => 'required|string',
        ]);

        $user = Auth::user();
        $chatbot = Chatbot::findOrFail($request->id);

        if ($user->role !== 'admin' && $chatbot->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        $chatbot->update([
            'name' => $request->name,
            'description' => $request->description,
            'type' => $request->type,
            'is_active' => $request->is_active ?? $chatbot->is_active,
            'fallback_message' => $request->fallback_message,
            'priority' => $request->priority ?? $chatbot->priority,
            'config' => $request->config ? json_decode($request->config, true) : $chatbot->config,
            'intents' => $request->intents ? json_decode($request->intents, true) : $chatbot->intents,
        ]);

        return redirect()->back()
            ->with('success_alert', __('Chatbot updated successfully'));
    }

    public function destroy(Request $request)
    {
        $user = Auth::user();
        $chatbot = Chatbot::findOrFail($request->id);

        if ($user->role !== 'admin' && $chatbot->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        $chatbot->delete();

        return redirect()->route('chatbot.list')
            ->with('success_alert', __('Chatbot deleted successfully'));
    }

    public function toggleStatus($id)
    {
        $user = Auth::user();
        $chatbot = Chatbot::findOrFail($id);

        if ($user->role !== 'admin' && $chatbot->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        $chatbot->update(['is_active' => !$chatbot->is_active]);

        return redirect()->back()
            ->with('success_alert', __('Chatbot status updated'));
    }

    public function sessions($id)
    {
        $user = Auth::user();
        $chatbot = Chatbot::findOrFail($id);

        if ($user->role !== 'admin' && $chatbot->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        $sessions = ChatbotSession::where('chatbot_id', $id)
            ->with('conversations')
            ->orderBy('last_activity', 'desc')
            ->paginate(20);

        return view('chatbot.sessions', compact('chatbot', 'sessions'));
    }

    public function clearSessions($id)
    {
        $user = Auth::user();
        $chatbot = Chatbot::findOrFail($id);

        if ($user->role !== 'admin' && $chatbot->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        ChatbotSession::where('chatbot_id', $id)->delete();

        return redirect()->back()
            ->with('success_alert', __('Chatbot sessions cleared successfully'));
    }

    /**
     * Store a new intent for a chatbot
     */
    public function storeIntent(Request $request)
    {
        $validated = $request->validate([
            'chatbot_id' => 'required|exists:chatbots,id',
            'pattern' => 'required|string|max:255',
            'response' => 'required|string',
            'category' => 'nullable|string|max:100',
            'priority' => 'nullable|integer|min:0|max:100',
            'keywords' => 'nullable|array',
        ]);

        $user = Auth::user();
        $chatbot = Chatbot::findOrFail($validated['chatbot_id']);

        // Check authorization
        if ($user->role !== 'admin' && $chatbot->user_id !== $user->id) {
            return back()->with('error', 'Unauthorized to add intents to this chatbot.');
        }

        // Create the intent
        ChatbotIntent::create([
            'chatbot_id' => $validated['chatbot_id'],
            'pattern' => $validated['pattern'],
            'response' => $validated['response'],
            'category' => $validated['category'] ?? 'general',
            'priority' => $validated['priority'] ?? 0,
            'keywords' => $validated['keywords'] ?? [],
            'is_active' => true,
        ]);

        return back()->with('success_alert', 'Intent added successfully!');
    }
}
