<?php

namespace App\Http\Controllers\User\Tickets;

use App\Helpers\DropdownListHelper;
use App\Models\Ticket;
use App\Http\Controllers\Controller;
use App\Http\Requests\User\TicketAnswerRequest;
use App\Http\Requests\User\TicketAttachmentRequest;
use App\Http\Requests\User\TicketCreateRequest;
use App\Services\User\Tickets\TicketsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;

class TicketsController extends Controller
{
    use DropdownListHelper;

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request, TicketsService $ticketsService)
    {
        return Inertia::render('User/Tickets/List', [
            'tickets' => $ticketsService->getTickets($request)
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return Inertia::render('User/Tickets/Create', [
            'priorityList' => $this->ticketPriorityList()
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(TicketCreateRequest $request, TicketsService $ticketsService)
    {
        /** @var \App\Models\User $user */
        $user = auth()->user();

        // check for admin and owner
        if ($user->type == "admin" || $user->type == "owner")
            return redirect()->route('user.tickets.index')->withErrors([__('messages.admin_can_not_create_ticket')]);

        // create ticket
        $ticket = $user->tickets()->create([
            'title' => $request->title,
            'priority' => $request->priority,
            'status' => 'waiting_admin',
        ]);

        // check for ticket status
        if ($ticket == null)
            return redirect()->back()->withErrors([__('messages.ticket_create_error')]);

        // create ticket starter message
        $ticket->ticketAnswers()->create([
            'user_id' => $user->id,
            'type' => 'text',
            'content' => $request->content,
            'status' => 'publish',
        ]);

        if ($request->exists('attachment') && $request->attachment != null) {
            $request->validate([
                'attachment' => ['required', 'file', 'max:10240', 'mimes:jpeg,jpg,png,webp,gif,svg'],
            ]);

            // upload attachment
            $ticketsService->uploadAttachment($request, $user, $ticket);
        }

        return redirect()->route('user.tickets.show', $ticket->id)->with('message', [__('messages.ticket_created')]);
    }

    /**
     * Display the specified resource.
     */
    public function show(Ticket $ticket)
    {
        /** @var \App\Models\User $user */
        $user = auth()->user();

        // check for user accessibility
        if ($user->id != $ticket->user_id)
            return redirect()->route('user.tickets.index')->withErrors([__('messages.unauthorized')]);

        $ticket = [
            'id' => $ticket->id,
            'jalali_created_at' => $ticket->jalali_created_at,
            'jalali_updated_at' => $ticket->jalali_updated_at,
            'priority' => $ticket->priority,
            'status' => $ticket->status,
            'title' => $ticket->title,
            'user_id' => $ticket->user_id,
            'ticket_answers' => $ticket->ticket_answers->map(fn($answer) => [
                'id' => $answer['id'],
                'user_id' => $answer['user_id'],
                'type' => $answer['type'],
                'content' => $answer['content'],
                'get_file' => $answer['get_file'],
                'jalali_created_at' => $answer['jalali_created_at'],
                'user' => [
                    'id' => $answer['user']['id'],
                    'get_name' => $answer['user']['get_name'],
                    'get_avatar' => $answer['user']['get_avatar'],
                    'type' => $answer['user']['type'],
                    'seller' => $answer['user']['seller'],
                ],
            ])
        ];

        return Inertia::render('User/Tickets/Show', [
            'ticket' => $ticket
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Ticket $ticket)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Ticket $ticket)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Ticket $ticket)
    {
        //
    }

    /** send answer */
    public function answer(TicketAnswerRequest $request, Ticket $ticket)
    {
        // check to prevent send answer to closed ticket
        if ($ticket->status == "closed")
            return redirect()->route('user.tickets.index')->withErrors([__('messages.ticket_is_closed')]);

        /** @var \App\Models\User $user */
        $user = auth()->user();

        // check for user accessibility
        if ($user->id != $ticket->user_id)
            return redirect()->route('user.tickets.index')->withErrors([__('messages.unauthorized')]);

        // create answer
        $answer = $ticket->ticketAnswers()->create([
            'user_id' => $user->id,
            'type' => 'text',
            'content' => $request->content,
            'status' => 'publish',
        ]);

        // check answer status
        if ($answer == null)
            return redirect()->back()->withErrors([__('messages.unknown_error')]);

        // update ticket status
        $ticket->update([
            'status' => 'waiting_admin'
        ]);

        return redirect()->back()->with('message', [__('messages.ticket_answer_created')]);
    }

    /** send attachment */
    public function attachment(TicketAttachmentRequest $request, Ticket $ticket, TicketsService $ticketsService)
    {
        // check to prevent send answer to closed ticket
        if ($ticket->status == "closed")
            return redirect()->route('user.tickets.index')->withErrors([__('messages.ticket_is_closed')]);

        /** @var \App\Models\User $user */
        $user = auth()->user();

        // check for user accessibility
        if ($user->id != $ticket->user_id)
            return redirect()->route('user.tickets.index')->withErrors([__('messages.unauthorized')]);

        // upload attachment
        $ticketsService->uploadAttachment($request, $user, $ticket, true);

        return redirect()->back()->with('message', [__('messages.ticket_attachment_created')]);
    }
}
