<?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;

class OrderItem extends ComponentBase
{


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


    public function onRender()
    {
        $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'){

                $machineProductionsFiltered = ProductionMachineModel::where("type_id", $orderItems[$x]->type_id)
                                                        ->where("size_id", $orderItems[$x]->size_id)
                                                        ->where("color_id", $orderItems[$x]->color_id)
                                                        ->withCount([
                                                            'pivot_sewer AS leftSum' => function ($query) {
                                                                $query->select(DB::raw("(amount - SUM(spent_amount)) as leftSum"))->where('status', 'complated');
                                                            }
                                                        ])
                                                        ->withCount([
                                                            'pivot_sewer AS spentSum' => function ($query) {
                                                                $query->select(DB::raw("(SUM(spent_amount)) as spentSum"))->where('status', 'complated');
                                                            }
                                                        ])
                                                        ->get();

                if($machineProductionsFiltered != null){
                    for ($i = 0; $i < count($machineProductionsFiltered); $i++) {

                        $left = ($machineProductionsFiltered[$i]->produced_weight - $machineProductionsFiltered[$i]->spentSum);

                        $stockCalc += $left;
                    }

                    if($stockCalc > $orderItems[$x]->amount){
                        $notCompleteCalc = 'artykmaç';
                    }else{
                        $notCompleteCalc = number_format(($orderItems[$x]->amount - $stockCalc),2).' kg';
                    }
                }else{
                    $stockCalc = 0;
                }
                // $stockCalc = number_format(($sumOfProduced - $prodMachine[0]->spentSum),2);

            }else{
                $colorId = $orderItems[$x]->color_id;
                $bag_gram = $orderItems[$x]->bag_gram;

                $sewerProductions = SewerModel::where("width", $orderItems[$x]->bag_width)
                                                ->where("height", $orderItems[$x]->bag_height)
                                                ->with("machin_production")
                                                ->whereHas('machin_production', function ($query) use($colorId) {
                                                    $query->where('color_id', $colorId);
                                                })
                                                ->whereHas('pivot_sewer', function ($query) use($bag_gram) {
                                                    $query->where('bag_gram', $bag_gram);
                                                })
                                                ->sum("produced_bag_qty");
                $stockCalc= $sewerProductions;

                if($stockCalc > $orderItems[$x]->amount){
                    $notCompleteCalc = 'artykmaç';
                }else{
                    $notCompleteCalc = number_format(($orderItems[$x]->amount - $stockCalc),2).' sany';
                }
            }



            $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 .= $orderItems[$x]->size->name ?? "";
                    }else{
                        $html_data .= 'Ini: '.$orderItems[$x]->bag_width.' Boýy: '.$orderItems[$x]->bag_height;
                    }
                $html_data .='</td>
                <td><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).' $</a>
                </td>

                <td><a href="#" data-request="onModalSetAmount"
                    data-request-data="orderItemId: '.$orderItems[$x]->id.'"
                    data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1">'.$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>'.$orderItems[$x]->note.'</td>
                <td><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></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.01" pattern="/^-?\d+\.?\d*$/"
                                    onKeyPress="if(this.value.length==4) 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 {
            return Flash::error("Yalnyshlyk bar!!");
        }

    }

    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 {
            return Flash::error("Yalnyshlyk bar!!");
        }
    }

    public function onCreateOrderItem()
    {
        $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->size_id = $data["size_id"];
        $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->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 {
            return Flash::error("Yalnyshlyk bar!!");
        }
    }

}
