<?php

namespace Romanah\Gokbakja\Components;

use Cms\Classes\ComponentBase;
use Romanah\Gokbakja\Models\ProductionMachine as ProductionMachineModel;
use Romanah\Gokbakja\Models\Order as OrderModel;
use Romanah\Gokbakja\Models\OrderItem as OrderItemModel;
use Romanah\Gokbakja\Models\SewerProduction as SewerModel;
use Redirect;
use Carbon\Carbon;
use Flash;
use DB;
use October\Rain\Support\Facades\Flash as FacadesFlash;
use Romanah\Gokbakja\Models\LoadTransport as ModelsLoadTransport;
use Romanah\Gokbakja\Models\BagAction;
use Romanah\Gokbakja\Models\RulonAction;
use Romanah\Gokbakja\Models\Stock;

class OrderItem extends ComponentBase
{


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


    public function onRender()
    {
        $user = \Auth::user();
        $crudOrderq = $this->page["crudOrders"];

        $orderId = $this->param("orderId");
        $html_data = '';

        $orderItems = OrderItemModel::where("order_id", $orderId)->orderBy("id", "DESC")->with(["type", "size", "color"])->get();

        //dd($orderItems);
        for ($x = 0; $x < count($orderItems); $x++) {
            $calcAmount = ($orderItems[$x]->amount * $orderItems[$x]->price);

            $stockCalc = 0;
            $notCompleteCalc = 0;

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

                $bag_type = $orderItems[$x]->type_id;
                $bag_size = $orderItems[$x]->width;
                $bag_gram = $orderItems[$x]->rulon_gram;
                $rulon_layer = $orderItems[$x]->rulon_layer;
                $color = $orderItems[$x]->color_id;
                $amountCalc = $orderItems[$x]->amount;

                $rulonCalc = RulonAction::with('product')
                ->whereHas('product', function($q)use($bag_type, $bag_size, $color, $bag_gram, $rulon_layer){
                    $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');


                $stockCalc = $rulonCalc;
                $calc = (float)($stockCalc - $amountCalc);
                //dd($stockCalc);
                if($calc > 0){

                    $notCompleteCalc = '<font style="color: darkgreen;"> +'.number_format($calc, 2).' artyk</font>';
                }elseif($calc < 0){
                    $notCompleteCalc = '<font style="color: darkred;">'.number_format($calc, 2).' ýetenok</font>';
                }elseif($calc == 0){
                    $notCompleteCalc = '<font style="color: darkgreen;"> Ýetmezçilik ýok</font>';
                }

            }else{

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

                $bag_type = $orderItems[$x]->type_id;
                $bag_width = $orderItems[$x]->bag_width;
                $bag_height = $orderItems[$x]->bag_height;
                $color = $orderItems[$x]->color_id;
                $bag_gram = $orderItems[$x]->bag_gram;
                $amountCalc = $orderItems[$x]->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');


                $stockCalc = (float)$bagCalc;
                $calc = (float)($stockCalc - $amountCalc);
                //dd($stockCalc);
                if($calc > 0){

                    $notCompleteCalc = '<font style="color: darkgreen;"> +'.number_format($calc, 2).' artyk</font>';
                }elseif($calc < 0){
                    $notCompleteCalc = '<font style="color: darkred;">'.number_format($calc, 2).' ýetenok</font>';
                }elseif($calc == 0){
                    $notCompleteCalc = '<font style="color: darkgreen;"> Ýetmezçilik ýok</font>';
                }


            }

            $editBtnPrice = '';
            $editAmount = '';
            $editDelete = '';
            $status = '';

            $loadedAmount = ModelsLoadTransport::where('order_item_id', $orderItems[$x]->id)->sum('loaded_amount');

            if($loadedAmount > $orderItems[$x]->amount){
                $diffLoaded = number_format(($loadedAmount - $orderItems[$x]->amount), 2);
                $status = '<font style="color: darkgreen;">Tamamlandy (+'.$diffLoaded.')</font';
            }else if($loadedAmount < $orderItems[$x]->amount){
                $diffLoaded = number_format(($orderItems[$x]->amount - $loadedAmount), 2);
                $status = '<font style="color: darkred;">Ýetmezçilik (-'.$diffLoaded.')</font';
            }else if($loadedAmount == $orderItems[$x]->amount){
                $status = '<font style="color: darkgreen;">Tamalandy</font';
            }


            if($orderItems[$x]->user_id != $user->id){
                $editBtnPrice = '<a href="#"
                class="badge badge-soft-success"
                style="font-size: 14px;">'.number_format($orderItems[$x]->price, 4).' $</a>';

                $editAmount = '<a href="#" >';

                $editDelete = '<a href="#" style="color: darkred;font-weight: bold;">Size degişli däl</a>';
            }else{
                $editBtnPrice = $crudOrderq ? '<a href="#" data-request="onModalSet"
                data-request-data="orderItemId: '.$orderItems[$x]->id.'"
                data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1"
                class="badge badge-soft-success"
                style="font-size: 14px;">'.number_format($orderItems[$x]->price, 4).' $</a>'
                :

                '<a href="#" class="badge badge-soft-success"
                style="font-size: 14px;">'.number_format($orderItems[$x]->price, 4).' $</a>';

                $editAmount = $crudOrderq ? '<a href="#" data-request="onModalSetAmount"
                data-request-data="orderItemId: '.$orderItems[$x]->id.'"
                data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1">'
                :
                '<a href="#">';

                $editDelete = $crudOrderq ? '<a href="#" data-request="onDeleteOrder" data-request-confirm="Sargyt Haryt #' . $orderItems[$x]->id . ' pozmak isleýäňizmi?" data-request-data="orderItemId: ' . $orderItems[$x]->id . '" style="color: darkred;font-weight: bold;">POZ</a>' : '';
            }

            $html_data .= '<tr>
                <td style="font-weight: bold;">'.($x+1).', #'.$orderItems[$x]->id.'</td>
                <td><a href="#" style="font-weight: bold;">';

                    if ($orderItems[$x]->order_item_type == 'rulon'){
                        $html_data .= 'Rulon, '.($orderItems[$x]->type->name ?? "") .','. ($orderItems[$x]->color->name ?? "");
                    }else{
                        $html_data .= 'Halta, '. ($orderItems[$x]->color->name ?? "") .', '. (number_format($orderItems[$x]->bag_gram ?? 0, 2)) .' gr';
                    }

                $html_data .='</a></td>
                <td>';
                    if ($orderItems[$x]->order_item_type == 'rulon'){
                        $html_data .= 'Ölçegi: '.($orderItems[$x]->width ?? "").', '.$orderItems[$x]->rulon_gram.' gram m2 , rulon gaty: '.$orderItems[$x]->rulon_layer;
                    }else{
                        $html_data .= 'Ini: '.$orderItems[$x]->bag_width.' Boýy: '.$orderItems[$x]->bag_height;
                    }
                $html_data .='</td>
                <td>
                    '.$editBtnPrice.'
                </td>

                <td>'.$editAmount.' '.$orderItems[$x]->amount;

                    if ($orderItems[$x]->order_item_type == 'rulon'){
                        $html_data .=' kg';
                    }else{
                        $html_data .=' sany';
                    }

                    $html_data .= '</a></td>
                <td>
                    '.number_format($calcAmount, 2).' $
                </td>
                <td>
                    '.number_format($stockCalc, 2);

                if ($orderItems[$x]->order_item_type == 'rulon'){
                    $html_data .=' kg';
                }else{
                    $html_data .=' sany';
                }

                $html_data .= '</td>
                <td>'.$notCompleteCalc.'</td>
                <td>'.$loadedAmount.'</td>
                <td>'.$status.'</td>
                <td>'.$orderItems[$x]->note.'</td>
                <td>'.$editDelete.'</td>
            </tr>';
        }


        return  $html_data;
    }

    public function onModalSet()
    {

        $data = post();

        $orderItem = OrderItemModel::where("id", $data["orderItemId"])->first();

        $html_data = '<div class="modal-header">
                            <h5 class="modal-title" id="mySmallModalLabel">Sargyt Haryt Bahasy</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form data-request="onUpdateOrderItemPrice" method="POST" data-request-flash>
                                <input type="number" step="0.0001" pattern="/^-?\d+\.?\d*$/"
                                    onKeyPress="if(this.value.length==7) return false;"
                                    name="price" class="form-control"
                                    placeholder="%"
                                    value="' . $orderItem->price . '">
                                <input type="hidden" name="id" value="' . $data["orderItemId"] . '">
                                <button type="submit"
                                    class="btn btn-primary waves-effect waves-light"
                                    data-bs-dismiss="modal"
                                    style="margin-top: 15px;width: 100%;">Üýtget</button>
                            </form>
                        </div>';

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

    public function onModalSetAmount()
    {

        $data = post();

        $orderItem = OrderItemModel::where("id", $data["orderItemId"])->first();

        $html_data = '<div class="modal-header">
                            <h5 class="modal-title" id="mySmallModalLabel">Sargyt Mukdary</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form data-request="onUpdateOrderItemAmount" method="POST" data-request-flash>
                                <input type="number" step="0.01" pattern="/^-?\d+\.?\d*$/"
                                    onKeyPress="if(this.value.length==4) return false;"
                                    name="amount" class="form-control"
                                    placeholder=""
                                    value="' . $orderItem->amount . '">
                                <input type="hidden" name="id" value="' . $data["orderItemId"] . '">
                                <button type="submit"
                                    class="btn btn-primary waves-effect waves-light"
                                    data-bs-dismiss="modal"
                                    style="margin-top: 15px;width: 100%;">Üýtget</button>
                            </form>
                        </div>';

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

    public function onUpdateOrderItemAmount()
    {
        // $this["currentMonth"] = $currentDate->format('m');
        $data = post();

        $orderItem = OrderItemModel::where("id", $data["id"])->first();

        $orderItem->amount = (float) $data["amount"];
        $orderItem->save();

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

    }

    public function onUpdateOrderItemPrice()
    {
        // $this["currentMonth"] = $currentDate->format('m');
        $data = post();

        $orderItem = OrderItemModel::where("id", $data["id"])->first();

        $orderItem->price = (float) $data["price"];
        $orderItem->save();



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

    public function onCreateOrderItem()
    {
        $user = \Auth::user();
        $data = post();
        $orderId = $this->param("orderId");


        $createOrderItem = new OrderItemModel();
        $createOrderItem->amount = $data["amount"];
        $createOrderItem->order_item_type = $data["order_item_type"];
        $createOrderItem->order_id = $orderId;
        $createOrderItem->type_id = $data["type_id"];
        $createOrderItem->width = $data["width"];
        $createOrderItem->rulon_layer = $data["rulon_layer"];
        $createOrderItem->rulon_gram = $data["rulon_gram"];
        $createOrderItem->color_id = $data["color_id"];
        $createOrderItem->bag_gram = $data["bag_gram"];
        $createOrderItem->bag_width = $data["bag_width"];
        $createOrderItem->bag_height = $data["bag_height"];
        $createOrderItem->price = $data["price"];
        $createOrderItem->note = $data["note"];
        $createOrderItem->user_id = $user->id;
        $createOrderItem->save();

        if ($createOrderItem) {
            Flash::success("Sargyt Harydy Ustunlikli Goşuldy");
            return Redirect::refresh();
        }
    }


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

        $orderItem = OrderItemModel::where("id", $data["orderItemId"])->delete();


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

}
