<?php

namespace App\Http\Controllers;

use App\Models\SupportMessage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class SupportController extends Controller
{
    // ── User sends a text message ─────────────────────────────
    public function send(Request $request)
    {
        $request->validate(['message' => 'required|string|max:2000']);

        SupportMessage::create([
            'user_id'      => Auth::id(),
            'sender'       => 'user',
            'message'      => $request->message,
            'message_type' => 'text',
            'is_read'      => false,
        ]);

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

    // ── User uploads image or voice ───────────────────────────
    public function upload(Request $request)
    {
        $type = $request->input('type', 'image'); // image | voice

        if ($type === 'image') {
            $request->validate(['file' => 'required|image|max:5120']); // 5MB
            $path = $request->file('file')->store('chat/images', 'public');
        } else {
            $request->validate(['file' => 'required|file|mimes:webm,ogg,mp3,wav|max:10240']); // 10MB
            $ext  = $request->file('file')->getClientOriginalExtension() ?: 'webm';
            $name = Str::uuid() . '.' . $ext;
            $path = $request->file('file')->storeAs('chat/voices', $name, 'public');
        }

        $caption = $request->input('caption', '');

        SupportMessage::create([
            'user_id'      => Auth::id(),
            'sender'       => 'user',
            'message'      => $caption ?: ($type === 'image' ? '📷 Image' : '🎤 Voice message'),
            'message_type' => $type,
            'file_path'    => $path,
            'is_read'      => false,
        ]);

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

    // ── User fetches their chat history ───────────────────────
    public function messages()
    {
        $messages = SupportMessage::where('user_id', Auth::id())
            ->orderBy('created_at')
            ->get()
            ->map(fn($m) => [
                'id'           => $m->id,
                'sender'       => $m->sender,        // user | admin | system
                'message'      => $m->message,
                'message_type' => $m->message_type ?? 'text',  // text | image | voice | system
                'file_url'     => $m->fileUrl(),
                'agent_name'   => $m->agent_name,
                'created_at'   => $m->created_at->format('d M H:i'),
            ]);

        // Mark admin messages as read (not system)
        SupportMessage::where('user_id', Auth::id())
            ->where('sender', 'admin')
            ->where('is_read', false)
            ->update(['is_read' => true]);

        $unread = 0; // after marking read above, unread is 0

        return response()->json(['messages' => $messages, 'unread' => $unread]);
    }

    // ── Unread count badge ────────────────────────────────────
    public function unread()
    {
        $count = SupportMessage::where('user_id', Auth::id())
            ->where('sender', 'admin')
            ->where('is_read', false)
            ->count();

        return response()->json(['count' => $count]);
    }
}
