<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Ticket;
use App\Models\User;
use App\Models\Validate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class TicketController extends Controller
{
    public function index(){
        return view('user.open-ticket');
    }

    public function store(Request $request){
        $validator =  $request->validate(Validate::$TicketForm);
        if(!$validator){
           throw ValidationException::withMessages($validator);
        }
        $validator['user_id'] = auth()->user()->id;
        Ticket::create($validator);
        return redirect(route('user.tickets'))->with('success',__('Your ticket has been submitted'));
    }

    public function show(){
        $tickets = Ticket::where('user_id',auth()->user()->id)->orderBy('created_at','DESC')->get();
        return view('user.tickets',compact('tickets'));
    }

    public function display(Request $request, $id){
    $ticket = Ticket::where('id', $id)->first();
    if ($ticket->status == 'pending') {
        if ($request->ajax()) {
            return response()->json([
                'status'=>'warning',
                'message' => 'Your Ticket is still pending reply',
                'ticket' => $ticket
            ]);
        }
    } else {
        $replied_by = User::where('id', $ticket->reply_id)->first();
        $name = $replied_by->firstname.' '.$replied_by->lastname;
        $date = date_format(date_create($replied_by->created_at), 'd M, Y');
        $replyRate = date_format(date_create($replied_by->replied_at), 'd M, Y');
        if ($request->ajax()) {
            return response()->json([
                'status'=>'success',
                'ticket' => $ticket,
                'name' => $name,
                'date' => $date,
                'reply_date'=>$replyRate
            ]);
        }
    }
}
}
