<?php


namespace App\Http\Controllers;
use App\Repositories\UserRepository;
use App\User;
use Auth;
use Request;
use Validator;
use App\Models\UserAccount;


class UserDataController extends Controller
{

    protected $userRepo;

    public function __construct(UserRepository $userRepo)
    {
        $this->middleware('auth');
        $this->userRepo = $userRepo;
    }

    public function userEdit(){
        $user = Auth::user();

        /*if(!$user->account){
            $user->account = new UserAccount();
        }*/
        $data = [
            'user' => $user,
        ];
        return view('user.edit', $data);
    }

    public function userEditStore(){

        $user = Auth::user();
        /*if(!$user->account){
            $user->account = new UserAccount();
        }*/
        $data = Request::all();
        if(isset($data['action']) && $data['action'] == "reverse_charge_validate"){
            return $this->userRepo->reverse_charge_validate($data, $user, route('user_edit', [$user->id]));
        }

        if(isset($data['action']) && $data['action'] == "reverse_charge_delete"){
            return $this->userRepo->reverse_charge_delete($data, $user, route('user_edit', [$user->id]));
        }        

        $rules = array(
            'salutation' => 'required',
            'first_name'=>'required',
            'last_name'=>'required',
            'address'=>'required',
            'zipcode'=>'required',
            'city' => 'required',
            'phone' => 'required_without:mobil',
            'mobil' => 'required_without:phone',
            'tax_number' => 'required_without:tax_identification_number',
            'tax_identification_number' => 'required_without:tax_number',
            'country_id' => 'required|integer|min:1',
            'email' => 'required|string|email|max:255|exists:users,email',
            'email-confirm' => 'required|same:email',
        );
        if(!Request::get('same_as_billing')){
            $rules = array_merge($rules, [
                'shipping_firstname'=>'required',
                'shipping_lastname'=>'required',
                'shipping_address'=>'required',
                'shipping_zipcode'=>'required',
                'shipping_city' => 'required',
                'shipping_salutation' => 'required'

            ]);
        }
        $data = [
            'user' => $user,
        ];
        $validator = Validator::make(Request::all(), $rules);

        if ($validator->fails()) {
            return view('user.edit', $data)->withErrors($validator);

        } else {
            $this->userRepo->update(Request::all());
            \Session()->flash('alert-save', true);
            return redirect(route('user_edit', [$user->id]));
        }
    }


   
    public function userDataStore(){

        $user = User::findOrFail(Auth::user()->id);
        if(!$user->account){
            $user->account = new UserAccount();
        }
        $rules = array(
            'salutation' => 'required',
            'last_name' => 'required|max:255',
            'country_id' => 'required|integer|min:1',
            'email' => 'required|string|email|max:255|exists:users,email',
            'email-confirm' => 'required|same:email',
        );
        if($user->active == 0){
            $rules['accepted_data_protection'] = 'required';
            $rules['accepted_active'] = 'required';
        }

        if(Request::get('company') == 1){
            $rules['company_name'] = 'required|max:255';
            $rules['company_country_id'] = 'required|integer|min:1';
        }

        $data = [
            'user' => $user,
        ];

        $validator = Validator::make(Request::all(), $rules);

        if ($validator->fails()) {

            // get the error messages from the validator
            $messages = $validator->messages();
            // redirect our user back to the form with the errors from the validator
            return view('user.edit', $data)->withErrors($validator);

        } else {
            $this->userRepo->update(Request::all());

            if($user->active == 0) {
                $account = $user->account;
                $account->data_protection = now();
                $account->save();

                $user->active = 1;
                $user->active_date = now();
                $user->save();
            }

            if(Request::get('accepted_active') == "on"){
                $user->agreement = now();
            }else{
                $user->agreement = null;
            }


            \Session()->flash('alert-save', true);
            return redirect('/home');
        }
    }
    
    public function userDataAcceptedForm(){
        $user = Auth::user();

        if(Request::get('accepted_active') == "on"){
            $user->agreement = now();
        }else {
            $user->agreement = null;
        }

        $user->save();
        \Session()->flash('alert-save', true);
        return redirect('/home');
    }

    public function userDataFree(){
        $user = Auth::user();
        $user->active = 1;
        $user->active_date = now();
        $user->save();
        return redirect('/home');

    }

    public function userDataFreeForm(){
        $user = Auth::user();

        $rules = array(
            'accepted_data_protection' => 'required'
        );

        $data = [
            'user' => $user,
        ];
        $validator = Validator::make(Request::all(), $rules);

        if ($validator->fails()) {
            // get the error messages from the validator
            $messages = $validator->messages();
            // redirect our user back to the form with the errors from the validator
            return view('home', $data)->withErrors($validator);
        } else {
            $account = $user->account;
            $account->data_protection = now();
            $account->save();

            if(Request::get('accepted_active') == "on"){
                $user->agreement = now();
            }else{
                $user->agreement = null;
            }



            $user->active = 1;
            $user->active_date = now();
            $user->save();

        }
        return redirect('/home');
    }

    public function userProfile(){
        $user = Auth::user();
        $data = [
            'user' => $user,
        ];
        return view('user.profile', $data);
    }

    public function userProfileStore(){
        $user = Auth::user();
        $data = Request::all();
        if($account = $user->account){
            $account->about_you = $data['about_you'] ? $data['about_you'] : null;
            $account->save();
        }
        \Session()->flash('alert-save', true);
        return redirect(route('user_profile'));
    }

     // Upload FILE  -----------------------------------------------------------------------------------------------------------------------
     public function imageUpload(){

        $user = Auth::user();
        try {
            $image = \App\Services\Slim::getImages('avatar')[0];
           
            if ( isset($image['output']['data']) )
            {
                // Original file name
                $name = $image['output']['name'];
                // Base64 of the image
                $data = $image['output']['data'];
                $file_ex = array( 'image/jpeg' => 'jpg', 'image/png' => 'png');

                    if (!isset($file_ex[$image['output']['type']])) {
                        \Session()->flash('alert-danger', 'File is not jpg or png!');
                        return redirect()->back();
                }

                $ext = $file_ex[$image['output']['type']];

                $data = \Storage::disk('user')->put(
                        $user->id.'/avatar.'.$ext, 
                        $data
                );
                
                \Session()->flash('alert-success', "Datei hochgeladen");
                return redirect()->back();
            }
            \Session()->flash('alert-danger', "Datei leer");
            return redirect()->back();
        }
        catch (\Exception $e) {
            \Session()->flash('alert-danger', "Fehler".$e);
            return redirect()->back();
        }
    }

    public function imageDelete($delete){
        $user = Auth::user();
        if($delete === 'avatar'){
            if($user->hasProfileImage()){
                \Storage::disk('user')->delete(str_replace('_', '/',  $user->getProfileImage()));
                \Session()->flash('alert-success', "Datei gelöscht");
                return redirect()->back();
            }
        }
       
    }

}