<?php

namespace App\Http\Controllers\SyS;


use Auth;
use Request;
use App\User;
use App\Mail\MailInfo;
use App\Services\Shop;
use App\Models\UserShop;
use App\Services\Payment;
use App\Models\ShoppingUser;
use App\Models\PaymentMethod;
use App\Models\ShoppingOrder;
use App\Models\UserPayCredit;
use App\Services\CustomerPriority;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Api\KasController;
use App\Repositories\ContractPDFRepository;
use App\Http\Controllers\Api\KasSLLController;


class AdminToolsController extends Controller
{
    protected $userRepo;

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

    }

    public function index($action)
    {
       
        switch ($action) {
            case 'pay_credits':
                dd($action);
                $value = $this->makeUserPayCredits();
                $data = [
                    'values' => $value,
                    'text' => '',
                ];
                return view('sys.admin.index', $data);
                break;
            case 'export_vp':
                $values = User::with('account')->select('users.*')->where('users.deleted_at', '=', null)->where('users.admin', "<", 4)->get();
                $data = [
                    'values' => $values,
                    'text' => '',
                ];
                return view('sys.admin.export_vp', $data);
                break;    

            case 'dbaction':
                $values = [];
                $data = [
                    'values' => $values,
                    //'text' => 'Add payment_for in shopping_order', //_dbOrderPaymentFor
                    //'text' => 'Calculate TAX for shopping_order in tax_split array ',
                    'text' => 'show in AdminToolsController dbaction',


                ];
                return view('sys.admin.index', $data);
                break;    
                
        }


        
    }

    public function store($action)
    {
          
        $data = [];
        switch ($action) {
            case 'pay_credits':
                dd($action);
                return view('sys.admin.index', $data);
                break;
            case 'export_vp':            
                return $this->export_vp();
                break;
            case 'dbaction':            
                //return $this->_dbOrderPaymentFor();
                break;
                
        }
    }

    private function _dbOrderPaymentFor(){
        $c = 0;
        $ShoppingUsers = ShoppingUser::all();
        foreach($ShoppingUsers as $ShoppingUser){
            if($ShoppingUser->shopping_order){
                $ShoppingUser->shopping_order->payment_for = $ShoppingUser->getOrderPaymentFor();
                $ShoppingUser->shopping_order->save();
                $c ++;
            }
        }
        dd($c);
    }
    private function export_vp(){

        $query = User::with('account')->select('users.*')->where('users.deleted_at', '=', null)->where('users.admin', "<", 4)->get();
        $fileName = "GS-VP-export-".date("d-m-Y").".csv";
        $headers = array(
            "Content-type"        => "text/csv",
            "Content-Disposition" => "attachment; filename=$fileName",
            "Pragma"              => "no-cache",
            "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
            "Expires"             => "0"
        );

        $columns = array('ID', 'Email', 'Firma', 'Anrede', 'Vorname', 'Nachname', 'Mitglied', 'Bis');
        $callback = function() use($query, $columns) {

            $file = fopen('php://output', 'w');
            fputcsv($file, $columns);
            $row = [];

            foreach ($query as $val) {
                $row['ID']  = $val->id;
                $row['Email']    = $val->email;
                $row['Firma']    = $val->account->company;
                $row['Anrede']    = $val->account->salutation == 'mr' ? 'Herr' : 'Frau' ;
                $row['Vorname']    = $val->account->first_name;
                $row['Nachname']  = $val->account->last_name;
                $row['Mitglied']  = $val->payment_account ? ($val->isActiveAccount() ? 'JA' : 'Abgelaufen') : "Nein";
                $row['Bis']  = $val->payment_account ? $val->getPaymentAccountDateFormat(false) : "-";
                fputcsv($file, $row);
                
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);

        //dd("ok");

    }

    private function makeUserPayCredits()
    {
       //is the first of
       $shopping_orders = ShoppingOrder::whereHas('shopping_order_items', function($q) {
            $q->where('product_id', 1);
        })->where('paid', 1)->where('total_shipping', '>', 0)->get();

    
        foreach ($shopping_orders as $shopping_order) {
            $payment_credit = $shopping_order->total_shipping;
            $c = UserPayCredit::where('shopping_order_id', $shopping_order->id)->first();
            if(!$c){
                $uP = UserPayCredit::create([
                    'user_id' => $shopping_order->auth_user->id,
                    'credit' => $payment_credit,
                    'old_credit_total' => 0,
                    'new_credit_total' => $payment_credit,
                    'message' => 'payment_for_account',
                    'status' => 1,
                    'shopping_order_id' => $shopping_order->id
                ]);

                $uP->created_at = $shopping_order->created_at;
                $uP->updated_at = $shopping_order->created_at;
                $uP->save();
            }
        }


        $shopping_orders = ShoppingOrder::where('payment_credit', '>', 0)->where('paid', 1)->get();
        foreach ($shopping_orders as $shopping_order) {
            $payment_credit = $shopping_order->payment_credit;
            $c = UserPayCredit::where('shopping_order_id', $shopping_order->id)->first();
            if(!$c){
                //find last 
                $UserPayCredit = UserPayCredit::where('user_id', $shopping_order->auth_user->id)->orderBy('created_at', 'desc')->first();
                $old_credit = 0;
                $credit = $shopping_order->payment_credit*-1;
                if($UserPayCredit){
                    $old_credit = $UserPayCredit->new_credit_total;
                }
                $uP = UserPayCredit::create([
                    'user_id' => $shopping_order->auth_user->id,
                    'credit' => $credit,
                    'old_credit_total' => $old_credit,
                    'new_credit_total' => $old_credit + $credit,
                    'message' => 'user_order_deduction',
                    'status' => 2,
                    'shopping_order_id' => $shopping_order->id
                ]);
                $uP->created_at = $shopping_order->created_at;
                $uP->updated_at = $shopping_order->created_at;
                $uP->save();

            }
        }
        return $shopping_orders;
    }

    /*public function customers()
    {

        $shopping_users = ShoppingUser::where('member_id', '=', NULL)->where('auth_user_id', '=', NULL)->get();
        $data = [
            'values' => $shopping_users,
            'text' => '',
        ];

        return view('sys.admin.customers', $data);
    }


    public function customerStore()
    {
        $data = Request::all();
        $ret = "";
        if($data['action'] === 'makePaymentMethodsDefault'){
            $users = User::where('payment_methods', '=', NULL)->get();
            //$users = User::all();
            foreach ($users as $user){
                $user->payment_methods = PaymentMethod::getDefaultAsArray();
                $user->save();
            }
        }
        if($data['action'] === 'checkForAll'){
            $shopping_users = CustomerPriority::checkForAll();
        }

        if($data['action'] === 'checkContractPDF'){
            //create PDF
            $user = User::findOrFail(80);

            $pdf = new ContractPDFRepository($user);
            $pdf->_set('disk', 'user');
            $pdf->_set('dir', '/'.$user->id.'/documents/');
            $pdf->_set('user_id', $user->id);
            $pdf->_set('identifier', 'contract');
            $pdf->createContractPDF();

        }



        if(strpos($data['action'], 'checkOne_') !== false){
            $id = (int) str_replace('checkOne_', '', $data['action']);
            $shopping_user = ShoppingUser::findOrFail($id);
            $ret = CustomerPriority::checkOne($shopping_user);
        }
        \Session()->flash('alert-success', $ret);
        return back();
    }

    public function cronjobs()
    {
        //$user_shops = UserShop::all();
        $text = "";
        $values = [
            'check_payments_account' => route('cron_jobs_action', ['check_payments_account', 'key'])
        ];
        $data = [
            'values' => $values,
            'text' => $text,
        ];

        return view('sys.admin.cronjobs', $data);
    }
    public function cronjobsStore()
    {
        $data = Request::all();
        \Session()->flash('alert-save', true);
        return back();
    }


    public function domainSSL()
    {
        $user_shops = UserShop::all();
        $text = "";

        $kas = new KasController();
        $domain = 'hier die DOMAIN';

        $ssl = KasSLLController::getApiSSLParameter();

        $subdomains = $kas->action('get_subdomains');
        foreach ($subdomains as $subdomain){
            $text .= $subdomain['subdomain_name']." - ".$subdomain['ssl_certificate_sni']."\n";

            if($subdomain['ssl_certificate_sni'] !== "Y"){
                $pra = array(
                    'hostname' => $subdomain['subdomain_name'],
                );
                $pra = array_merge($pra, $ssl);
                $value = $kas->action('update_ssl', $pra);
                $text .= $value."\n";
            }
        }
        $data = [
            'values' => $user_shops,
            'text' => $text,
        ];

        return view('sys.admin.domain-ssl', $data);



    }
    public function domainSSLStore()
    {
        $data = Request::all();
        \Session()->flash('alert-save', true);
        return back();
    }

    public function shoppingOrders()
    {
        $shopping_users = ShoppingUser::all();
        $data = [
            'values' => $shopping_users,
            'text' => '',
        ];
        return view('sys.admin.shopping-orders', $data);

    }
    public function shoppingOrdersStore()
    {
        //first run
        $data = Request::all();

        if($data['action'] === 'first_run'){
            $shopping_users = ShoppingUser::whereHas('shopping_order', function($q) {
                $q->where('txaction', 'paid')->OrWhere('txaction', 'appointed');
            })->get();

            $order_email = [];
            $order_number = [];

            foreach ($shopping_users as $shopping_user){
                $order_email[$shopping_user->billing_email] = isset($order_email[$shopping_user->billing_email]) ? $order_email[$shopping_user->billing_email] + 1 : 1;
                if($shopping_user->number) {
                    $order_number[$shopping_user->number] = isset($order_number[$shopping_user->number]) ? $order_number[$shopping_user->number] + 1 : 1;
                    $shopping_user->orders = $order_number[$shopping_user->number];
                }else {
                    $shopping_user->orders = $order_email[$shopping_user->billing_email];
                }
                $shopping_user->save();

            }
            \Session()->flash('alert-save', true);
        }

        if($data['action'] === 'next_run'){
           Shop::userOrders();
            \Session()->flash('alert-save', true);
        }
        return back();

    }
    */



}