<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Models\Department;
use App\Models\Option;
use App\Http\Controllers\AppBaseController;
use abeautifulsite\SimpleImage;
use Exception;

class SettingsController extends AppBaseController
{

    /**
     * @var string
     */
    private $envPath;

    /**
     * @var string
     */
    private $envExamplePath;


    /**
     *
     * @return void
     * 
     */
    function __construct(Department $department, Option $options)
    {
        parent::__construct();
        $this->department = $department;
        $this->options = $options;

        $this->envPath = base_path('.env');
        $this->envExamplePath = base_path('.env.example');
    }


	/**
	 *
	 * Return The settings index file
	 * @return App\Models\User
	 */
    public function index()
    {
        $user = \Auth::user();
        return view('dashboard.settings.index', compact('user'));
    }



    /**
     *
     * Theme Update
     * @param  App\Http\Request, $id
     * @return Ajax Response
     * 
     */
    public function generalSettings(Requests\UpdateGeneralSettings $request)
    {
        
        // Check the reqeust type
        if( $request->ajax() ) : 

            $title_option = $this->options
                            ->where('name', 'title')
                            ->first();

            $timezone_option = $this->options
                            ->where('name', 'timezone')
                            ->first();

            $email_notification = $this->options
                            ->where('name', 'email_notification')
                            ->first();

            $edit_ticket = $this->options
                            ->where('name', 'edit_ticket')
                            ->first();

            if( $title_option ) {
                $title_option->value = $request->get('company_name');
                $title_option->save();
            }

            if( $timezone_option ) {
                $timezone_option->value = $request->get('timezone');
                $timezone_option->save();
            }

            if( $email_notification ) {
                $email_notification->value = $request->get('email_notification');
                $email_notification->save();
            }
            
            if( $edit_ticket ) {
                $edit_ticket->value = $request->get('edit_ticket');
                $edit_ticket->save();
            }

            // Process Site Logo
            $this->processSiteLogo($request);
            // Process Dashboard Logo
            $this->processBackendLogo($request);

            return \Response::json(['success' => 'General settings has been updated. ' ]);

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


    /**
     *
     * Theme Update
     * @param  Illuminate\Http\Request
     * @return Ajax Response
     *
     */
    public function themeUpdate(Request $request)
    {
        // Check the reqeust type
        if( $request->ajax() ) : 

            $style_option = $this->options
                            ->where('name', 'style')
                            ->first();

            $extra_css_option = $this->options
                            ->where('name', 'extra_css')
                            ->first();

            if( $style_option ) {
                $style_option->value = $request->get('style');
                $style_option->save();
            }

            if( $extra_css_option ) {
                $extra_css_option->value = $request->get('extra_css');
                $extra_css_option->save();
            }

            return \Response::json(['success' => 'Theme option has been updated. ' ]);

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


    /**
     *
     * Update profile settings 
     * @param  App\Http\Request
     * 
     */
    public function profileUpdate(Requests\UpdateProfileRequest $request)
    {
        //  Check the request type
        if( $request->ajax() ) :

            // Save the user request
            \Auth::user()->fill($request->only([
                'first_name',
                'last_name',
                'email'
            ]))->save();

            // if the user set any passwor then validate it and update the database
            if( $request->has('password') ) {
                // Validate the password
                $this->validate($request, [
                    'password' => 'min:6'
                ]);

                \Auth::user()->fill($request->only([ 'password' ]))->save();
            }

            // Process the image 
            $this->processProfileImage($request);

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


        else:

        endif;
    }



    /**
     *
     * Add department
     * @param  Illuminate\Http\Request
     *
     */
    public function addDepartment(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:departments'
        ]);

        $department = $this->department->create($request->only('name'));

        return \Response::json(['success' => 'Department added.', 'department' => $department ]);

    }


