<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\ShoppingUser;
use App\Repositories\CustomerRepository;
use App\Services\CustomerPriority;
use App\Services\HTMLHelper;
use App\User;
use Illuminate\Support\Collection;
use Request;
use Validator;


class CustomerController extends Controller
{
    protected $customerRepository;

    public function __construct(CustomerRepository $customerRepository)
    {
        $this->middleware('active.account');
        $this->customerRepository = $customerRepository;

    }

    public function index()
    {
        if(Request::get('reset') === 'filter'){
           // set_user_attr('filter_member_id', null);
           // set_user_attr('filter_customer_member', null);
            return redirect(route('admin_customers'));
        }
        $data = [

        ];
        return view('user.customer.index', $data);
    }


    public function detail($id)
    {
        $shopping_user = ShoppingUser::findOrFail($id);
        if($shopping_user->member_id != \Auth::user()->id){
            abort(404);
        }
        $data = [
            'shopping_user' => $shopping_user,
            'isAdmin' => false,
            'isView' => 'customer',

        ];
        return view('user.customer.detail', $data);
    }

    public function edit($id)
    {
        $shopping_user = ShoppingUser::findOrFail($id);
        if($shopping_user->member_id != \Auth::user()->id){
            abort(404);
        }
        $data = [
            'shopping_user' => $shopping_user,
            'isAdmin' => false,
            'isView' => 'customer',

        ];
        return view('user.customer.edit', $data);
    }

    public function add($id, $step=0)
    {
        if($id === "new"){
            $shopping_user = new ShoppingUser();
            $shopping_user->id = "new";
        }else{
            $shopping_user = ShoppingUser::findOrFail($id);
            if($shopping_user->member_id != \Auth::user()->id){
                abort(404);
            }
        }

        $billing_email = null;
        if(!session('errors')){
            if(old('email') || old('billing_email')){
                $step = 1;
                $shopping_user->same_as_billing = true;
                $billing_email = old('email');
            }
            if(old('switcher-without-email') === 'true'){
                $step = 1;
                $shopping_user->same_as_billing = true;
                $shopping_user->faker_mail = true;
                $billing_email = time()."-faker@gruene-seele.bio";
            }
        }
        $data = [
            'shopping_user' => $shopping_user,
            'isAdmin' => false,
            'isView' => $step === 0 ? 'customer' : 'customer-add',
            'step' => $step,
            'billing_email' => $billing_email,

        ];
        return view('user.customer.add', $data);
    }

    private function checkShoppingUsersEmail($data){
        $rules = array(
            'email' => 'required|string|email|max:255|unique:shopping_users,billing_email',
        );
        $messages = [
            'unique'    => __('validation.custom.unique_email_client'),
        ];
        $validator = Validator::make(Request::all(), $rules, $messages);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput(Request::all());
        }

