<?php

namespace App\Http\Controllers;

use App\Classes\Options;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Ticket;
use App\Models\Role;
use App\Models\Notification;
use App\Models\Department;
use App\Http\Requests;
use Illuminate\Support\Facades\Mail;

class TicketController extends HomeBaseController
{

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

    /**
     *
     * Return all tickets from database model
     * @return App\Models\Ticket
     * 
     */
    public function allTickets()
    {
        $tickets = Auth::user()->tickets()->orderBy('created_at', 'DESC')->paginate(20);

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



    /**
     *
     * 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 && $ticket->user_id == \Auth::user()->id ) {
            $replies = $ticket->replies()->paginate(15);
            return view('tickets.single', compact('ticket', 'replies'));

        } else {
            abort(404);
        }

    }



    /**
     *
     * Create ticket
     * @param  App\Http\Requests
     * @return App\Models\Ticket
     * 
     */
    public function createTicket(Requests\CreateTicketRequest $request)
    {

        // Check the request type
        if( $request->ajax() ) :

            $ticket = \Auth::user()->tickets()->create($request->only(
                'subject', 
                'department_id', 
                'message'
            ));

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

            // Make the notification
            $this->makeNotification( $ticket );
            
            // Send the mail
            if( Options::get('email_notification') == 'on' ) {
                try {
                    $this->sendMailNotification( $ticket );
                    
                } catch (Exception $e) {
                    return \Response::json(['success' => $e->getMessage()]);
                }
            }

            return \Response::json(['success' => $ticket]);
            
        else:

            return redirect('/');
        
        endif;
        
    }


    /**
     *
     * Ticket edit page
     * @param  Illuminate\Http\Request, $id
     * @return App\Models\Department
     *
     */
    public function getEditTickets(Request $request, $id)
    {
        $ticket = $this->tickets->find($id);
        $departments = Department::lists('name', 'id');

        if($ticket && $ticket->user_id == \Auth::user()->id) :

            return view('tickets.edit', compact('ticket', 'departments'));

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



    /**
     *
     * Update The Edited Ticket
     * @param  App\Http\Requests, $id
     * @return App\Models\Ticket
     *
     */
    public function postEditTickets(Requests\UpdateTicketRequest $request, $id)
    {
        $ticket = $this->tickets->find($id);

        if($ticket && $ticket->user_id == \Auth::user()->id) :

            $ticket->fill($request->only('subject', 'department_id', 'message'))->save();

            // Process the updated file
            $this->processFileUpdate($request, $ticket);

            return redirect()->back()->with('message', 'Ticket has been updated');

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

    }


    /**
     *
     * Create notification when client opens any ticket
     * @param @ticket
     * @return App\Models\Notification
     *
     */
    public function makeNotification( $ticket  )
    {
        $user_id = \Auth::user()->id;

        // Create the notification
        Notification::create([
            'user_id' => $user_id,
            'ticket_id' => $ticket->id,
            'title' => 'opened a new ticket',
            'type'  => 'open'
        ]);

    }


    /**
     *
     * Send The Mail When any ticket opens
     * @param  $ticket 
     * @return Illuminate\Support\Facades\Mail
     */
    public function sendMailNotification( $ticket )
    {
        $user = Auth::user();
        $role = Role::where('name', 'admin')->first();
        $admin = Role::find( $role->id )->users()->first();


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

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

            $m->to($admin->email)->subject('New ticket opened.');

        });

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

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

            $m->to($user->email)->subject('Ticket Opened.');

        });
    }


    /**
     *
     * Process the file
     * @param  $request, $ticket 
     *
     */
    public function processFile($request, $ticket)
    {
        // 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() . '_' . $file->getClientOriginalName();

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

            // Update the database
            $ticket->files = $name;    
            $ticket->save();

        endif;   
    }



    /**
     *
     * Process the upldated file
     * @param  $request, $ticket 
     *
     */
    public function processFileUpdate($request, $ticket)
    {
        // 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() . '_' . $file->getClientOriginalName();

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

            // if has any exixting file, delete that first
            if( $ticket->files ) {
                unlink('uploads/' . $ticket->files);
            }

            // Update the database
            $ticket->files = $name;    
            $ticket->save();

        endif;   
    }
}
