<?php

namespace App\Http\Controllers;

use Request;
use App\Models\Setting;
use App\Services\Payment;
use App\Models\ShoppingUser;
use App\Models\ShoppingOrder;
use App\Models\UserPayCredit;
use App\Models\ShoppingPayment;
use App\Models\PaymentTransaction;
use App\Services\CustomerPriority;
use App\Repositories\InvoiceRepository;
use App\Services\PaymentService;

class SalesController extends Controller
{

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

    public function index(){

        if(Request::get('reset') === 'filter'){
            set_user_attr('filter_txaction', null);
            set_user_attr('filter_member_id', null);
            set_user_attr('filter_art', null);
            set_user_attr('filter_shipped', null);
            return redirect(route('admin_sales'));
        }
        //set Filter!
        $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();
        $data = [
            'filter_members' => $filter_members,
        ];
        return view('admin.sales.index', $data);
    }

    public function detail($id){

        $ShoppingOrder = ShoppingOrder::find($id);
        if($ShoppingOrder->shipped == 0){
            $ShoppingOrder->shipped = 1;
            $ShoppingOrder->save();
        }
        $data = [
            'shopping_order' => $ShoppingOrder,
            'isAdmin' => true,
            'isView' => $ShoppingOrder->auth_user_id ? 'sales_user' : 'sales_customer',
        ];

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

    public function detailStore($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_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']);
            }
        }
        $ShoppingOrder = ShoppingOrder::find($id);
        $data = [
            'change_member_error' => $change_member_error,
            'shopping_order' => $ShoppingOrder,
            'isAdmin' => true,
            'isView' => $ShoppingOrder->auth_user_id ? 'sales_user' : 'sales_customer',
        ];
        return view('admin.sales.detail', $data);
    }

    public function datatable(){

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

        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'));
        }
        
        set_user_attr('filter_art', Request::get('filter_art'));
        if(Request::get('filter_art') != ""){
            if(Request::get('filter_art') === 'user_order'){
                $query->where('shopping_orders.auth_user_id', '!=', NULL)->where('payment_for', '!=', 6);
            }elseif(Request::get('filter_art') === 'customer_order'){
                $query->where('shopping_orders.auth_user_id', NULL);
            }elseif(Request::get('filter_art') === 'user_for_customer'){
                $query->where('shopping_user_id', '!=', NULL)->where('payment_for', '=', 6);
            }
          //  $query->where('payment_for', '=', Request::get('filter_art'));
        }
        set_user_attr('filter_shipped', Request::get('filter_shipped'));
        if(Request::get('filter_shipped') != ""){
            $query->where('shipped', '=', Request::get('filter_shipped'));
        }
        return \DataTables::eloquent($query)
            ->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
                return '<a href="' . route('admin_sales_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('payment_for', function (ShoppingOrder $ShoppingOrder) {
                return Payment::getPaymentForTypeBadge($ShoppingOrder);
            })
            ->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').'" 
                               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('payment_for', 'payment_for $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', 'payment_for', 'shipped'])
            ->make(true);
    }

    /*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('payment_for', function (ShoppingOrder $ShoppingOrder) {
                return Payment::getPaymentForTypeBadge($ShoppingOrder);
            })
            ->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('payment_for', 'payment_for $1')
            ->orderColumn('shipped', 'shipped $1')
            ->orderColumn('total_shipping', 'total_shipping $1')

            ->rawColumns(['id', 'txaction', 'payment_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'));
        }
        $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_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._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_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('payment_for', function (ShoppingOrder $ShoppingOrder) {
                return Payment::getPaymentForTypeBadge($ShoppingOrder);
            })
            ->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').'" 
                               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('payment_for', 'payment_for $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', 'payment_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();
                //handel Promotion Product and credit by storno
                Payment::handelUserPromotionOrder($shopping_order);
                Payment::handelUserShopOrder($shopping_order);

                if($shopping_order->getAPIShippedType() === 'sent' ||  $shopping_order->getAPIShippedType() === 'close'){
                    if(!$shopping_order->shipped_at){
                        $shopping_order->shipped_at = now();
                        $shopping_order->save();
                        //is shipped set pending_to 
                        if($shopping_order->shopping_order_margin){
                            if($shopping_order->shopping_order_margin->hasPartnerCommission()){
                            $days = Setting::getContentBySlug('pending_partner_commissions_in_days');
                                $days = $days ? $days : 20;
                                $partner_commission_pending_to = $shopping_order->shipped_at;
                                $partner_commission_pending_to->addDays($days);
                                $shopping_order->shopping_order_margin->partner_commission_pending_to = $partner_commission_pending_to;
                                $shopping_order->shopping_order_margin->save();
                            }else{
                                $days = Setting::getContentBySlug('pending_order_margins_in_days');
                                $days = $days ? $days : 20;
                                $margin_pending_to = $shopping_order->shipped_at;
                                $margin_pending_to->addDays($days);
                                $shopping_order->shopping_order_margin->margin_pending_to = $margin_pending_to;
                                $shopping_order->shopping_order_margin->save();
                            }
                        }
                    }
                }else{
                    $shopping_order->shipped_at = null;
                    $shopping_order->save();
                    if($shopping_order->shopping_order_margin){
                        //zurücksetzen der pending_to
                        $shopping_order->shopping_order_margin->partner_commission_pending_to = null;
                        $shopping_order->shopping_order_margin->margin_pending_to = null;
                        $shopping_order->shopping_order_margin->save();
                    }
                }
                if($shopping_order->getAPIShippedType() === 'cancel'){
                    if($shopping_order->shopping_order_margin){
                        $shopping_order->shopping_order_margin->cancellation = true;
                        $shopping_order->shopping_order_margin->partner_commission_pending_to = null;
                        $shopping_order->shopping_order_margin->margin_pending_to = null;
                        $shopping_order->shopping_order_margin->save();
                    }
                }else{
                    if($shopping_order->shopping_order_margin && $shopping_order->shopping_order_margin->cancellation){
                        $shopping_order->shopping_order_margin->cancellation = false;
                        $shopping_order->shopping_order_margin->partner_commission_pending_to = null;
                        $shopping_order->shopping_order_margin->margin_pending_to = null;
                        $shopping_order->shopping_order_margin->save();
                    }
                }


            }
            
        
            /* txaction ändern
                änderung der txaction von der Bestellung, Status Zahlung, offen, bezahlt, keine zahlung */
            if($data['action'] === 'store_txaction' && isset($data['txaction']) && isset($data['payment_id'])){
                PaymentService::updateTransactionStatus($data['id'], $data['txaction'], $data['payment_id']);
            }

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


    public function invoice(){
        $data = Request::all();
        if(!isset($data['id'])){
            abort(404);
        }
        if(isset($data['action'])){
            if($data['action'] === 'create_invoice'){
                $shopping_order = ShoppingOrder::findOrFail($data['id']);
                $invoice_repo = new InvoiceRepository($shopping_order);
                if(\App\Services\Invoice::isInvoice($shopping_order)){
                    $user_invoice = $invoice_repo->update($data);
                }else{
                    $user_invoice = $invoice_repo->create($data);
                }
                return redirect(route('admin_sales_detail', [$shopping_order->id]));
            }
        }
    }

    public function sendLogisticMail($id){
        $shopping_order = ShoppingOrder::findOrFail($id);
       
        if(\App\Services\Invoice::isInvoice($shopping_order)){
            \App\Services\Invoice::sendLogisticMail($shopping_order);
            \Session()->flash('alert-success', "Rechnung / Lieferschein wurde an den Versand gesendet.");
        }else{
            \Session()->flash('alert-error', "Keine Rechnung vorhanden.");
        }
        return redirect(route('admin_sales_detail', [$shopping_order->id]));
    }

}