<?php

namespace Modules\SupportTicket\Http\Controllers;

use Brian2694\Toastr\Facades\Toastr;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\SupportTicket\Services\TicketStatusService;

class TicketStatusController extends Controller
{
    protected $ticketStatusService;

    public function __construct(TicketStatusService $ticketStatusService)
    {

        $this->ticketStatusService = $ticketStatusService;
    }


    public function index()
    {
        $statuses = $this->ticketStatusService->getAll();
        return view('supportticket::status.index', compact('statuses'));
    }


    public function store(Request $request)
    {
        $validate_rules = [
            'name' => 'required|string|unique:ticket_statuses,name'

        ];


    $request->validate($validate_rules, validationMessage($validate_rules));
        $this->ticketStatusService->create($request->except('_token'));
        Toastr::success(trans('common.Operation successful'), trans('common.Success'));

        return redirect()->route('ticket.status.index');
    }


    public function edit(Request $request)
    {
        $edit = $this->ticketStatusService->find($request->id);
        $statuses = $this->ticketStatusService->getAll();
        return view('supportticket::status.index', compact('statuses','edit'));
    }


    public function update(Request $request)
    {
        $request->validate([
            'name' => 'required|string|unique:ticket_statuses,name,' . $request->id
        ]);
            $this->ticketStatusService->update($request->except('_token'));

            Toastr::success(trans('common.Operation successful'), trans('common.Success'));

            return redirect()->route('ticket.status.index');
    }

    public function destroy(Request $request)
    {
        $this->ticketStatusService->delete($request->id);
        Toastr::success(trans('common.Operation successful'), trans('common.Success'));

        return redirect()->route('ticket.status.index');
    }

    public function status(Request $request)
    {
        try {
            $this->ticketStatusService->statusChange($request->except('_token'));
            return true;
        } catch (Exception $e) {
            Toastr::error(trans('common.Operation failed'), trans('common.Failed'));

            return response()->json([
                'error' => $e->getMessage()
            ], 503);
        }
    }
}
