<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\DevMessage;
use Illuminate\Support\Facades\Auth;

class DevChatController extends Controller
{
    public function index()
    {
        // Fetch all messages in ascending order so the oldest is at the top, newest at bottom
        $messages = DevMessage::with('user')->orderBy('created_at', 'asc')->get();
        return view('admin.developer.dev_chat', compact('messages'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'message' => 'nullable|string',
            'attachment' => 'nullable|file|max:10240' // 10MB max
        ]);

        if (!$request->message && !$request->hasFile('attachment')) {
            return redirect()->back()->with('error', 'Please enter a message or attach a file.');
        }

        $user = Auth::user();
        $message = new DevMessage();
        $message->message = $request->message ?? '';

        if ($user && ($user->hasRole('dev') || $user->email === 'dev@americanplastic.lk')) {
            $message->user_id = $user->id;
            $message->sender_name = 'DEV';
        } else {
            // For the admin side
            $message->user_id = $user->id ?? null;
            $message->sender_name = $user ? $user->name : 'System Admin';
        }

        if ($request->hasFile('attachment')) {
            $file = $request->file('attachment');
            $filename = time() . '_' . $file->getClientOriginalName();
            
            // Ensure the directory exists
            $destinationPath = public_path('uploads/dev_chats');
            if (!file_exists($destinationPath)) {
                mkdir($destinationPath, 0777, true);
            }

            // Move directly to the public/uploads/dev_chats directory
            $file->move($destinationPath, $filename);
            
            $message->file_path = 'uploads/dev_chats/' . $filename;
            $message->file_original_name = $file->getClientOriginalName();
        }

        $message->save();

        return redirect()->back()->with('success', 'Message sent.');
    }
}
