<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Role;
use App\Models\Notification;
use App\Http\Requests;
use App\Http\Controllers\AppBaseController;
use abeautifulsite\SimpleImage;
use Exception;

class ClientController extends AppBaseController
{

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

	/**
	 *
	 * Return All clients list
     * @return App\Models\Role
	 *
	 */
    public function allClients()
    {
        $role = Role::where('name', 'client')->first();
        $clients = Role::find($role->id)->users()->orderBy('created_at', 'DESC')->paginate(20);

        return view('dashboard.clients.index', compact('clients'));
    }


    /**
     *
     * Create a Client
     * @param  App\Http\Requests
     * @return App\Models\User
     * 
     */
    public function create(Requests\CreateClientRequest $request)
    {

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

	    	// Create the user
	        $user = $this->users->create($request->only(
	        	'first_name', 
	        	'last_name', 
	        	'email', 
	        	'password'
	        ));

	    	$this->processProfileImage($request, $user);

	        // Find the role
	        $role = Role::where('name', '=', 'client')->first();

	        // Attach the role to the user
	        $user->attachRole( $role );

	        return \Response::json(['success' => 'Client has been added']);

	    else:

	    	return redirect('/');

	    endif;

    }


    /**
     *
     * Remove Staff
     * @param  Illuminate\Http\Requests
     * @return App\Models\User
     *
     */
    public function removeClient(Request $request)
    {
        $id = $request->get('id');

        // Check the request type
        if( $request->ajax() ) :
            // find the users
            $client = $this->users->find($id);

            if( $client ) {

                // DElete all tickets related to client
                foreach( $client->tickets as $ticket) {
                    // Delete the files of ticket
                    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 the ticket
                    $ticket->delete();
                }


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

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

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

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

        endif;
    }


    /**
     *
     * Remove all notifications of the ticket
     * @param  $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);
    }



    /**
     *
     * Process the user uploaded image
     * @param  $request, $user
     *
     */
    public function processProfileImage($request, $user)
    {

        // Check if the form has any file
        if( $request->file('client_img') ) :
                
	    	// Make the folder if not exists
			if (!file_exists('uploads/profile_images')) {
			    mkdir('uploads/profile_images', 0777, true);
			}
            try {

                // The requested image
                $file = $request->file('client_img');
                $name = time() . str_random(15);

                // Crop the image
                $simpleImage = new SimpleImage();
                $simpleImage->load($file)->best_fit(300, 400)->save('uploads/profile_images/' . $name . '.jpg');

                // Update the database
                $user->profile_img = $name . '.jpg';    
                $user->save();


            } catch (Exception $e) {
                return \Response::json(['error' => $e->getMessage()]);
            }

        endif;   
    }
}
