<?php


namespace App\Http\Controllers;

use App\Models\Models\UserCreditMargin as ModelsUserCreditMargin;
use App\Models\ShoppingOrderMargin;
use App\Models\UserCredit;
use App\Models\UserCreditMargin;
use App\Repositories\CreditRepository;
use App\Services\Credit;
use App\Services\Payment;
use App\Services\Payment\UserBot;
use App\Services\Util;
use App\User;
use Carbon;
use Illuminate\Support\Collection;
use Request;

class PaymentCreditController extends Controller
{

    private $startYear;
    private $endYear;
    private $rangeYears;
    private $activeYear;
    private $userBot;

    public function __construct(UserBot $userBot)
    {
        $this->middleware('auth');
        $this->userBot = $userBot;
        $this->startYear = 2021;
        $this->endYear = date('Y');
        $this->rangeYears = range($this->startYear, $this->endYear);
        $this->activeYear = $this->endYear;

    }

    public function index()
    {
        $data = $this->makeData();
        return view('admin.payment.credit.index', $data);
    }

   
    /**
     * fügt eine neue Manuelle Gutschrift hinzu
     * 
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(){
        $data = Request::all();

        if(isset($data['action']) && $data['action'] === 'add-user-credit'){
            $add_credit_error = false;
            if(!isset($data['member_id']) || !$user = User::find($data['member_id'])){
                $add_credit_error = 'Vertriebspartner nicht gefunden';
            }
            if(!isset($data['credit'])){
                $add_credit_error = 'Bitte Betrag eingeben';
            }
            if(!isset($data['message'])){
                $add_credit_error = 'Bitte Mitteilung eingeben';
            }
            if($add_credit_error){
                $data = $this->makeData();
                $data['add_credit_error'] = $add_credit_error;
                return view('admin.payment.credit.index', $data);
            }

            $credit = Util::reFormatNumber($data['credit']);
            $credit = number_format($credit, 2, '.', '');      
            Payment::addUserCreditMargin($user, $credit, 3, $data['message']);
            \Session()->flash('alert-success', "Guthaben hinzugefügt");
        }

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

    /**
     * Erstellt eine neue komplette Gutschrift für einen Benutzer
     * 
     * @return \Illuminate\Http\RedirectResponse
     */
    public function create(){
        $data = Request::all();
        if(isset($data['action'])){
            if($data['action'] === 'create_credit'){
                if(!isset($data['userid'])){
                    abort(404);
                }
                $user = User::findOrFail($data['userid']);
                $invoice_repo = new CreditRepository($user);
                $invoice_repo->create($data);
                \Session()->flash('alert-success', "Gutschrift erstellt");
                return redirect($data['back']);
            }
            if($data['action'] === 'user-credit-status'){
                $UserCredit = UserCredit::findOrFail($data['id']);
                $UserCredit->status = $data['status'];
                $UserCredit->save();
                \Session()->flash('alert-success', "Status gespeichert");
                return back();
            }
        }
    }

    private function makeData(): array
    {
        $this->setActiveYears();
        $this->userBot->readUserHasCredits();
        $this->userBot->readUserHasPendingCredit();
        
        return [
            'years' => $this->rangeYears,
            'active_year' => $this->activeYear,
            'users_credits' => $this->userBot->getUsers(),
            'users_credits_pending' => $this->userBot->getUsersPending(),
        ];
    }

    private function setActiveYears(){
        if(Request::get('filter_sales_year')){
            $this->activeYear = Request::get('filter_sales_year');
        }
    }

    public function delete($id, $del){

        if($del === 'user_credit_margin'){
            $UserCreditMargin = UserCreditMargin::findOrFail($id);
            if($deleteTime = $UserCreditMargin->deleteTime()){
                $UserCreditMargin->delete();
                \Session()->flash('alert-success', "Guthaben ist gelöscht");
            }else{
                \Session()->flash('alert-error', "Guthaben kann nicht gelöscht werden");
            }
        }
        if($del === 'shopping_order_margin'){
            $ShoppingOrderMargin = ShoppingOrderMargin::findOrFail($id);
            $ShoppingOrderMargin->out_paid = true;
            $ShoppingOrderMargin->save();
            \Session()->flash('alert-success', "Gutschrift ist gelöscht");
        }
        return redirect(route('admin_payments_credit'));
    }

    public function datatable(){

        $this->setActiveYears();
        $startDate = Carbon::parse("01.01.{$this->activeYear}")->format('Y-m-d');
        $endDate = Carbon::parse("31.12.{$this->activeYear}")->format('Y-m-d');
    
        $query = UserCredit::with('user', 'user.account')->select('user_credits.*')
        //::with('shopping_user', )->select('shopping_orders.*')
        //->where('paid', '=', 1)
        ->whereBetween('date', [$startDate, $endDate]);
        //->orderBy('created_at', 'DESC');

        return \DataTables::eloquent($query)
       
           
            ->addColumn('total', function (UserCredit $UserCredit) {
                return $UserCredit->getFormattedTotal()." €";
            })
            ->addColumn('user_margins', function (UserCredit $UserCredit) {
                $ret = "";
                if($UserCredit->user_margins){
                    foreach($UserCredit->user_margins as $user_margin){
                        $ret .= $user_margin->firstname."/".$user_margin->lastname."/".$user_margin->reference."/".$user_margin->created_at."<br>"; 
                    }
                }
                if($UserCredit->user_credits){
                    foreach($UserCredit->user_credits as $user_credit){
                        $ret .= nl2br($user_credit->message)." / ".$user_credit->created_at."<br>"; 

                    }
                }
                return $ret;
            })
          /*  ->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
                return Payment::getShoppingOrderBadge($ShoppingOrder);
            })*/
            ->addColumn('credit', function (UserCredit $UserCredit) {
                $ret = "";
                if(Credit::isCredit($UserCredit)){
                    $ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit', 'download']).'" class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a> ';
                    $ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit', 'stream']).'" target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a>';
                }else{
                    $ret = "-";
                }
                return $ret;
            })

            ->addColumn('status', function (UserCredit $UserCredit) {
                return '<a href="#" data-toggle="modal" data-target="#modals-load-content" data-modal="modal-lg"
                 data-id="'.$UserCredit->id.'" data-route="'.route('modal_load').'" data-action="user-credit-status" data-view="">
                 <span class="badge  badge-pill badge-'.$UserCredit->getStatusColor().'">'.$UserCredit->getStatusType().' <span class="ion ion-md-cash"></span></span>
                     </a>';
            })

           
            ->orderColumn('id', 'id $1')
            ->orderColumn('status', 'status $1')
            ->orderColumn('total', 'total $1')
            ->rawColumns(['shipping_order', 'total', 'credit', 'status', 'user_margins'])
            ->make(true);
    }
}