<?php


namespace App\Http\Controllers;
use App\Repositories\UserRepository;
use Auth;
use Input;
use Validator;


class UserDataController extends Controller
{

    protected $userRepo;

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

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function userEdit(){
        $user = Auth::user();

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

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function userEditStore(){

        $user = Auth::user();
        /*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(Input::get('company') == 1){
            $rules['company_name'] = 'required|max:255';
            $rules['company_country_id'] = 'required|integer|min:1';
        }

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

        $validator = Validator::make(Input::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(Input::all());
            \Session()->flash('alert-save', true);
            return redirect('/user/edit');
        }
    }

    /**
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function userDataAcceptedForm(){
        $user = Auth::user();

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

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

}