<?php

namespace App\Http\Controllers;

use App\Models\Conversation;
use App\Models\Message;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Netflie\WhatsAppCloudApi\WhatsAppCloudApi;

class InboxController extends Controller
{
    /**
     * GET /inbox  or  GET /inbox/{conversation}
     */
    public function index(Request $request, ?Conversation $conversation = null)
    {
        $user   = Auth::user();
        $filter = $request->query('filter', 'all');

        $conversations = Conversation::where('user_id', $user->id)
            ->when($filter === 'new',    fn($q) => $q->where('status', 'new'))
            ->when($filter === 'closed', fn($q) => $q->where('status', 'closed'))
            ->when($filter === 'open',   fn($q) => $q->where('status', 'open'))
            ->orderByDesc('last_message_at')
            ->get();

        $messages = collect();

        if ($conversation) {
            // Ensure it belongs to this user
            abort_if($conversation->user_id !== $user->id, 403);

            // Mark as read
            $conversation->update(['unread_count' => 0]);

            $messages = Message::where('conversation_id', $conversation->id)
                ->orderBy('created_at')
                ->get();
        }

        $pusherKey     = Setting::get('pusher_app_key', '');
        $pusherCluster = Setting::get('pusher_app_cluster', 'mt1');
        $waConnected   = !empty($user->access_token) && !empty($user->phone_number_id) && !empty($user->waba_id);
        $appLogo       = Setting::get('app_logo', '');
        $appName       = Setting::get('project_name', 'Inbox');
        $hasLogo       = $appLogo && file_exists(public_path('uploads/' . $appLogo));
        $logoUrl       = $hasLogo ? asset('uploads/' . $appLogo) : '';

        return view('user.inbox', compact(
            'user', 'conversations', 'conversation', 'messages',
            'filter', 'pusherKey', 'pusherCluster',
            'waConnected', 'logoUrl', 'appName'
        ));
    }

    /**
     * POST /inbox/{conversation}/send
     */
    public function send(Request $request, Conversation $conversation)
    {
        $user = Auth::user();
        abort_if($conversation->user_id !== $user->id, 403);

        $request->validate(['message' => ['required', 'string', 'max:4096']]);

        if (!$user->access_token || !$user->phone_number_id) {
            return back()->with('error', 'WhatsApp not configured. Go to WhatsApp Setup first.');
        }

        try {
            $whatsapp = new WhatsAppCloudApi([
                'from_phone_number_id' => $user->phone_number_id,
                'access_token'         => $user->access_token,
            ]);

            $whatsapp->sendTextMessage($conversation->contact_phone, $request->message);

            Message::create([
                'conversation_id' => $conversation->id,
                'user_id'         => $user->id,
                'direction'       => 'outgoing',
                'type'            => 'text',
                'content'         => $request->message,
                'status'          => 'sent',
            ]);

            $conversation->update([
                'last_message'    => $request->message,
                'last_message_at' => now(),
                'status'          => 'open',
            ]);

        } catch (\Throwable $e) {
            Log::error('Inbox send error', ['conversation' => $conversation->id, 'error' => $e->getMessage()]);
            return back()->with('error', 'Failed to send: ' . $e->getMessage());
        }

        return redirect()->route('user.inbox.conversation', $conversation->id);
    }

    /**
     * PATCH /inbox/{conversation}/status
     */
    public function updateStatus(Request $request, Conversation $conversation)
    {
        $user = Auth::user();
        abort_if($conversation->user_id !== $user->id, 403);

        $request->validate(['status' => ['required', 'in:new,open,closed']]);
        $conversation->update(['status' => $request->status]);

        return back();
    }

    /**
     * PATCH /inbox/{conversation}/label
     */
    public function updateLabel(Request $request, Conversation $conversation)
    {
        $user = Auth::user();
        abort_if($conversation->user_id !== $user->id, 403);

        $conversation->update(['label' => $request->label]);

        return response()->json(['success' => true]);
    }
}
