<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Ticket;
use App\Models\Reply;
use App\Http\Requests;
use Illuminate\Support\Facades\Mail;

class ReplyController extends HomeBaseController
{

	/**
	 *
	 * @return void
	 * 
	 */
	
	function __construct()
	{
        parent::__construct();
	}


	/**
	 *
	 * Create the reply
	 * @param  Illuminate\Http\Request, $id
	 * @return App\Models\Reply
	 *
	 */
	public function createReply(Request $request, $id)
	{
		//  Check the request type is ajax or not
		
		$user = \Auth::user();
		
		if( $request->ajax() ) :
			$reply = new Reply;
			$reply->ticket_id = $id;
			$reply->user_id = $user->id;
			$reply->body = $request->body;
			$reply->save();

			// Process the uploaded file
			$this->processFile($request, $reply);

			// Make email notificatin
			if( $user->hasRole( ['admin', 'staff'] ) ) {
				$this->makeEmailNotification( $user, $id );
			}

			return \Response::json(['success' => 'Reply has been posted.', 'reply' => $reply, 'user' => $user]);
		else:
			return redirect('/');
		endif;

	}


	/**
	 *
	 * Remove the reply
	 * @param  Illuminate\Http\Request, $id
	 * @return App\Models\Ticket
	 */
	public function removeReply(Request $request, $id)
	{

		//  Check the request type is ajax or not
		if( $request->ajax() ) :
			$reply = Reply::find($id);

			// Find the reply and if the reply is belongs to the user or the user is a admin or staff
			// then delete the reply
			if( $reply && ( 
				$reply->user_id == \Auth::user()->id || 
				\Auth::user()->hasRole(['admin', 'staff']) 
			) ) :

				// Remove the file associated with reply 
                if( $reply->file !== NULL ) {
                    if( file_exists( public_path( 'uploads/' . $reply->file ) ) ) {
                        unlink( public_path( 'uploads/' . $reply->file ) );
                    }
                }
				$reply->delete();

				return \Response::json(['success' => 'Reply has been deleted.']);
			endif;

		else:
			return redirect('/');
		endif;

	}



	/**
	 * 
	 * Make the email notification to the user of the ticket
	 * @param $user - authenticated user
	 * @param $id - id of the ticket
	 *
	 */
	
	public function makeEmailNotification( $user, $id  )
	{
	    $ticket = Ticket::find( $id );

	    if( $ticket ) {
	    	$ticketUserName = $ticket->user->first_name;
	    	$ticketUserEmail = $ticket->user->email;


	        Mail::send('mail.ticket_reply_to_user', ['user' => $ticketUserName, 'ticket' => $ticket], function ($m) use ($user, $ticketUserEmail) {

	            $m->from($user->email, $user->fullName());

	            $m->to($ticketUserEmail)->subject('New reply to your ticket.');

	        });

	    }
	}


    /**
     *
     * Process the file
     * @param  Illuminate\Http\Request, $reply
     */
    public function processFile($request, $reply)
    {
        // Check if the form has any file
        if( $request->file('file') ) :
                
	    	// Make the folder if not exists
			if (!file_exists('uploads')) {
			    mkdir('uploads', 0777, true);
			}

            // Get the requested file
            $file = $request->file('file');
            $name = time() . '_' . str_random(8) . '.' .  $file->guessClientExtension();

            // Move the file to the folder
            $file->move('uploads', $name);

            // Update the database
            $reply->file = $name;    
            $reply->save();

        endif;   
    }

}
