<?php

namespace App\Http\Controllers\Admin\Marketing\Tool;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CommunicationLog;
use App\Http\Requests\StoreCommunicationLogRequest;
use App\Models\Task;
use App\Http\Requests\StoreTaskRequest;
use App\Models\Sentiment;
use App\Http\Requests\StoreSentimentRequest;
use App\Models\ChatMessage;
use App\Models\User;

class ToolController extends Controller
{
    public function index()
    {
        return view('admin.marketing.tool.index');
    }

    public function communicationLog()
    {
        $logs = CommunicationLog::with(['merchant', 'loggedBy'])->latest()->paginate(15);
        return view('admin.marketing.tool.communicationLog', compact('logs'));
    }

    public function createCommunicationLog()
    {
        $merchants = User::where('role', 'seller')->get();
        return view('admin.marketing.tool.createCommunicationLog', compact('merchants'));
    }

    public function storeCommunicationLog(StoreCommunicationLogRequest $request)
    {
        $data = $request->validated();
        $data['logged_by'] = auth()->id();
        CommunicationLog::create($data);

        return redirect()->route('admin.marketing.communication-log')->with('success', 'Communication log created successfully.');
    }

    public function editCommunicationLog(CommunicationLog $log)
    {
        $merchants = User::where('role', 'seller')->get();
        return view('admin.marketing.tool.editCommunicationLog', compact('log', 'merchants'));
    }

    public function updateCommunicationLog(StoreCommunicationLogRequest $request, CommunicationLog $log)
    {
        $data = $request->validated();
        $log->update($data);

        return redirect()->route('admin.marketing.communication-log')->with('success', 'Communication log updated successfully.');
    }

    public function destroyCommunicationLog(CommunicationLog $log)
    {
        $log->delete();

        return redirect()->route('admin.marketing.communication-log')->with('success', 'Communication log deleted successfully.');
    }

    public function taskManager()
    {
        $tasks = Task::with(['assignedTo', 'createdBy'])->latest()->paginate(15);
        return view('admin.marketing.tool.taskManager', compact('tasks'));
    }

    public function createTask()
    {
        $users = User::all();
        return view('admin.marketing.tool.createTask', compact('users'));
    }

    public function storeTask(StoreTaskRequest $request)
    {
        $data = $request->validated();
        $data['created_by'] = auth()->id();
        Task::create($data);

        return redirect()->route('admin.marketing.task-manager')->with('success', 'Task created successfully.');
    }

    public function editTask(Task $task)
    {
        $users = User::all();
        return view('admin.marketing.tool.editTask', compact('task', 'users'));
    }

    public function updateTask(StoreTaskRequest $request, Task $task)
    {
        $data = $request->validated();
        $task->update($data);

        return redirect()->route('admin.marketing.task-manager')->with('success', 'Task updated successfully.');
    }

    public function destroyTask(Task $task)
    {
        $task->delete();

        return redirect()->route('admin.marketing.task-manager')->with('success', 'Task deleted successfully.');
    }

    public function sentimentTracking()
    {
        $sentiments = Sentiment::with('merchant')->latest()->paginate(15);
        return view('admin.marketing.tool.sentimentTracking', compact('sentiments'));
    }

    public function createSentiment()
    {
        $merchants = User::where('role', 'seller')->get();
        return view('admin.marketing.tool.createSentiment', compact('merchants'));
    }

    public function storeSentiment(StoreSentimentRequest $request)
    {
        Sentiment::create($request->validated());
        return redirect()->route('admin.marketing.sentiment-tracking')->with('success', 'Sentiment entry created successfully.');
    }

    public function editSentiment(Sentiment $sentiment)
    {
        $merchants = User::where('role', 'seller')->get();
        return view('admin.marketing.tool.editSentiment', compact('sentiment', 'merchants'));
    }

    public function updateSentiment(StoreSentimentRequest $request, Sentiment $sentiment)
    {
        $sentiment->update($request->validated());
        return redirect()->route('admin.marketing.sentiment-tracking')->with('success', 'Sentiment entry updated successfully.');
    }

    public function destroySentiment(Sentiment $sentiment)
    {
        $sentiment->delete();
        return redirect()->route('admin.marketing.sentiment-tracking')->with('success', 'Sentiment entry deleted successfully.');
    }

    public function liveChat()
    {
        $users = User::where('id', '!=', auth()->id())->get();
        $messages = ChatMessage::with(['sender', 'receiver'])
            ->where('sender_id', auth()->id())
            ->orWhere('receiver_id', auth()->id())
            ->latest()
            ->take(50)
            ->get()
            ->reverse();
        return view('admin.marketing.tool.liveChat', compact('users', 'messages'));
    }

    public function sendMessage(Request $request)
    {
        $request->validate([
            'receiver_id' => 'required|exists:users,id',
            'message' => 'required|string',
        ]);

        ChatMessage::create([
            'sender_id' => auth()->id(),
            'receiver_id' => $request->receiver_id,
            'message' => $request->message,
        ]);

        return redirect()->route('admin.marketing.live-chat')->with('success', 'Message sent successfully.');
    }

    public function getMessages($userId)
    {
        $messages = ChatMessage::with(['sender', 'receiver'])
            ->where(function($query) use ($userId) {
                $query->where('sender_id', auth()->id())
                      ->where('receiver_id', $userId);
            })
            ->orWhere(function($query) use ($userId) {
                $query->where('sender_id', $userId)
                      ->where('receiver_id', auth()->id());
            })
            ->orderBy('created_at', 'asc')
            ->get();

        // Mark messages as read
        ChatMessage::where('receiver_id', auth()->id())
            ->where('sender_id', $userId)
            ->where('is_read', false)
            ->update(['is_read' => true]);

        return response()->json($messages);
    }
}
