<?php

namespace App\Http\Controllers;

use App\Mail\MailReleaseAccount;
use App\Models\File;
use App\Models\Product;
use App\Models\ShoppingInstance;
use App\Models\UserAccount;
use App\Models\UserHistory;
use App\Models\UserLevel;
use App\Repositories\FileRepository;
use App\Services\Util;
use App\User;
use Auth;
use Hash;
use Illuminate\Support\Facades\Mail;
use Request;
use Validator;
use Yard;

class WizardController extends Controller
{

    protected $fileRepo;


    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(FileRepository $fileRepo)
    {
        $this->fileRepo = $fileRepo;

    }

    public function create()
    {
        if(!Auth::check()){
            return redirect('login');
        }

        $user = User::findOrFail(Auth::user()->id);
        if(!$user->account){
            $account = UserAccount::create([]);
            $user->account_id = $account->id;
            $user->save();
            return redirect(route('wizard_create'));
        }

        $step = !$user->wizard ? 0 : $user->wizard;

        if($step >= 20){
            return redirect('/home');
        }
        $userHistoryWizardPayment = UserHistory::whereUserId($user->id)->whereAction('wizard_payment')->get()->last();

        $data = [
            'user' => Auth::user(),
            'step' => $step,
            'products' =>  Product::where('active', true)->where('show_at', '=', 3)->orderBy('pos', 'ASC')->get(),
            'products_on_board' => Product::where('active', true)->where('show_at', '=', 5)->orderBy('pos', 'ASC')->get(),
            'userHistoryWizardPayment' => $userHistoryWizardPayment,
        ];

        if($step == 15){
            return view('user.wizard.create_release', $data);
        }

        return view('user.wizard.create', $data);
    }

    public function register()
    {

        if(!Auth::check()){
            return redirect('login');
        }
        $user = User::findOrFail(Auth::user()->id);
        if(!$user->account){
            $account = UserAccount::create([]);
            $user->account_id = $account->id;
            $user->save();
            return redirect(route('wizard_register'));
        }

        $step = !$user->wizard ? 0 : $user->wizard;

        if($step >= 10){
            return redirect('/home');
        }

        $data = [
            'user' => Auth::user(),
            'step' => $step,
            'user_levels' => UserLevel::where('active', true)->get(),
            //'products' =>  Product::where('active', true)->where('show_at', '=', 3)->orderBy('pos', 'ASC')->get(),
            //'products_on_board' => Product::where('active', true)->where('show_at', '=', 5)->orderBy('pos', 'ASC')->get(),
        ];
        if($step == 5){
            return view('user.wizard.register_release', $data);
        }

        return view('user.wizard.register', $data);
    }

    public function payment()
    {
        if(!Auth::check()){
            return redirect('login');
        }

        $user = User::findOrFail(Auth::user()->id);
        if(!$user->account){
            $account = UserAccount::create([]);
            $user->account_id = $account->id;
            $user->save();
            return redirect(route('wizard_payment'));
        }

        $userHistoryWizardPayment = UserHistory::whereUserId($user->id)->whereAction('wizard_payment')->get()->last();

        $data = [
            'user' => Auth::user(),
            'step' => 0,
            'products' =>  Product::where('active', true)->where('show_at', '=', 3)->orderBy('pos', 'ASC')->get(),
            'products_on_board' => Product::where('active', true)->where('show_at', '=', 5)->orderBy('pos', 'ASC')->get(),
            'userHistoryWizardPayment' => $userHistoryWizardPayment,
        ];

        if($user->wizard == 20){
            return view('user.wizard.register_payment', $data);
        }

        return redirect(route('/'));
    }

