<?php


namespace App\Http\Controllers\Stats;

use Auth;
use Request;
use App\User;
use Carbon\Carbon;
use Faker\Core\Number;
use App\Exports\ExcelExport;
use App\Services\HTMLHelper;
use App\Models\ShoppingOrder;
use App\Services\Stats\Sales;
use App\Models\ShoppingOrderItem;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use App\Services\BusinessPlan\ExportBot;
use Illuminate\Database\Eloquent\Collection;

class SalesController extends Controller
{

    private $serviceSales;

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

    public function index()
    {
        $this->setFilterVars();
        $data = [
            'filter_months' => HTMLHelper::getTransMonths(true),
            'filter_years' => HTMLHelper::getYearRange(2020),
            'filter_products' => $this->serviceSales->setFilterProducts(),
        ];
        return view('admin.stats.salesvolume', $data);
    }


    public function download()
    {
        $this->setFilterVars();

        if (Request::get('action') === "filter") {
            // $data = Request::all();
            return back();
        }

        if (Request::get('action') === "export") {
            $objects = $this->serviceSales->getObjects();
            $columns = [];
            $filename = "gs-absatzmengen-" . session('product_sales_vol_filter_month') . '_' . session('product_sales_vol_filter_year') . "-export";
            $headers = array(
                '#',
                'Produkt',
                'Artikelnummer',
                'Menge',
                'Gesamt Netto in EURO',
                'Vorjahr Menge',
                'Vorjahr Gesamt Netto in EURO',
                'Einzelrabatt',
                'Einzelrabatt %',
                'VP Einzelrabatt %',


            );
            if ($objects) {
                foreach ($objects as $key => $obj) {
                    $columns[] = array(
                        'id'                => $key,
                        'name'              => $obj['name'],
                        'number'            => $obj['number'],
                        'qty'               => $obj['qty'],
                        'total'             => $obj['total'],
                        'pre_qty'           =>  $obj['pre_qty'],
                        'pre_total'         =>  $obj['pre_total'],
                        'single_commission' => $obj['single_commission'],
                        'value_commission'  => $obj['value_commission'],
                        'partner_commission' => $obj['partner_commission'],

                    );
                }
            }
            return Excel::download(new ExcelExport($columns, $headers), $filename . '.xls');
        }
    }

    private function setFilterVars()
    {

        if (!session('product_sales_vol_filter_month')) {
            session(['product_sales_vol_filter_month' => intval(date('m'))]);
        }
        if (!session('product_sales_vol_filter_year')) {
            session(['product_sales_vol_filter_year' => intval(date('Y'))]);
        }
        if (!session('product_sales_vol_filter_products')) {
            session(['product_sales_vol_filter_products' => []]);
        }
        if (Request::get('product_sales_vol_filter_month')) {
            session(['product_sales_vol_filter_month' => Request::get('product_sales_vol_filter_month')]);
        }
        if (Request::get('product_sales_vol_filter_year')) {
            session(['product_sales_vol_filter_year' => Request::get('product_sales_vol_filter_year')]);
        }
        if (Request::get('product_sales_vol_filter_products')) {
            session(['product_sales_vol_filter_products' => Request::get('product_sales_vol_filter_products')]);
        }

        $this->serviceSales->setFilterVars(
            session('product_sales_vol_filter_month'),
            session('product_sales_vol_filter_year'),
            session('product_sales_vol_filter_products')
        );
    }









    public function datatable()
    {

        $this->setFilterVars();
        $collection = $this->serviceSales->getCollection();

        /* $collect = collect([
            ['id' => 1, 'name' => 'John', 'number'=>92012, 'value'=>123],
            ['id' => 2, 'name' => 'Jane', 'number'=>92012, 'value'=>123],
            ['id' => 3, 'name' => 'James', 'number'=>92012, 'value'=>123],
        ]);
        */

        return \DataTables::of($collection)->toJson();
    }

    /*private function testCheckFunction(){

        //$date_start = Carbon::parse('01.'.session('product_sales_vol_filter_month').'.'.session('product_sales_vol_filter_year'))->format('Y-m-d');
        //$date_end = Carbon::parse('01.'.session('product_sales_vol_filter_month').'.'.session('product_sales_vol_filter_year'))->endOfMonth()->format('Y-m-d');

         $date_start = Carbon::parse('01.01.2024')->format('Y-m-d H:i:s');
        $date_end = Carbon::parse('01.01.2024')->endOfMonth()->format('Y-m-d H:i:s');
        dump($date_start);
        dump($date_end);

        $ShoppingOrders = ShoppingOrder::where('mode', 'live')->whereBetween('created_at', [$date_start, $date_end])->get();

        $objects = [];
        $counter = 0;
        foreach($ShoppingOrders as $ShoppingOrder){
            foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
                
                if($shopping_order_item->product){
                    if($shopping_order_item->product->id === 122){
                        //dump($shopping_order_item->qty);
                        //$counter += $shopping_order_item->qty;
                        if(isset($objects[$shopping_order_item->product->id])){
                            $value = intval($objects[$shopping_order_item->product->id]['value'] + $shopping_order_item->qty);
                            $objects[$shopping_order_item->product->id]['value'] = $value;
                        }else{
                            $objects[$shopping_order_item->product->id] = [
                                'name' => $shopping_order_item->product->name, 
                                'number' => $shopping_order_item->product->number, 
                                'value' => $shopping_order_item->qty
                            ];
                        }
                    }
                }

            }
        }

        $ShoppingOrderItems = ShoppingOrderItem::whereProductId(122)->whereBetween('created_at', [$date_start, $date_end])->get();
        $counter = 0;
        foreach($ShoppingOrderItems as $ShoppingOrderItem){
            $counter += $ShoppingOrderItem->qty;
            dump($ShoppingOrderItem->id);
        }
       // dump($objects);
        dump($counter);
        dd("OKAY");
    }*/
}
