<?php

namespace Romanah\Gokbakja\Components;

use Cms\Classes\ComponentBase;
use Redirect;
use Carbon\Carbon;
use Flash;
use DB;
use Romanah\Gokbakja\Models\BagAction;
use Romanah\Gokbakja\Models\LoadTransport as ModelsLoadTransport;
use Romanah\Gokbakja\Models\OrderItem;
use Romanah\Gokbakja\Models\RulonAction;
use Romanah\Gokbakja\Models\Stock;

class LoadTransport extends ComponentBase
{


    public function componentDetails()
    {
        return [
            'name'        => 'LoadTransport',
            'description' => 'LoadTransport settings'
        ];
    }

    public function onDeleteItem(){
        $user = \Auth::user();

        $data = post();
        $loadedItem = ModelsLoadTransport::where("id", $data["itemId"])->with('order_item')->with('product')->first();

        if($loadedItem->order_item->order_item_type == 'rulon'){
            $stock = Stock::where("type", 'rulon')->first();

            $createResult = new RulonAction();
            $createResult->product_id = $loadedItem->product_id;
            $createResult->type = 'inbox';
            $createResult->amount = $loadedItem->loaded_amount;
            $createResult->stock_id = $stock->id;
            $createResult->user_id = $user->id;
            $createResult->note = "#Sargyt".$loadedItem->order_id.". #Transport".$loadedItem->transport_id." - ýüklenden soň aýyryldy.";
            $createResult->save();
        }else{
            $stock = Stock::where("type", 'bag')->first();

            $createResult = new BagAction();
            $createResult->product_id = $loadedItem->product_id;
            $createResult->type = 'inbox';
            $createResult->amount = $loadedItem->loaded_amount;
            $createResult->stock_id = $stock->id;
            $createResult->user_id = $user->id;
            $createResult->note = "#Sargyt".$loadedItem->order_id.". #Transport".$loadedItem->transport_id." - ýüklenden soň aýyryldy.";
            $createResult->save();
        }

        $loadedItem->delete();

        if ($loadedItem && $createResult) {
            Flash::success("Ustunlikli Pozuldy");
            return Redirect::refresh();
        } else {
            Flash::error("Yalnyshlyk bar!!");
            return Redirect::refresh();
        }
    }

    public function onSetUpdateForm(){
        $data = post();
        $loadedItem = ModelsLoadTransport::where("id", $data["itemId"])->first();

        $html_data = '<div class="modal-header">
                        <h5 class="modal-title" id="mySmallModalLabel">Yüklenen Tapgyr kody #'.$loadedItem->id.'</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"
                            aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form data-request="onUpdateLoadItem" data-request-flash data-request-validate>

                            <div class="row">

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Ýüklenmeli Mukdar</label>
                                        <input type="number" step="0.01" name="loaded_amount" class="form-control"
                                            placeholder="Ýüklenmeli Mukdar" value="'.$loadedItem->loaded_amount.'">
                                    </div>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Bellik</label>
                                        <input type="text" name="note" class="form-control"
                                            placeholder="Bellik" value="'.$loadedItem->note.'">
                                    </div>
                                </div>

                                <input type="hidden" name="loadId" value="'.$loadedItem->id.'">
                                <div class="col-md-12 mt-3">
                                    <button type="submit" class="btn btn-primary waves-effect waves-light"
                                        style="margin-top: 30px;width: 100%;">Üýtget</button>
                                </div>

                            </div>

                        </form>
                    </div>';

        return [
            '#modal-form' => $html_data,
        ];
    }

    public function onUpdateLoadItem(){
        $data = post();

        $loadedItem = ModelsLoadTransport::where("id", $data["loadId"])->first();
        $loadedItem->loaded_amount = $data["loaded_amount"];
        $loadedItem->note = $data["note"];
        $loadedItem->save();

        if ($loadedItem) {
            Flash::success("Ustunlikli Uytgedildi");
            return Redirect::refresh();
        } else {
            Flash::error("Yalnyshlyk bar!!");
            return Redirect::refresh();
        }
    }


    public function onCreateLoadItem(){
        $user = \Auth::user();

        $data = post();
        $orderId = $this->param("orderId");
        $transportId = $this->param("transportId");

        if($data["product_id"]){

            $loadedItem = new ModelsLoadTransport();
            $loadedItem->order_id = $orderId;
            $loadedItem->order_item_id = $data["order_item_id"];
            $loadedItem->loaded_amount = $data["loaded_amount"];
            $loadedItem->note = $data["note"];
            $loadedItem->transport_id = $transportId;
            $loadedItem->product_id = $data["product_id"];
            $loadedItem->save();

            if($data["product_type"] == "rulon"){
                $stock = Stock::where("type", 'rulon')->first();

                $createResult = new RulonAction();
                $createResult->product_id = $data["product_id"];
                $createResult->type = 'outbox';
                $createResult->amount = -$data["loaded_amount"];
                $createResult->stock_id = $stock->id;
                $createResult->user_id = $user->id;
                $createResult->note = "#Sargyt".$orderId." üçin. #Transport".$transportId." - ýüklendi";
                $createResult->save();

            }else{
                $stock = Stock::where("type", 'bag')->first();

                $createResult = new BagAction();
                $createResult->product_id = $data["product_id"];
                $createResult->type = 'outbox';
                $createResult->amount = -$data["loaded_amount"];
                $createResult->stock_id = $stock->id;
                $createResult->user_id = $user->id;
                $createResult->note = "#Sargyt".$orderId." üçin. #Transport".$transportId." - ýüklendi";
                $createResult->save();
            }

            if ($loadedItem && $createResult) {
                Flash::success("Haryt Transporta Ustunlikli Yuklendi");
                return Redirect::refresh();
            } else {
                Flash::error("Yalnyshlyk bar!!");
                return Redirect::refresh();
            }
        }else{
            Flash::error("Sklatdan haryt saylan!");
            return Redirect::refresh();
        }


    }

