<?php

namespace Modules\StockIssues\Console;

use App\Product;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Modules\StockIssues\Exports\TestExport;
use Modules\StockIssues\Models\BusinessLocation;
use Modules\StockIssues\Models\StockReport;

class StockReportGenerate extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'stock:report';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'generate stock report';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     * @throws Exception
     */
    public function handle()
    {
        BusinessLocation::query()->with('business')->get()->each(function (BusinessLocation $businessLocation) {
            if ($businessLocation->business->time_zone) {
                config(['app.timezone' => $businessLocation->business->time_zone]);
                date_default_timezone_set($businessLocation->business->time_zone);
            }
            $now = now();
            $date = $now->toDateString();
            $time = $now->format('Hi');

            $query = Product::query()
                ->join('units', 'products.unit_id', '=', 'units.id')
                ->join('variations as v', 'v.product_id', '=', 'products.id')
                ->leftJoin('variation_location_details as vld', function ($query) use ($businessLocation) {
                    $query->whereColumn('vld.variation_id', 'v.id')
                        ->where('vld.location_id', $businessLocation->id);
                })
                ->with([
                    'purchase_lines' => function ($query) use ($businessLocation) {
                        $query
                            ->select([
                                'purchase_lines.*',
                                DB::raw('(purchase_lines.quantity - (purchase_lines.quantity_sold + purchase_lines.quantity_adjusted + purchase_lines.quantity_returned + purchase_lines.po_quantity_purchased + purchase_lines.mfg_quantity_used)) as avl_qty'),
                                DB::raw('((purchase_lines.quantity - (purchase_lines.quantity_sold + purchase_lines.quantity_adjusted + purchase_lines.quantity_returned + purchase_lines.po_quantity_purchased + purchase_lines.mfg_quantity_used)) * purchase_price) as total_purchase_price')
                            ])
                            ->join('transactions', 'purchase_lines.transaction_id', '=', 'transactions.id')
                            ->where('transactions.location_id', $businessLocation->id);
                    }
                ])
                ->where('products.business_id', $businessLocation->business_id)
                ->where('products.is_inactive', false)
                ->where('products.enable_stock', true)
                ->where('products.type', '!=', 'modifier')
                ->whereHas('product_locations', function ($query) use ($businessLocation) {
                    $query->where('product_locations.location_id', $businessLocation->id);
                })
                ->groupBy(['products.id']);

            $products = $query->select(
                'products.id',
                'products.name',
                'products.sku',
                'products.type',
                DB::raw('SUM(vld.qty_available) as current_stock'),
                //'products.not_for_selling',
                'units.actual_name as unit'
            );
            $products = $products->get()->reject(function ($product) {
                return $product->current_stock === null;
            });
            if ($products->count() > 0) {
                /*if ($products->first()->purchase_lines->count() > 0)
                    dd(
                        $products->first()->purchase_lines//->toArray()
                    );*/
                $export = new TestExport($products->map(function ($product) {
                    return array_merge(Arr::only($product->toArray(), [
                        'id', 'name', 'sku', 'type', 'current_stock', 'unit',
                    ]), [
                        //'avl_qty' => (string)$product->purchase_lines->sum('avl_qty'),
                        'total_purchase_price' => $product->current_stock > 0 ?
                            (string)$product->purchase_lines->sum('total_purchase_price') : '-'
                    ]);
                }));
                $path = "{$date}/{$date} {$time} location-{$businessLocation->id}.xlsx";
                Excel::store($export, $path, 'dropbox');//dropbox
                StockReport::query()->create([
                    'business_location_id' => $businessLocation->id,
                    'path' => $path,
                    'products_count' => $products->count(),
                ]);
            }
        });
        /*$disk = Storage::disk(config('backup.backup.destination.disks')[0]);
        //$client = new DropboxClient(env('DROPBOX_ACCESS_TOKEN'));
        //
        //$export->setYear(2019);


        dd([
            $disk->allFiles(),
            //$client->getTemporaryLink('1200x630wa.png')
        ]);*/
    }
}