        $rules = array(
            'email' => 'required|string|email|max:255|unique:users,email',
        );
        $messages = [
            'unique'    => __('validation.custom.unique_email_member'),
        ];
        $validator = Validator::make(Request::all(), $rules, $messages);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput(Request::all());
        }

        return back()->withInput(Request::all());
    }

    public function store($id)
    {
        $data = Request::all();

        if($id === 'new' && $data['action'] === 'add_customer_with_email'){
            return $this->checkShoppingUsersEmail($data);
        }
        if($id === 'new' && $data['action'] === 'add_customer_without_email'){
            return back()->withInput(Request::all());
        }

        if($data['action'] === 'shopping-user-store-new' || $data['action']==='shopping-user-store'){
            $rules = array(
                'billing_salutation' => 'required',
                'billing_firstname'=>'required',
                'billing_lastname'=>'required',
                'billing_email'=>'required|email',
                'billing_address'=>'required',
                'billing_zipcode'=>'required',
                'billing_city' => 'required',
                'billing_country_id' => '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'
                ]);
            }
            $validator = Validator::make(Request::all(), $rules);
            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput(Request::all());
            }
        }

        $data['faker_mail'] = isset($data['faker_mail']) ? true : false;
        $data['has_buyed'] = isset($data['has_buyed']) ? true : false;
        $data['subscribed'] = isset($data['subscribed']) ? true : false;
        //subscribed can only true when has_buyed ist active
        $data['subscribed'] = $data['has_buyed'] ? $data['subscribed'] : false;

        $data['same_as_billing'] = isset($data['same_as_billing']) ? true : false;
        $data['shipping_country_id'] = isset($data['shipping_country_id']) ? $data['shipping_country_id'] : $data['billing_country_id'];

        if($id > 0 && $data['action'] === 'shopping-user-store'){
            $shopping_user = ShoppingUser::findOrFail($id);
            if($shopping_user->member_id != \Auth::user()->id){
                abort(404);
            }
            CustomerPriority::checkChangeOne($shopping_user, $data, true);
            $shopping_user->fill($data);
            $shopping_user->save();

        }

        if($id === 'new' && $data['action'] === 'shopping-user-store-new') {
            $shopping_user = ShoppingUser::create($data);
            $shopping_user->member_id = \Auth::user()->id;
            $shopping_user->save();
            CustomerPriority::checkNewOne($shopping_user, true);
        }
        \App\Services\Shop::newUserOrder($shopping_user->number);

        if($shopping_user->is_like){
            \Session()->flash('custom-error', __('validation.custom.match_found'));
        }

        \Session()->flash('alert-save', true);
        return redirect(route('user_customer_detail', [$shopping_user->id]));
    }

    public function getCustomers()
    {
        $user = User::find(\Auth::user()->id);

        $query = ShoppingUser::select(['id', 'billing_company', 'billing_salutation', 'billing_firstname', 'billing_lastname', 'billing_email', 'faker_mail', 'billing_zipcode', 'billing_city', 'billing_country_id', 'orders', 'subscribed', 'created_at', 'number', 'mode', 'is_like', 'wp_order_number'])
            ->where('shopping_users.member_id', '=', $user->id);
            //->groupBy('shopping_users.number');

        /*set_user_attr('filter_member_id', Request::get('filter_member_id'));
        if(Request::get('filter_member_id') != ""){
            $query->where('member_id', '=', Request::get('filter_member_id'));
        }*/
        return \DataTables::eloquent($query)

            ->addColumn('send_to', function (ShoppingUser $ShoppingUser) {
                return $ShoppingUser->is_like ? '<span class="badge badge-pill badge-warning"><i class="fa fa-clock"></i> in Prüfung</span>' : '<a href="' . route('user_order_my_delivery', ['ot', $ShoppingUser->id]) . '" class="btn btn-sm btn-secondary"><span class="fa fa-shopping-cart"></span> wählen</a>';
            })
            ->addColumn('billing_email', function (ShoppingUser $ShoppingUser) {
                return $ShoppingUser->faker_mail ? "-" : $ShoppingUser->billing_email;
            })
            ->addColumn('id', function (ShoppingUser $ShoppingUser) {
                return '<a href="' . route('user_customer_detail', [$ShoppingUser->id]) . '" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
            })
            ->addColumn('billing_salutation', function (ShoppingUser $ShoppingUser) {
                return HTMLHelper::getSalutationLang($ShoppingUser->billing_salutation);
            })
            ->addColumn('billing_country_id', function (ShoppingUser $ShoppingUser) {
                return $ShoppingUser->billing_country ? $ShoppingUser->billing_country->getLocated() : '';
            })
            ->addColumn('first_created_at', function (ShoppingUser $ShoppingUser) {
                return $ShoppingUser->firstEntryByNumber()->created_at->format('d.m.Y');
            })
            ->addColumn('orders', function (ShoppingUser $ShoppingUser) {
                return $ShoppingUser->lastEntryByNumber()->orders;
            })
            ->addColumn('subscribed', function (ShoppingUser $ShoppingUser) {
                return get_active_badge($ShoppingUser->subscribed);
            })
            ->addColumn('status', function (ShoppingUser $ShoppingUser) {
                return $ShoppingUser->is_like ? '<span class="badge badge-pill badge-warning"><i class="fa fa-clock"></i> in Prüfung</span> ' : '<span class="badge badge-pill badge-success"><i class="fa fa-check-circle"></i> zugewiesen</span>';
            })
            ->addColumn('extras', function (ShoppingUser $ShoppingUser) {
                return $ShoppingUser->wp_order_number.($ShoppingUser->mode==='dev' ? ' <span class="badge badge-warning">dev</span>' : '');
            })
            ->filterColumn('billing_email', function($query, $keyword) {
                if($keyword != ""){
                    $query->where('billing_email', 'LIKE', '%'.$keyword.'%');
                }
            })
            ->orderColumn('send_to', 'id $1')
            ->orderColumn('id', 'id $1')
            ->orderColumn('billing_email', 'billing_email $1')
            ->orderColumn('billing_country_id', 'billing_country_id $1')
            ->orderColumn('billing_salutation', 'billing_salutation $1')
            ->orderColumn('first_created_at', 'created_at $1')
            ->orderColumn('orders', 'orders $1')
            ->orderColumn('subscribed', 'subscribed $1')
            ->rawColumns(['send_to', 'id', 'subscribed', 'extras', 'status'])
            ->make(true);
    }
}