    /**
     *
     * Add department
     * @param  Illuminate\Http\Request, $id
     *
     */
    public function removeDepartment(Request $request, $id)
    {
        // Check the reqeust type
        if( $request->ajax() ) :

            $this->validate($request, [
                'id' => 'required'
            ]);

            // Find the department
            $department = $this->department->find($id);

            // If found the department
            if($department) {
                // Find all the tickets related to it
                $tickets = $department->tickets->all();

                // Unassign every tickets
                foreach( $tickets as $ticket ) {
                    $ticket->department_id = 0;
                    $ticket->save();
                }

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

            return \Response::json(['success' => 'Department Deleted.' ]);

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


    /**
     *
     * Edit department
     * @param  Illuminate\Http\Request, $id
     * @return App\Models\Department
     */
    public function editDepartment(Request $request, $id)
    {
        // Check the reqeust type
        if( $request->ajax() ) :

            $this->validate($request, [
                'name' => 'required'
            ]);

            // Find the department
            $department = $this->department->find($id);

            // If found the department
            if($department) {
                $department->name = $request->name;
                $department->save();
            }

            return \Response::json(['success' => 'Department Edited.' ]);

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



    /**
     *
     * Change The .env file via app settings
     * @param  Illuminate\Http\Request
     *
     */
    
    public function appSettings(Request $request)
    {
        $this->validate($request, [
            'MAIL_DRIVER'  => 'required',
            'recaptcha'  => 'required'
        ]);


        // Set env key and values
        $env_update = $this->changeEnv([
            'MAIL_DRIVER'       => $request->MAIL_DRIVER,
            'MAIL_HOST'         => $request->MAIL_HOST,
            'MAIL_PORT'         => $request->MAIL_PORT,
            'MAIL_USERNAME'     => $request->MAIL_USERNAME,
            'MAIL_PASSWORD'     => $request->MAIL_PASSWORD,
            'MAIL_ENCRYPTION'   => $request->MAIL_ENCRYPTION,
            'G_RECAPTCHA_KEY'   => $request->recaptcha
        ]);

        if($env_update){

            // $this->updateOptionsRecords($request);

            return \Response::json(['success', 'App environment has been updated']);
        } else {
            return \Response::json(['error', 'Can not be saved'], 500);
        }
    }



    /**
     * Get the content of the .env file.
     *
     * @return string
     */
    public function getEnvContent()
    {
        if (!file_exists($this->envPath)) {
            if (file_exists($this->envExamplePath)) {
                copy($this->envExamplePath, $this->envPath);
            } else {
                touch($this->envPath);
            }
        }

        return file_get_contents($this->envPath);
    }

    /**
     *
     * Update the env file
     *
     */
    public function changeEnv($data = array())
    {
        if(count($data) > 0){

            // Read .env-file
            $env = $this->getEnvContent();

            // Split string on every " " and write into array
            $env = preg_split('/\s+/', $env);;

            // Loop through given data
            foreach((array)$data as $key => $value){

                // Loop through .env-data
                foreach($env as $env_key => $env_value){

                    // Turn the value into an array and stop after the first split
                    // So it's not possible to split e.g. the App-Key by accident
                    $entry = explode("=", $env_value, 2);

                    // Check, if new key fits the actual .env-key
                    if($entry[0] == $key){
                        // If yes, overwrite it with the new one
                        $env[$env_key] = $key . "=" . $value;
                    } else {
                        // If not, keep the old one
                        $env[$env_key] = $env_value;
                    }
                }
            }

            // Turn the array back to an String
            $env = implode("\n", $env);

            // And overwrite the .env with the new data
            file_put_contents(base_path() . '/.env', $env);
            
            return true;
        } else {
            return false;
        }
    }


    /**
     *
     * Update the options record
     * @param  $request
     *
     */
    public function updateOptionsRecords( $request )
    {
        $mail_driver = Option::where('name', 'MAIL_DRIVER')->first();
        $mail_driver->value = $request->get('MAIL_DRIVER');
        $mail_driver->save(); 

        $MAIL_HOST = Option::where('name', 'MAIL_HOST')->first();
        $MAIL_HOST->value = $request->get('MAIL_HOST');
        $MAIL_HOST->save(); 

        $MAIL_PORT = Option::where('name', 'MAIL_PORT')->first();
        $MAIL_PORT->value = $request->get('MAIL_PORT');
        $MAIL_PORT->save(); 

        $MAIL_USERNAME = Option::where('name', 'MAIL_USERNAME')->first();
        $MAIL_USERNAME->value = $request->get('MAIL_USERNAME');
        $MAIL_USERNAME->save(); 

        $MAIL_PASSWORD = Option::where('name', 'MAIL_PASSWORD')->first();
        $MAIL_PASSWORD->value = $request->get('MAIL_PASSWORD');
        $MAIL_PASSWORD->save(); 
        
        $MAIL_ENCRYPTION = Option::where('name', 'MAIL_ENCRYPTION')->first();
        $MAIL_ENCRYPTION->value = $request->get('MAIL_ENCRYPTION');
        $MAIL_ENCRYPTION->save(); 
        
        $G_RECAPTCHA_KEY = Option::where('name', 'G_RECAPTCHA_KEY')->first();
        $G_RECAPTCHA_KEY->value = $request->get('recaptcha');
        $G_RECAPTCHA_KEY->save(); 
    }



    /**
     *
     * Process the site logo
     * @param  $request
     *
     */
    public function processSiteLogo($request)
    {


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

            try {

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

                // Crop the image
                $simpleImage = new SimpleImage();
                $simpleImage->load($file)->fit_to_height(60)->fit_to_width(170)->save('assets/img/' . $name . '.png');

                // Get the dashboard logo row from database
                $logo_option =  Option::where('name', 'logo')->first();

                // Delete previously uploaded logo
                if( $logo_option->value !== '' ) {
                    if( file_exists('assets/img/' . $logo_option->value) ) {
                        unlink( public_path( 'assets/img/' . $logo_option->value  ) );                        
                    }
                }

                // Save the new logo
                $logo_option->value = $name . '.png';
                $logo_option->save();

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

        endif;   
    }



    /**
     *
     * Process the site backend logo
     * @param  $request
     *
     */
    public function processBackendLogo($request)
    {


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

            try {

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

                // Crop the image
                $simpleImage = new SimpleImage();
                $simpleImage->load($file)->fit_to_height(60)->fit_to_width(170)->save('assets/img/' . $name . '.png');

                // Get the dashboard logo row from database
                $backend_logo =  Option::where('name', 'dashboard_logo')->first();

                // Delete previously uploaded logo
                if( $backend_logo->value !== '' ) {
                    if( file_exists('assets/img/' . $backend_logo->value) ) {
                        unlink( public_path( 'assets/img/' . $backend_logo->value  ) );                        
                    }
                }

                // Save the new logo
                $backend_logo->value = $name . '.png';
                $backend_logo->save();

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

        endif;   
    }


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


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

                $user = \Auth::user();

                if( $user->profile_img !== NULL ) {
                    if( file_exists( public_path( 'uploads/profile_images/' . $user->profile_img ) ) ) {
                        unlink( public_path( 'uploads/profile_images/' . $user->profile_img ) );
                    }
                }

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

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


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

        endif;   
    }
}