    public function onCalculateLoaded(){
        $data = post();
        $orderId = $this->param("orderId");

        $loadedItemSum = ModelsLoadTransport::where("order_item_id", $data["item_id"])->where("order_id", $orderId)->sum("loaded_amount");
        // dd($loadedItemSum);
        $productFromStock = $this->getProductFromStock($data["item_id"]);

        $dataResult = array(
            "loadedSum"=>$loadedItemSum,
            "productFromStock"=>$productFromStock
        );
        return $dataResult;
    }

    public function getProductFromStock($order_item_id){

        $currentOrderItem = OrderItem::where("id", $order_item_id)->first();

        if ($currentOrderItem->order_item_type == 'rulon'){
            $stock = Stock::where("type", 'rulon')->first();

            $bag_type = $currentOrderItem->type_id;
            $bag_size = $currentOrderItem->width;
            $bag_gram = $currentOrderItem->rulon_gram;
            $rulon_layer = $currentOrderItem->rulon_layer;
            $color = $currentOrderItem->color_id;
            $amountCalc = $currentOrderItem->amount;

            $rulonCalc = RulonAction::with('product')
            ->whereHas('product', function($q)use($bag_type, $bag_size, $color,  $rulon_layer, $bag_gram){
                $q->where('type_id', $bag_type)
                ->where('width', $bag_size)
                ->where('gram', $bag_gram)
                ->where('layer', $rulon_layer)
                ->where('color_id', $color);
            })
            ->where("stock_id", $stock->id)
            //->where("status_accountant", "accept")
            //->where("status_director", "accept")
            ->sum('amount');

            $products = '';
            $orderItemType = '';

            if($rulonCalc > 0){
                $rulonProducts = RulonAction::select('romanah_gokbakja_rulon_action.*')
                            ->with('product')
                            ->whereHas('product', function($q)use($bag_type, $bag_size, $color,  $rulon_layer, $bag_gram){
                                $q->where('type_id', $bag_type)
                                ->where('width', $bag_size)
                                ->where('gram', $bag_gram)
                                ->where('layer', $rulon_layer)
                                ->where('color_id', $color);
                            })
                            ->with(['product' => function($q){
                                $q->with(['bag_type', 'bag_size', 'color', 'machine']);
                            }])
                            ->where("stock_id", $stock->id)
                            //->where("status_accountant", "accept")
                            //->where("status_director", "accept")
                            ->addSelect(DB::raw("SUM(amount) as quantity"))
                            ->having('quantity', '>', 0)
                            ->groupBy('romanah_gokbakja_rulon_action.product_id')
                            ->orderBy('id', 'DESC')
                            ->get();

                $products = $rulonProducts;
                $orderItemType = 'rulon';
            }

            return array(
                "inStockAmount" => $rulonCalc,
                "orderItemType" => $orderItemType,
                "products" => $products
            );

        }else{

            $stock = Stock::where("type", 'bag')->first();

            $bag_type = $currentOrderItem->type_id;
            $bag_width = $currentOrderItem->bag_width;
            $bag_height = $currentOrderItem->bag_height;
            $color = $currentOrderItem->color_id;
            $bag_gram = $currentOrderItem->bag_gram;
            $amountCalc = $currentOrderItem->amount;

            $bagCalc = BagAction::with('product.rulon_action.product')
            ->whereHas('product.rulon_action.product', function($q)use($bag_type, $color){
                $q->where('type_id', $bag_type)
                ->where('color_id', $color);
            })
            ->with('product.pivot_sewer')
            ->whereHas('product.pivot_sewer', function($qq)use($bag_gram){
                $qq->where('bag_gram', $bag_gram);
            })
            ->with('product')
            ->whereHas('product', function($qqq)use($bag_width, $bag_height){
                $qqq->where('width', $bag_width)->where('height', $bag_height);
            })
            ->where("stock_id", $stock->id)
            //->where("status_accountant", "accept")
            //->where("status_director", "accept")
            ->sum('amount');


            $products = '';
            $orderItemType = '';

            if($bagCalc > 0){
                $bagProducts = BagAction::select('romanah_gokbakja_bag_actions.*')
                            ->with('product.rulon_action.product')
                            ->whereHas('product.rulon_action.product', function($q)use($bag_type, $color){
                                $q->where('type_id', $bag_type)
                                ->where('color_id', $color);
                            })
                            ->with('product.pivot_sewer')
                            ->whereHas('product.pivot_sewer', function($qq)use($bag_gram){
                                $qq->where('bag_gram', $bag_gram);
                            })
                            ->with(['product.rulon_action.product.bag_type', 'product.rulon_action.product.color', 'product.pivot_sewer'])
                            ->whereHas('product', function($qqq)use($bag_width, $bag_height){
                                $qqq->where('width', $bag_width)->where('height', $bag_height);
                            })
                            ->where("stock_id", $stock->id)
                            //->where("status_accountant", "accept")
                            //->where("status_director", "accept")
                            ->addSelect(DB::raw("SUM(amount) as quantity"))
                            ->having('quantity', '>', 0)
                            ->groupBy('romanah_gokbakja_bag_actions.product_id')
                            ->orderBy('id', 'DESC')
                            ->get();

                $products = $bagProducts;
                $orderItemType = 'bag';
            }

            return array(
                "inStockAmount" => $bagCalc,
                "orderItemType" => $orderItemType,
                "products" => $products
            );

        }
    }

}
