<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Ticket;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class TicketController extends Controller
{
    public function index()
    {
        $client = Auth::user()->client;
        $tickets = $client
            ? $client->tickets()->with('installation')->latest()->paginate(10)
            : Ticket::whereRaw('1 = 0')->paginate(10);

        return view('client.tickets.index', compact('tickets'));
    }

    public function create()
    {
        $client = Auth::user()->client;
        $installations = $client
            ? $client->installations()->orderBy('address')->pluck('address', 'id')
            : collect([]);

        return view('client.tickets.create', compact('installations'));
    }

    public function store(Request $request)
    {
        $client = Auth::user()->client;

        if (! $client) {
            return redirect()->route('client.tickets.index')->with('error', 'A sua conta ainda não tem um perfil de cliente associado.');
        }

        $validated = $request->validate([
            'installation_id' => [
                'nullable',
                Rule::exists('installations', 'id')->where('client_id', $client->id),
            ],
            'subject' => ['required', 'string', 'max:255'],
            'description' => ['required', 'string'],
            'priority' => ['required', Rule::in(['low', 'medium', 'high', 'urgent'])],
        ]);

        $validated['client_id'] = $client->id;
        $validated['status'] = 'open';

        $ticket = Ticket::create($validated);

        return redirect()->route('client.tickets.show', $ticket)->with('success', 'Pedido de suporte aberto com sucesso.');
    }

    public function show(Ticket $ticket)
    {
        $client = Auth::user()->client;

        abort_unless($client && $ticket->client_id === $client->id, 403);

        $ticket->load(['installation', 'technician']);

        return view('client.tickets.show', compact('ticket'));
    }
}
