<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use App\Models\Ticket;
use App\Models\Notification;
use App\Models\Role;
use App\Models\Department;
use App\Http\Requests;
use App\Http\Controllers\AppBaseController;

class TicketController extends AppBaseController
{


    /**
     *
     * @return void
     * 
     */
    function __construct(Ticket $tickets)
    {
        parent::__construct();
    	$this->tickets = $tickets;
    }

    /**
     *
     * Return all tickets from database model
     * @return App\Models\Ticket
     *
     */
    public function tickets($view)
    {

        if( $view == 'all' ) {
            $tickets = $this->tickets->orderBy('created_at', 'DESC')->paginate(20);
        } else if ( $view == 'new' ) {
            $tickets = $this->tickets->where('status', 'new')->orderBy('created_at', 'DESC')->paginate(20);
        } else if ( $view == 'pending' ) {
            $tickets = $this->tickets->where('status', 'pending')->orderBy('created_at', 'DESC')->paginate(20);
        } else if ( $view == 'solved' ) {
            $tickets = $this->tickets->where('status', 'solved')->orderBy('created_at', 'DESC')->paginate(20);
        } else {
            return redirect('/dashboard');
        }

        return view('dashboard.tickets.tickets', compact('tickets', 'view'));
    }



    /**
     *
     * Show a sinlge ticket
     * @param $id, $subject
     * @return View
     *
     */
    public function showTickets($id, $subject)
    {
        
        // Reformat title
        $subject = Ticket::reformatTicket( $subject );

        // Find the ticket
        $ticket = $this->tickets->where( compact('id') )->first();

        if( $ticket ) {

            $replies = $ticket->replies()->paginate(15);

            $role = Role::where('name', 'staff')->first();
            $staffs = Role::find($role->id)->users()->get();

            return view('dashboard.tickets.single', compact('ticket', 'replies', 'staffs'));

        } else {
            abort(404);
        }

    }



    /**
     *
     * Search for a ticket
     * @param  Illuminate\Http\Request
     * @return App\Models\Ticket
     */
    public function searchTicket(Request $request)
    {
        $term = $request->get('term');

        $tickets = Ticket::where('subject', 'LIKE', '%' . $term . '%')->orWhere('id', $term)->orderBy('created_at', 'DESC')->paginate(20);
        $view = '';

        return view('dashboard.tickets.tickets', compact('tickets', 'view'));
    }


    /**
     *
     * Assign The ticket to a user
     * @param  Illuminate\Http\Request, $id
     * @return App\Models\Ticket
     *
     */
    public function assignTicket(Request $request, $id)
    {
        // Check the request type
        if( $request->ajax() ) :
            // find the ticket
            $ticket = $this->tickets->find($id);

            if( $ticket ) {
                $ticket->assigned_to = $request->get('assign_user');
                $ticket->save();

                // return the success response
                return \Response::json(['success' => 'Ticket has been assigned.']);
            } else {
                // return the error response
                return \Response::json(['error' => 'Sorrr, can not assign the ticket.', 500]);
            }

        else :
            // redirect if the request type is not ajax
            return redirect('/');

        endif;
    }


    /**
     *
     * Update ticket status
     * @param  Illuminate\Http\Request, $id
     * @return App\Models\Ticket
     *
     */
    public function updateStatus(Request $request, $id)
    {
        $ticket_status = $request->get('ticket_status');
        $user = \Auth::user();
        // Check the request type
        if( $request->ajax() ) :
            // find the ticket
            $ticket = $this->tickets->find($id);

            if( $ticket ) {

                // Update the ticket status
                $ticket->status = $ticket_status;
                $ticket->save();

                $this->makeNotification( $ticket );


                // Update the Solved by field
                // So that we can determine who solved it
                if( $ticket_status == 'solved') {
                    $ticket->solved_by = $user->id;
                    $ticket->save();
                } else if ($ticket_status == 'pending') {
                    $ticket->solved_by = 0;
                    $ticket->save(); 
                }

                // return the success response
                return \Response::json(['success' => 'Ticket status has been updated.', 'user' => $user]);
            } else {
                // return the error response
                return \Response::json(['error' => 'Sorrr, can not update the ticket.', 500]);
            }

        else :
            // redirect if the request type is not ajax
            return redirect('/');

        endif;
    }



    /**
     *
     * Remove ticket
     * @param  Illuminate\Http\Request
     * @return App\Models\Ticket
     *
     */
    public function removeTicket(Request $request)
    {
        $id = $request->get('id');
        $user_id = \Auth::user()->id;
        // Check the request type
        if( $request->ajax() ) :
            // find the ticket
            $ticket = $this->tickets->find($id);

            if( $ticket && ( 
                $ticket->user_id == $user_id || 
                \Auth::user()->hasRole(['admin', 'staff']) )
            ) {

                // Delete the ticket associted file first
                if( $ticket->files !== NULL ) {
                    if( file_exists( public_path( 'uploads/' . $ticket->files ) ) ) {
                        unlink( public_path( 'uploads/' . $ticket->files ) );
                    }
                }

                // Remove ticket notifications
                $this->removeTicketNotifications( $ticket );

                // DElete all replies related to it
                foreach( $ticket->replies as $reply) {
                    // Delete the files of reply
                    if( $reply->file !== NULL ) {
                        if( file_exists( public_path( 'uploads/' . $reply->file ) ) ) {
                            unlink( public_path( 'uploads/' . $reply->file ) );
                        }
                    }

                    // Delete the reply
                    $reply->delete();
                }

                // Delete the ticket
                $ticket->delete();

                // return the success response
                return \Response::json(['success' => 'Ticket has been deleted.']);
            } else {
                // return the error response
                return \Response::json(['error' => 'Sorry, can not delete the ticket.', 500]);
            }

        else :
            // redirect if the request type is not ajax
            return redirect('/');

        endif;
    }


    /**
     *
     * Make notification for the action
     * @param App\Models\Ticket
     * @return App\Models\Notification
     *
     */
    public function makeNotification( $ticket )
    {
        $userId = \Auth::user()->id;
        Notification::create([
            'user_id'   => $userId,
            'ticket_id'   => $ticket->id,
            'title'   => 'is now ' . $ticket->status,
            'type'   => $ticket->status
        ]);
    }



    /**
     *
     * Remove all notifications of the ticket
     * @param App\Models\Ticket
     * @return App\Models\Notification
     *
     */
    
    public function removeTicketNotifications( $ticket )
    {
        $notifications = Notification::where('ticket_id', $ticket->id)->get();

        foreach( $notifications as $notification )
        {
            $notification->delete();
        }
        // dd($notifications);
    }

}