    public function storeRegister($step = false)
    {

        if (!Auth::check()) {
            return redirect('login');
        }

        $user = User::findOrFail(Auth::user()->id);
        if (!$user->account) {
            $user->account = new UserAccount();
        }

        if ($step == 0) {
            $rules = array(
                'accepted_data_protection' => 'required',
                'accepted_active' => 'required',
                'accepted_contract' => 'required'
            );
            $validator = Validator::make(Request::all(), $rules);
            if ($validator->fails()) {
                $data = [
                    'user' => Auth::user(),
                    'step' => $step,
                    'user_levels' => UserLevel::where('active', true)->get(),
                    //'products' =>  Product::where('active', true)->where('show_at', '=', 3)->orderBy('pos', 'ASC')->get(),
                    //'products_on_board' => Product::where('active', true)->where('show_at', '=', 5)->orderBy('pos', 'ASC')->get(),
                ];
                $user->wizard = 0;
                $user->save();
                return view('user.wizard.register', $data)->withErrors($validator);
            }
            $account = $user->account;
            if($account->accepted_contract === null){
                $account->accepted_contract = now();
            }
            if($account->data_protection === null){
                $account->data_protection = now();
            }
            $account->save();
            if($user->agreement === null){
                $user->agreement = now();
            }

            $user->wizard = 1;
            $user->save();
            return redirect(route('wizard_register'));
        }
        if ($step == 1) {
            $rules = array(
                'salutation' => 'required',
                'first_name' => 'required',
                'last_name' => 'required',
                'address' => 'required',
                'zipcode' => 'required',
                'city' => 'required',
                'phone' => 'required_without:mobil',
                'mobil' => 'required_without:phone',
                'country_id' => 'required|integer|min:1',
                'birthday' => 'required',
            );

            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',
                    'shipping_country_id' => 'required|integer|min:1',
                ]);
            }
            $validator = Validator::make(Request::all(), $rules);
            if ($validator->fails()) {
                $user->wizard = 1;
                $user->save();
                return redirect(route('wizard_register', [1]))->withErrors($validator)->withInput(Request::all());
            }
            $data = Request::all();
            $data['same_as_billing'] = Request::get('same_as_billing') == NULL ? 0 : 1;
            $user->account->fill($data)->save();
            $user->wizard = 2;
            $user->save();
            return redirect(route('wizard_register'));
        }

        if ($step == 2) {
             if(Request::get('submit') === 'do'){
                 if(File::whereUserId($user->id)->whereIdentifier('id_card')->count() == 0){
                     $validator = Validator::make(Request::all(), []);
                     $validator->errors()->add('field', __('Kein Ausweis hinterlegt, bitte erst hochladen.'));
                     $user->wizard = 2;
                     $user->save();
                     return redirect(route('wizard_register'))->withErrors($validator)->withInput(Request::all());
                 }
                 $user->wizard = 3;
                 $user->save();
                 return redirect(route('wizard_register'));
             }
            $this->fileRepo->_set('disk', 'user');
            $this->fileRepo->_set('dir', '/'.$user->id.'/verification/');
            $this->fileRepo->_set('user_id', $user->id);
            $this->fileRepo->_set('identifier', 'id_card');
            return  $this->fileRepo->uploadFile(Request::all());
        }

        if ($step == 3) {
            if(Request::get('submit') === 'do'){
                $data = Request::all();

                if($data['business_license_choose'] === "now"){
                    if(File::whereUserId($user->id)->whereIdentifier('business_license')->count() == 0){
                        $validator = Validator::make(Request::all(), []);
                        $validator->errors()->add('field', __('Kein Gewerbeschein hinterlegt, bitte erst hochladen.'));
                        $user->wizard = 3;
                        $user->save();
                        return redirect(route('wizard_register'))->withErrors($validator)->withInput(Request::all());
                    }
                }
                if($data['business_license_choose'] === "later"){

                }
                if($data['business_license_choose'] === "non"){
                    if(!$data['non_business_license_reason'] || $data['non_business_license_reason'] == ""){
                        $validator = Validator::make(Request::all(), []);
                        $validator->errors()->add('field', __('Bitte gib eine Begründung ein, warum Du keinen Gewerbeschein benötigst.'));
                        $user->wizard = 3;
                        $user->save();
                        return redirect(route('wizard_register'))->withErrors($validator)->withInput(Request::all());
                    }else{
                        $user->account->setNotice('business_license_reason', $data['non_business_license_reason']);
                    }
                }

                $user->account->setNotice('business_license', $data['business_license_choose']);
                $user->wizard = 4;
                $user->save();

                return redirect(route('wizard_register'));
            }
            $this->fileRepo->_set('disk', 'user');
            $this->fileRepo->_set('dir', '/'.$user->id.'/verification/');
            $this->fileRepo->_set('user_id', $user->id);
            $this->fileRepo->_set('identifier', 'business_license');
            return  $this->fileRepo->uploadFile(Request::all());
        }

        if ($step == 4) {

            $data = Request::all();

            if(!isset($data['switchers-package-wizard'])){
                $validator = Validator::make(Request::all(), []);
                $validator->errors()->add('field', __('Bitte wähle erst Deine Mitgildschaft aus.'));
                return redirect(route('wizard_register'))->withErrors($validator)->withInput(Request::all());
            }

            $user->m_level = $data['switchers-package-wizard'];
            $user->next_m_level = $data['switchers-package-wizard'];
            $user->wizard = 5;
            $user->release_account = now();
            UserHistory::create(['user_id' => $user->id, 'action'=>'release_account', 'status'=>0]);
            $user->save();

            if($user->isTestMode()){
                $mail = config('app.info_test_mail');
            }else{
                $mail = config('app.info_mail');
            }
            Mail::to($mail)->send(new MailReleaseAccount($user));

            return redirect(route('wizard_register'));
        }
    }

    public function storeCreate($step = 0)
    {

        if(!Auth::check()){
            return redirect('login');
        }

        $user = User::findOrFail(Auth::user()->id);
        if(!$user->account){
            $user->account = new UserAccount();
        }

        if($step == 10){
            $rules = array(
                'accepted_data_protection' => 'required',
                'accepted_active' => 'required',
            );
            $validator = Validator::make(Request::all(), $rules);
            if ($validator->fails()) {
                $data = [
                    'user' => Auth::user(),
                    'step' => $step,
                    'products' =>  Product::where('active', true)->where('show_at', '=', 3)->orderBy('pos', 'ASC')->get(),
                    'products_on_board' => Product::where('active', true)->where('show_at', '=', 5)->orderBy('pos', 'ASC')->get(),
                ];
                $user->wizard = 10;
                $user->save();
                return view('user.wizard.create', $data)->withErrors($validator);

            }
            $account = $user->account;
            if($account->accepted_contract === null){
                $account->accepted_contract = now();
            }
            if($account->data_protection === null){
                $account->data_protection = now();
            }
            $account->save();
            if($user->agreement === null){
                $user->agreement = now();
            }
            $user->wizard = 11;
            $user->save();

            return redirect(route('wizard_create', [11]));
        }
        if($step == 11){

            if($user->isPasswort()){
                $user->wizard = 12;
                $user->save();
                return redirect(route('wizard_create', [12]));
            }
            $rules = array(
                'password' => 'required|string|min:6|confirmed',
            );
            $validator = Validator::make(Request::all(), $rules);
            if ($validator->fails()) {
                $data = [
                    'user' => Auth::user(),
                    'step' => $step,
                    'products' =>  Product::where('active', true)->where('show_at', '=', 3)->orderBy('pos', 'ASC')->get(),
                    'products_on_board' => Product::where('active', true)->where('show_at', '=', 5)->orderBy('pos', 'ASC')->get(),
                ];
                return view('user.wizard.create', $data)->withErrors($validator);
            }

            $user->fill([
                'password' => Hash::make(Request::get('password'))
            ])->save();
            $user->wizard = 12;

            $user->save();
            return redirect(route('wizard_create', [12]));
        }
        if($step == 12){
            $rules = array(
                'salutation' => 'required',
                'first_name' => 'required',
                'last_name' => 'required',
                'address' => 'required',
                'zipcode' => 'required',
                'city' => 'required',
                'phone' => 'required_without:mobil',
                'mobil' => 'required_without:phone',
                'country_id' => 'required|integer|min:1',
                'birthday' => 'required',
            );

            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'

                ]);
            }
            $validator = Validator::make(Request::all(), $rules);
            if ($validator->fails()) {
                return redirect(route('wizard_create', [12]))->withErrors($validator)->withInput(Request::all());
            }

            $data = Request::all();
            $data['same_as_billing'] = Request::get('same_as_billing') == NULL ? 0 : 1;
            $user->account->fill($data)->save();

            $user->wizard = 13;
            $user->active_date = now();
            $user->active = 1;
            $user->confirmation_code = null;
            $user->confirmation_code_to = null;
            $user->confirmation_code_remider = 0;
            $user->save();
            return redirect(route('wizard_create', [13]));

        }
    }

    public function storePayment($step = 0){

        if(Request::get('switchers-package-wizard')){
            $user = User::find(Auth::user()->id);
            Yard::instance('shopping')->destroy();
            $product = Product::find(Request::get('switchers-package-wizard'));
            /*$showAboOptions = false;
            if(Request::get('abo_options')){
                $showAboOptions = true;
                $user->abo_options = true;
                $user->save();
            }*/
            if($product && $product->active && $product->show_at == 3){
                //set membership product
                $image = "";
                if($product->images->count()){
                    $image = $product->images->first()->slug;
                }
                Yard::instance('shopping')->add($product->id, $product->getLang('name'), 1, $product->price, $product->tax, ['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight]);

                //set onboarding products
                if(Request::get('products_on_board')){
                    foreach (Request::get('products_on_board') as $product_on_board_id){
                        $product_on_board = Product::find($product_on_board_id);
                        $image = "";
                        if($product_on_board->images->count()){
                            $image = $product_on_board->images->first()->slug;
                        }
                        Yard::instance('shopping')->add($product_on_board->id, $product_on_board->getLang('name'), 1, $product_on_board->price, $product->tax, ['image' => $image, 'slug' => $product_on_board->slug, 'weight' => $product_on_board->weight]);
                    }
                }

                /*do {
                    $identifier = Util::getToken();
                } while( ShoppingInstance::where('identifier', $identifier)->count() );
                */
                $identifier = Util::getToken();

                $data = [];
                $data['is_from'] = 'wizard';
                $data['is_for'] = 'me';


                /*ShoppingInstance::create([
                    'identifier' => $identifier,
                    'user_shop_id' => 1, //is first faker shop for buy intern
                    'auth_user_id' => Auth::user()->id,
                    'payment' => 4, //Vertriebspartner Wizard
                    'subdomain' => url('/'),
                    'country_id' => Yard::instance('shopping')->getShippingCountryId(),
                    'shopping_data' => $data,
                    'back' => url()->previous(),

                ]);*/
                Yard::instance('shopping')->putYardExtra('shopping_data', $data);
                //Yard::instance('shopping')->store($identifier);
                //add to DB
                //$path = route('checkout.checkout_card', ['identifier'=>$identifier]);
                UserHistory::create(['user_id' => $user->id, 'action'=>'wizard_payment', 'status'=>1, 'product_id'=>$product->id, 'identifier'=>$identifier]);
                //$path = str_replace('http', 'https', $path);
                //return redirect()->secure($path);
                return redirect(route('user_checkout', [$identifier]));


            }
        }
        \Session()->flash('alert-error', "Fehler beim Produkt");
        return back();
    }

    public function delete($id, $relation){

        if($relation === 'upload'){
            $user = User::findOrFail(Auth::user()->id);
            $file = $user->files()->findOrFail($id);
            //remove file
            \Storage::disk('user')->delete($file->dir.$file->filename);
            $file->delete();
            \Session()->flash('alert-success', "Datei gelöscht");
        }
        return back();
    }


}