<?php

namespace App\Http\Controllers;

use App\Models\SupportTicket;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class SupportTicketController extends Controller
{
    public function index()
    {
        $user = Auth::user();
    
        // Fetch all users for the "Assign To" dropdown
        $users = User::all();
    
        // Fetch tickets based on role
        if ($user->hasRole('Admin')) {
            // Admins  see all tickets
            $tickets = SupportTicket::latest()->get();
        } else {
            // Employees & other roles see only their assigned tickets
            $tickets = SupportTicket::where('assigned_to', $user->id)->latest()->get();
        }
    
        return view('support_tickets.index', compact('tickets', 'users'));
    }
    


public function store(Request $request)
{
    $request->validate([
        'title' => 'required|string|max:255',
        'description' => 'required|string',
        'priority' => 'required|in:Low,Medium,High',
        'assigned_to' => 'nullable|exists:users,id',
    ]);

    SupportTicket::create([
        'user_id' => Auth::id(),
        'title' => $request->title,
        'description' => $request->description,
        'priority' => $request->priority,
        'status' => 'Open',
        'assigned_to' => $request->assigned_to,
    ]);

    return redirect()->route('support-tickets.index')->with('success', 'Ticket created successfully.');
}


public function show($id)
{
    $ticket = SupportTicket::with('assignedUser')->findOrFail($id);

    return response()->json([
        'title' => $ticket->title,
        'description' => $ticket->description,
        'priority' => $ticket->priority,
        'assigned_to' => $ticket->assignedUser ? $ticket->assignedUser->name : 'Not Assigned',
        'status' => $ticket->status,
    ]);
}
    public function reply(Request $request, SupportTicket $ticket)
    {
        $request->validate(['reply' => 'required|string']);

        $ticket->replies()->create([
            'user_id' => Auth::id(),
            'message' => $request->reply,
        ]);

        return response()->json(['success' => 'Reply added successfully!']);
    }
}

