<?php

namespace App\Http\Controllers;

use App\Models\PaymentTransaction;
use App\Models\ShoppingOrder;
use App\Models\ShoppingPayment;
use App\Models\ShoppingUser;
use App\Models\UserShop;
use App\Services\CustomerPriority;
use App\Services\Payment;
use Request;

class SalesController extends Controller
{

    public function __construct(){
        $this->middleware('admin');
    }

    public function users(){

        if(Request::get('reset') === 'filter'){
            return redirect(route('admin_sales_users'));
        }
        $data = [

        ];
        return view('admin.sales.users', $data);
    }

    public function usersDetail($id)
    {
        $ShoppingOrder = ShoppingOrder::find($id);
        if($ShoppingOrder->shipped === 0){
            $ShoppingOrder->shipped = 1;
            $ShoppingOrder->save();
        }

        $data = [
           'shopping_order' => $ShoppingOrder,
           'isAdmin' => true,
           'isView' => 'sales_user',
        ];
        return view('admin.sales.user_detail', $data);
    }

    public function usersStore($id)
    {
        die("keine funktion");
        $data = [
            'shopping_order' => ShoppingOrder::find($id),
            'isAdmin' => true,
        ];
        return view('admin.sales.user_detail', $data);
    }

    public function usersDatatable(){

        $query = ShoppingOrder::with('shopping_user', 'shopping_payments')->select('shopping_orders.*')->where('shopping_orders.auth_user_id', '!=', NULL);

        return \DataTables::eloquent($query)
            ->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
                return '<a href="' . route('admin_sales_users_detail', [$ShoppingOrder->id]) . '" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
            })
            ->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->created_at->format("d.m.Y");
            })
            ->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
                return Payment::getShoppingOrderBadge($ShoppingOrder);
            })
            ->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->getFormattedTotalShipping()." €";
            })
            ->addColumn('payment', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->getLastShoppingPayment('getPaymentType');
            })
            ->addColumn('shipped', function (ShoppingOrder $ShoppingOrder) {
                return '<span class="badge badge-pill badge-'.$ShoppingOrder->getShippedColor().'">'.$ShoppingOrder->getShippedType().'</span>';
            })
            ->addColumn('is_for', function (ShoppingOrder $ShoppingOrder) {
                if($ShoppingOrder->shopping_user->is_for === 'me'){
                    return '<span class="badge badge-pill badge-secondary">Vertriebspartnerbestellung</span>';
                }
                if($ShoppingOrder->shopping_user->is_for === 'ot'){
                    return '<span class="badge badge-pill badge-info">Kundenbestellung</span>';
                }
                if($ShoppingOrder->shopping_user->is_for === 'hp'){
                    return '<span class="badge badge-pill badge-dark">Homepartybestellung</span>';
                }
                return '-';
            })
            ->addColumn('reference', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->getLastShoppingPayment('reference');
            })
            ->addColumn('orders', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->shopping_user ? $ShoppingOrder->shopping_user->orders : '';
            })
            ->orderColumn('id', 'id $1')
            ->orderColumn('txaction', 'txaction $1')
            ->orderColumn('shipped', 'shipped $1')
            ->orderColumn('total_shipping', 'total_shipping $1')

            ->rawColumns(['id', 'txaction', 'is_for', 'shipped'])
            ->make(true);
    }

    public function customers()
    {
        if(Request::get('reset') === 'filter'){
            set_user_attr('filter_txaction', null);
            set_user_attr('filter_member_id', null);
            return redirect(route('admin_sales_customers'));
        }
        $filter_members = ShoppingOrder::join('users', 'member_id', '=', 'users.id')->groupBy('member_id')->join('user_accounts', 'account_id', '=', 'user_accounts.id')->select('users.id', 'users.email', 'user_accounts.first_name', 'user_accounts.last_name')->get(); //->pluck('email', 'id')->unique()->toArray();
        $data = [
            'filter_members' => $filter_members,
        ];
        return view('admin.sales.customers', $data);
    }

    public function customersDetail($id)
    {
        $ShoppingOrder = ShoppingOrder::find($id);
        if($ShoppingOrder->shipped === 0){
            $ShoppingOrder->shipped = 1;
            $ShoppingOrder->save();
        }
        $data = [
            'shopping_order' => $ShoppingOrder,
            'isAdmin' => true,
            'isView' => 'sales_customer',
        ];
        return view('admin.sales.customer_detail', $data);
    }

    public function customersStore($id)
    {
        $data = Request::all();
        $change_member_error = false;
        if($data['action']==='shopping-order-change-member'){
            if(!isset($data['change_member_key']) || $data['change_member_key'] !== config('main.edit_data_pass')){
                $change_member_error = "Das Passwort ist falsch.";
            }else{
                //change
                $shopping_order = ShoppingOrder::findOrFail($data['id']);
                CustomerPriority::newMemberForOrder($shopping_order, $data['change_member_id'], $data['customer_set_member_for']);
                \Session()->flash('alert-save', true);
                return redirect(route('admin_sales_customers_detail', [$shopping_order->id]));
            }
        }
        if($data['action']==='shopping-user-is-like-member'){
            if(!isset($data['change_member_key']) || $data['change_member_key'] !== config('main.edit_data_pass')){
                    \Session()->flash('alert-error', 'Das Passwort ist falsch.');
                    return redirect($data['back']);
            }else{
                if(!isset($data['is_like_shopping_user_id'])){
                    \Session()->flash('alert-error', 'Keine Änderung ausgewählt');
                    return redirect($data['back']);
                }
                $shopping_user = ShoppingUser::findOrFail($data['id']);
                $set_like_shopping_user = ShoppingUser::findOrFail($data['is_like_shopping_user_id']);
                $send_member_mail = isset($data['send_member_mail']) ? true : false;
                $change_shopping_user = isset($data['change_shopping_user']) ? true : false;
                //Mail send in setIsLike
                CustomerPriority::setIsLike($shopping_user, $set_like_shopping_user, $send_member_mail, $change_shopping_user);
                \Session()->flash('alert-save', true);
                return redirect($data['back']);
            }
        }
        $data = [
            'change_member_error' => $change_member_error,
            'shopping_order' => ShoppingOrder::find($id),
            'isAdmin' => true,
            'isView' => 'sales_customer',
        ];
        return view('admin.sales.customer_detail', $data);
    }

    public function customersDatatable(){

        $query = ShoppingOrder::with('shopping_user')->select('shopping_orders.*')->where('shopping_orders.auth_user_id', NULL);

        set_user_attr('filter_txaction', Request::get('filter_txaction'));
        if(Request::get('filter_txaction') != ""){
            if(Request::get('filter_txaction') === 'NULL'){
                $query->where('txaction', '=', NULL);

            }else{
                $query->where('txaction', '=', Request::get('filter_txaction'));
            }
        }
        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('id', function (ShoppingOrder $ShoppingOrder) {
                return '<a href="' . route('admin_sales_customers_detail', [$ShoppingOrder->id]) . '" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
            })
            ->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->created_at->format("d.m.Y");
            })
            ->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
                return Payment::getShoppingOrderBadge($ShoppingOrder);
            })
            ->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->getFormattedTotalShipping()." €";
            })
            ->addColumn('payment', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->getLastShoppingPayment('getPaymentType');
            })
            ->addColumn('shipped', function (ShoppingOrder $ShoppingOrder) {
                return '<span class="badge badge-pill badge-'.$ShoppingOrder->getShippedColor().'">'.$ShoppingOrder->getShippedType().'</span>';
            })
            ->addColumn('is_for', function (ShoppingOrder $ShoppingOrder) {
                if($ShoppingOrder->shopping_user->is_for === 'me'){
                    return '<span class="badge badge-pill badge-secondary">Vertriebspartnerbestellung</span>';
                }
                if($ShoppingOrder->shopping_user->is_for === 'ot'){
                    return '<span class="badge badge-pill badge-info">Kundenbestellung</span>';
                }
                if($ShoppingOrder->shopping_user->is_for === 'hp'){
                    return '<span class="badge badge-pill badge-dark">Homepartybestellung</span>';
                }
                return '-';
            })
            ->addColumn('reference', function (ShoppingOrder $ShoppingOrder) {
                return $ShoppingOrder->getLastShoppingPayment('reference');
            })
            ->addColumn('member_id', function (ShoppingOrder $ShoppingOrder) {
                if($ShoppingOrder->member_id) {
                    return $ShoppingOrder->member_id ? '<a href="' . route('admin_lead_edit', [$ShoppingOrder->member_id]) . '">' . $ShoppingOrder->member->getFullName() . '</a>' : '';
                }
                if($ShoppingOrder->shopping_user && $ShoppingOrder->shopping_user->is_like){
                    return '<button type="button" class="btn btn-xs btn-outline-info" data-toggle="modal" data-target="#modals-load-content"
                               data-id="'.$ShoppingOrder->shopping_user->id.'"
                               data-action="shopping-user-is-like-member" 
                               data-back="'.route('admin_sales_customers').'" 
                               data-modal="modal-xl" 
                               data-route="'.route('modal_load').'"><span class="fa fa-edit"></span> Vertriebspartner zuordnen</button>';
                }
                return '';
            })



           ->orderColumn('id', 'id $1')
            ->orderColumn('txaction', 'txaction $1')
            ->orderColumn('member_id', 'member_id $1')
            ->orderColumn('shipped', 'shipped $1')
            ->orderColumn('total_shipping', 'total_shipping $1')
            ->rawColumns(['id', 'member_id', 'txaction', 'user_shop_id', 'is_for', 'shipped'])
            ->make(true);
    }

    public function store(){
        $data = Request::all();
        if(!isset($data['id'])){
            abort(404);
        }
        if(isset($data['action'])){
            if($data['action'] === 'store_shipped' && isset($data['shipped'])){
                $shopping_order = ShoppingOrder::findOrFail($data['id']);
                $shopping_order->shipped = $data['shipped'];
                $shopping_order->save();
            }

            if($data['action'] === 'store_txaction' && isset($data['txaction']) && isset($data['payment_id'])){
                $shopping_order = ShoppingOrder::findOrFail($data['id']);
                $shopping_payment = ShoppingPayment::findOrFail($data['payment_id']);

                $payt = PaymentTransaction::create([
                    'shopping_payment_id' => $shopping_payment->id,
                    'request' =>  'transaction',
                    'txid' => 0,
                    'userid' => 0,
                    'status' => $shopping_payment->clearingtype,
                    'transmitted_data' => NULL,
                    'txaction' => $data['txaction'],
                    'mode' => $shopping_payment->mode,
                ]);

                $shopping_order->txaction = $data['txaction'];
                $shopping_order->paid = true;
                $shopping_order->save();
                $shopping_payment->txaction = $data['txaction'];
                $shopping_payment->save();

                if($payt->status === 'vor' && $payt->txaction === 'paid'){
                    $send_link = Payment::paymentStatusPaidAction($shopping_order, false);
                }
                $edata = [
                    'mode' => $payt->mode,
                    'txaction' => $payt->txaction,
                    'send_link' => false,
                ];
                //TODO can send MAIL
                Payment::paymentStatusSendMail($shopping_order, $shopping_payment, $edata);
            }

        }
        if(isset($data['back'])){

            return redirect($data['back']);
        }
        return back();
    }

}