<?php

namespace App\Http\Controllers\Backend;

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

class StaffController extends AppBaseController
{


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

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

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


    /**
     *
     * @param App\Models\User
     * @return App\Models\User
     *
     */
    
    public function getCreate(User $staff)
    {
        return view('dashboard.staffs.form', compact('staff'));
    }

    public function getPageEdit($id)
    {
        $staff = $this->users->find($id);
        if($staff) {
            return view('dashboard.staffs.form', compact('staff'));            
        }
    }


    /**
     *
     * Get Edit Page For staffs
     * @param  Illuminate\Http\Request
     * @return App\Models\User
     *
     */
    public function getEdit(Request $request)
    {   
        // Check the request type
        if( $request->ajax() ) :

            $id = $request->get('id');

            $staff = $this->users->find($id);

            if( $staff ) : 
                return \Response::json(['staff' => $staff]);
            endif;

        else:
            return redirect()->route('dashboard.staffs.getPageEdit');
        endif;
    }



    /**
     *
     * Create a Staff
     * 
     * @param Illuminate\Http\Request
     * @return App\Models\User
     *
     */
    public function create(Requests\CreateStaffRequest $request)
    {

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

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

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

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

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

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

        else:

            return redirect('/');

        endif;

    }

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

        $this->validate($request, [
            'email' => 'required|email|unique:users,email,' . $id
        ]);

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

            

	    	// Get the user the user
	        $staff = $this->users->find( $id );

            if( $staff ):

                // Process the profile image
                $this->updateProfileImage($request, $staff);

                // Update the record
                $staff->fill($request->only(['first_name', 'email', 'password', 'department_id', 'role_name']))->save();

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

	    else:

	    	return redirect('/');

	    endif;

    }



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

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

            if( $staff ) {

                // DElete all tickets related to client
                foreach( $staff->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( $staff->profile_img !== NULL ) {
                    if( file_exists( public_path( 'uploads/profile_images/' . $staff->profile_img ) ) ) {
                        unlink( public_path( 'uploads/profile_images/' . $staff->profile_img ) );
                    }
                }

                // Get all tickets where staff is assigned and solved it
                $tickets = Ticket::where('assigned_to', $staff->id)
                                    ->orWhere('solved_by', $staff->id)
                                    ->get();

                // Un assign those tickets
                foreach($tickets as $ticket) {
                    if($ticket->assigned_to == $staff->id) {
                        $ticket->assigned_to    = NULL;                        
                    } 
                    if($ticket->solved_by == $staff->id) {
                        $ticket->solved_by    = NULL;                        
                    }
                    $ticket->save();
                }
                
                // Delete the staff
                $staff->delete();

                // return the success response
                return \Response::json(['success' => 'Stafff 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 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();
        }
    }


    /**
     *
     * Process the user uploaded image
     * @param Illuminate\Http\Request, $staff
     *
     */
    public function updateProfileImage($request, $staff)
    {

        // Check if the form has any file
        if( $request->file('staff_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('staff_img');
                $name = time() . str_random(15);

                // Delete the existing profile image
                if( $staff->profile_img !== NULL ) {
                    if( file_exists( public_path( 'uploads/profile_images/' . $staff->profile_img ) ) ) {
                        unlink( public_path( 'uploads/profile_images/' . $staff->profile_img ) );
                    }
                }

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

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


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



        endif;   
    }

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

        // Check if the form has any file
        if( $request->file('staff_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('staff_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;   
    }
}
