<?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\TicketPriorityService;

class TicketPriorityController extends Controller
{
    protected $ticketPriorityService;

    public function __construct(TicketPriorityService $ticketPriorityService)
    {

        $this->ticketPriorityService = $ticketPriorityService;
    }

    public function index()
    {
        try {
            $data['priorities'] = $this->ticketPriorityService->getAll();
            return view('supportticket::priority.index', $data);
        } catch (Exception $e) {
            Toastr::error(trans('common.Operation failed'), trans('common.Failed'));
            return redirect()->back();
        }
    }

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

        ];


        $request->validate($validate_rules, validationMessage($validate_rules));

        $this->ticketPriorityService->create($request->except('_token'));

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

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


    }


    public function edit(Request $request)
    {
        $data['edit'] = $this->ticketPriorityService->find($request->id);
        $data['priorities'] = $this->ticketPriorityService->getAll();
        return view('supportticket::priority.index', $data);
    }

    public function update(Request $request)
    {
        $request->validate([
            'name' => 'required|string|unique:support_ticket_pirority,name,' . $request->id
        ]);
        $this->ticketPriorityService->update($request->except('_token'));
        Toastr::success(trans('common.Operation successful'), trans('common.Success'));

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


    public function status(Request $request)
    {
        try {
            $this->ticketPriorityService->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);
        }
    }

    public function destroy(Request $request)
    {
        $this->ticketPriorityService->delete($request->id);
           return redirect()->route('ticket.priority.index');
    }
}
