<?php

namespace Romanah\Gokbakja\Components;

use Cms\Classes\ComponentBase;
use Romanah\Gokbakja\Models\Production as ProductionModel;
use Romanah\Gokbakja\Models\PivotProduction as PivotProductionModel;
use Romanah\Gokbakja\Models\SewerProduction as SewerModel;
use Redirect;
use Carbon\Carbon;
use Flash;
use DB;
use Romanah\Gokbakja\Models\BagAction;
use Romanah\Gokbakja\Models\ProductionMachine;
use Romanah\Gokbakja\Models\PivotSewer;
use Romanah\Gokbakja\Models\RulonAction;
use Romanah\Gokbakja\Models\SewerMachine;
use Romanah\Gokbakja\Models\Shift;
use Romanah\Gokbakja\Models\Stock;

class Sewer extends ComponentBase
{

    public $sewers;

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


    public function onModalSetSewer()
    {

        $data = post();

        $sewerProd = SewerModel::where("id", $data["sewerId"])->with("employee", "pivot_sewer")->first();
        $shifts = Shift::get();
        $sewerMachines = SewerMachine::get();

        $html_data = '<div class="modal-header">
                            <h5 class="modal-title" id="mySmallModalLabel">Önümçilik No #' . $sewerProd->id . ', Rulon: ' . $sewerProd->pivot_sewer[0]->amount . ' kg</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form data-request="onUpdateSewerItem" method="POST" data-request-flash data-request-confirm="BRAK halta sanyna seretdinizmi? Maglumatlar dogry bolsa Tassyklan.">
                                <div class="row">

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Status</label>

                                        <select class="form-control select2" name="status" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "disabled" : "") . '>
                                            <option value="working"' . ($sewerProd->pivot_sewer[0]->status == 'working' ? "selected" : "") . '>Işlenýär</option>
                                            <option value="complated" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "selected" : "") . '>Tamamlandy</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Smen Saýlaň</label>

                                        <select class="form-control select2" name="shift_id" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "disabled" : "") . '>';
        for ($x = 0; $x < count($shifts); $x++) {
            $html_data .= '<option value="' . $shifts[$x]->id . '" ' . ($sewerProd->shift_id == $shifts[$x]->id ? ' selected' : '') . '>' . $shifts[$x]->desc . '</option>';
        }
        $html_data .= '</select>
                                    </div>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Stanok Saýlaň</label>

                                        <select class="form-control select2" name="sewer_machine_id" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "disabled" : "") . '>';
        for ($x = 0; $x < count($sewerMachines); $x++) {
            $html_data .= '<option value="' . $sewerMachines[$x]->id . '" ' . ($sewerProd->sewer_machine_id == $sewerMachines[$x]->id ? ' selected' : '') . '>' . $sewerMachines[$x]->name . '</option>';
        }
        $html_data .= '</select>
                                    </div>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <div>
                                    <label class="form-label">Ugramaly Senesi</label>
                                        <div class="input-group" id="datepicker2">
                                            <input type="text" class="form-control" placeholder="d.m.Y"
                                                data-date-format="d.m.yyyy" data-date-container="#datepicker2" data-provide="datepicker"
                                                data-date-autoclose="true" name="date" value="' . (Carbon::parse($sewerProd->date)->format('d.m.Y')) . '" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "disabled" : "") . '>

                                            <span class="input-group-text"><i class="mdi mdi-calendar"></i></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Halta Ini</label>

                                        <input type="number" name="width" step="0.01" class="form-control"
                                            placeholder="Halta Ini" value="' . ($sewerProd->width == null ? 0 : $sewerProd->width) . '" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "disabled" : "") . '>
                                    </div>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Halta Boýy</label>

                                        <input type="number" name="height" step="0.01" class="form-control"
                                            placeholder="Halta Boýy" value="' . ($sewerProd->height == null ? 0 : $sewerProd->height) . '" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "disabled" : "") . '>
                                    </div>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Tikilen Halta (arassa)</label>

                                        <input type="number" name="produced_bag_qty" class="form-control"
                                            placeholder="tikilen halta sany" value="' . ($sewerProd->produced_bag_qty ?? 0) . '" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "disabled" : "") . '>

                                    </div>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">BRAK Halta sany</label>

                                        <input type="number" name="defective_bag_qty" class="form-control"
                                            placeholder="brak halta sany" value="' . ($sewerProd->defective_bag_qty ?? '') . '" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "disabled" : "") . '>

                                    </div>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Sürülmedik Halta sany</label>

                                        <input type="number" name="defective_repair_qty" class="form-control"
                                            placeholder="Sürülmedik Halta sany" value="' . ($sewerProd->defective_repair_qty ?? 0) . '" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "disabled" : "") . '>

                                    </div>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Turba agramy</label>

                                        <input type="number" name="pipe_weight" class="form-control"
                                            placeholder="Turba agramy"  value="' . ($sewerProd->pipe_weight ?? 0) . '" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "disabled" : "") . ' step="0.01"
                                            pattern="/^-?\d+\.?\d*$/"
                                            onKeyPress="if(this.value.length==4) return false;">

                                    </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="' . $sewerProd->note . '" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "disabled" : "") . '>
                                    </div>
                                </div>

                                </div>
                                <input type="hidden" name="sewer_id" value="' . $data["sewerId"] . '">
                                <button type="submit" data-bs-dismiss="modal"
                                    class="btn btn-primary waves-effect waves-light"
                                    style="margin-top: 15px;width: 100%;">Üýtget</button>
                            </form>
                        </div>';

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

    public function onUpdateSewerItem()
    {
        $currentDate = Carbon::now();
        $user = \Auth::user();
        $currentDateFormat =  $currentDate->format('Y-m-d');
        $stock = Stock::where("type", 'rulon')->first();
        $stockBag = Stock::where("type", 'bag')->first();

        $data = post();

        if ($data["produced_bag_qty"] == 0) {
            Flash::error("Tikilen halta sanyny girizin");
            return Redirect::refresh();
        } else {
            if (($data["status"] == "complated") && ($data["produced_bag_qty"] > 0)) {

                $sewer = SewerModel::where("id", $data["sewer_id"])->first();
                $pivotSewer = PivotSewer::where("sewer_production_id", $data["sewer_id"])->first();


                if ($sewer->is_sewed == 1) {
                    // $spentCalc = (float)((float) $pivotSewer->amount - (float) $data["left_amount"]);
                    $spentCalc = (float)((float) $data["produced_bag_qty"] * (float) $sewer->bag_gram) / 1000;
                    $spentCalcDefective = (float)((float) $data["defective_bag_qty"] * (float) $sewer->bag_gram) / 1000;
                    $spentCalcDefectiveRepair = (float)((float) $data["defective_repair_qty"] * (float) $sewer->bag_gram) / 1000;

                    $spentCalcDefectiveAll = (float)($spentCalcDefective + $spentCalcDefectiveRepair);

                    $allSpent = (float)($spentCalc + $spentCalcDefectiveAll);


                    $leftCalc = (float)((float)$pivotSewer->amount - $spentCalc);
                    $leftq = (float) ((float)$leftCalc - (float)$spentCalcDefectiveAll);


                    $sewer->shift_id = $data["shift_id"];
                    $sewer->sewer_machine_id = $data["sewer_machine_id"];
                    $sewer->defective_repair_qty = (float) $data["defective_repair_qty"];
                    $sewer->pipe_weight = (float) $data["pipe_weight"];

                    $sewer->produced_bag_qty = (float) $data["produced_bag_qty"];
                    $sewer->defective_bag_qty = (float) $data["defective_bag_qty"];
                    $sewer->width = (float) $data["width"];
                    $sewer->height = (float) $data["height"];
                    $sewer->date = Carbon::parse($data["date"])->format('Y-m-d');
                    $sewer->note = $data["note"];
                    $sewer->save();

                    $pivotSewer->left_amount = (float) ((float)$leftCalc - (float)$spentCalcDefectiveAll);
                    $pivotSewer->spent_amount = (float) ((float)$spentCalc + (float)$spentCalcDefectiveAll);
                    $pivotSewer->spent_defective_amount = (float) $spentCalcDefectiveAll;
                    $pivotSewer->status = $data["status"];
                    $pivotSewer->save();

                    $currentRulonAction = RulonAction::where("id", $pivotSewer->rulon_action_id)->first();
                    if($leftq > 0){

                        $createResult = new RulonAction();
                        $createResult->product_id = $currentRulonAction->product_id;
                        $createResult->type = 'inbox';
                        $createResult->status_accountant = "new";
                        $createResult->status_director = "new";
                        $createResult->note = "#Dikiş" . $sewer->id . " galyndy";
                        $createResult->amount = (float) $pivotSewer->left_amount;
                        $createResult->stock_id = $stock->id;
                        $createResult->user_id = $user->id;
                        $createResult->save();
                    }


                    $createResultBag = new BagAction();
                    $createResultBag->product_id = $sewer->id;
                    $createResultBag->type = 'inbox';
                    $createResultBag->status_accountant = "new";
                    $createResultBag->status_director = "new";
                    $createResultBag->note = "#Dikiş" . $sewer->id . " #Rulon" . $currentRulonAction->product_id;
                    $createResultBag->amount = $sewer->produced_bag_qty;
                    $createResultBag->stock_id = $stockBag->id;
                    $createResultBag->user_id = $user->id;
                    $createResultBag->save();



                    if ($sewer && $pivotSewer && $createResultBag) {
                        Flash::success("Maglumatlar Ustunlikli Üýtgedildi");
                        return Redirect::refresh();
                    } else {
                        Flash::error("Yalnyshlyk bar!!");
                        return Redirect::refresh();
                    }
                }else{

                     $spentCalc = 0;
                     $spentCalcDefective = 0;
                     $spentCalcDefectiveRepair = 0;

                     $spentCalcDefectiveAll = (float)($spentCalcDefective + $spentCalcDefectiveRepair);

                     $allSpent = (float)($spentCalc + $spentCalcDefectiveAll);


                     $leftCalc = (float)((float)$pivotSewer->amount - $spentCalc);

                     $sewer->shift_id = $data["shift_id"];
                     $sewer->sewer_machine_id = $data["sewer_machine_id"];
                     $sewer->defective_repair_qty = (float) $data["defective_repair_qty"];
                     $sewer->pipe_weight = (float) $data["pipe_weight"];

                     $sewer->produced_bag_qty = (float) $data["produced_bag_qty"];
                     $sewer->defective_bag_qty = (float) $data["defective_bag_qty"];
                     $sewer->width = (float) $data["width"];
                     $sewer->height = (float) $data["height"];
                     $sewer->date = Carbon::parse($data["date"])->format('Y-m-d');
                     $sewer->note = $data["note"];
                     $sewer->save();

                     $pivotSewer->left_amount = (float) ((float)$leftCalc - (float)$spentCalcDefectiveAll);
                     $pivotSewer->spent_amount = (float) ((float)$spentCalc + (float)$spentCalcDefectiveAll);
                     $pivotSewer->spent_defective_amount = (float) $spentCalcDefectiveAll;
                     $pivotSewer->status = $data["status"];
                     $pivotSewer->save();


                     $createResultBag = new BagAction();
                     $createResultBag->product_id = $sewer->id;
                     $createResultBag->type = 'inbox';
                     $createResultBag->status_accountant = "new";
                     $createResultBag->status_director = "new";
                     $createResultBag->note = "Sürülmedikler täzeden sürüldi";
                     $createResultBag->amount = $sewer->produced_bag_qty;
                     $createResultBag->stock_id = $stockBag->id;
                     $createResultBag->user_id = $user->id;
                     $createResultBag->save();



                     if ($sewer && $pivotSewer && $createResultBag) {
                         Flash::success("Maglumatlar Ustunlikli Üýtgedildi");
                         return Redirect::refresh();
                     } else {
                         Flash::error("Yalnyshlyk bar!!");
                         return Redirect::refresh();
                     }

                }
            } else {
                Flash::error("Statusy Tamlaň ya-da halta sany girizilmedik");
                return Redirect::refresh();
            }
        }
    }

    public function onRender()
    {
        $user = \Auth::user();
        $html_data = '';

        $crudSewerProductionq = $this->page["crudSewerProduction"];

        $sewerDatas = SewerModel::with(["employee", "shift", "sewer_machine", "color"])->with(["pivot_sewer" => function ($q) {
            $q->with(["rulon_action.product.bag_type", "rulon_action.product.bag_size", "rulon_action.product.color"]);
        }])->orderBy('id', 'DESC')->get();


        //dd($sewerDatas);
        for ($x = 0; $x < count($sewerDatas); $x++) {

            $dateTitle =  ($sewerDatas[$x]->date == null ? "" : Carbon::parse($sewerDatas[$x]->date)->format('d.m.Y'));

            $statusTitle = '';
            if ($sewerDatas[$x]->pivot_sewer[0]->status == "working") {
                $statusTitle = "Işlenilýär";
            } else {
                $statusTitle = "Tamamlandy";
            }

            $editBtn = '';

            $rulonDynamic = '';

            if ($sewerDatas[$x]->is_sewed == 1) {
                $rulonDynamic = '#Rulon' . ($sewerDatas[$x]->pivot_sewer[0]->rulon_action->product_id ?? 0) . '- ' . ($sewerDatas[$x]->pivot_sewer[0]->rulon_action->product->width ?? "") . ' x ' . ($sewerDatas[$x]->pivot_sewer[0]->rulon_action->product->gram ?? "") . ' m2, ' . ($sewerDatas[$x]->pivot_sewer[0]->rulon_action->product->bag_type->name ?? "") . ', ' . ($sewerDatas[$x]->color->name ?? "");
            } else {
                $rulonDynamic = 'Sürülmedik sürüldi, reňki: '.($sewerDatas[$x]->color->name ?? "");
            }

            if ($sewerDatas[$x]->user_id != $user->id) {
                $editBtn = '<div style="display: flex;justify-content: center;">
                                <div style="margin-right: 10px;">
                                    <a type="button"
                                        class="btn btn-warning waves-effect waves-light"
                                        style="padding-top: 5px;padding-bottom: 5px;">
                                        <i class="ri-user-line align-middle me-2"></i> Size degişli däl
                                    </a>
                                </div>
                            </div>';
            } else {
                $editBtn =  $crudSewerProductionq ? '<div style="display: flex;justify-content: center;">
                <div style="margin-right: 10px;">
                    <a type="button" data-request="onModalSetSewer"
                    data-request-data="sewerId: ' . $sewerDatas[$x]->id . '"
                        data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1"
                        class="btn btn-warning waves-effect waves-light"
                        style="padding-top: 5px;padding-bottom: 5px;">
                        <i class="ri-pencil-line align-middle me-2"></i> Täzele
                    </a>
                </div>
                <div>
                    <a type="button"
                        data-request="onDeleteSewerItem"
                        data-request-data="sewerId: ' . $sewerDatas[$x]->id . '"
                        data-request-confirm="#Dikiş' . $sewerDatas[$x]->id . '  pozmak isleýäňizmi?"
                        class="btn btn-danger waves-effect waves-light"
                        style="padding-top: 5px;padding-bottom: 5px;">
                        <i class="ri-close-line align-middle me-2"></i> Poz
                    </a>
                </div>
            </div>' : '';
            }

            $html_data .= '<tr>
                        <td style="font-weight: bold;">' . ($x + 1) . '</td>
                        <td>' . $dateTitle . '</td>
                        <td style="font-weight: bold;"> #Dikiş' . $sewerDatas[$x]->id . '</td>
                        <td>
                            ' . $rulonDynamic . '
                        </td>
                        <td><span class="badge badge-soft-success"
                                style="font-size: 14px;">' . number_format($sewerDatas[$x]->pivot_sewer[0]->amount, 2) . ' kg</span>
                        </td>
                        <td><span class="badge badge-soft-primary"
                                style="font-size: 14px;">ini: ' . ($sewerDatas[$x]->width ?? "") . '- boyy:' . ($sewerDatas[$x]->height ?? "") . ' </span>
                        </td>


                        <td><a href="#" style="font-weight: bold;">' . ($sewerDatas[$x]->sewer_machine->name ?? "") . '</a></td>


                        <td>' . (number_format($sewerDatas[$x]->bag_gram ?? 0, 2)) . ' gr</td>

                        <td style="color: darkgreen !important;">' . ($sewerDatas[$x]->produced_bag_qty ?? 0) . '</td>
                        <td style="color: darkred !important;">' . ($sewerDatas[$x]->defective_bag_qty ?? 0) . '</td>
                        <td style="color: darkred !important;">' . ($sewerDatas[$x]->defective_repair_qty ?? 0) . '</td>
                        <td>' . number_format($sewerDatas[$x]->pivot_sewer[0]->spent_amount, 2) . ' kg</td>
                        <td style="color: red;">' . number_format($sewerDatas[$x]->pivot_sewer[0]->left_amount, 2) . ' kg</td>
                        <td><span class="badge badge-soft-warning"
                        style="font-size: 14px;">' . $statusTitle . '</span></td>

                        <td>' . $sewerDatas[$x]->note . ' turba: ' . $sewerDatas[$x]->pipe_weight . '</td>
                        <td>
                            ' . $editBtn . '
                        </td>
                    </tr>';
        }

        return  $html_data;
    }

    public function onReportSewer()
    {

        $currentDate = Carbon::now();
        $currentDateFormat =  $currentDate->format('Y-m-d');

        $data = post();


        $sewerProductions = SewerModel::with(["employee", "rulon_action.product.bag_size", "rulon_action.product.bag_type", "rulon_action.product.color", "pivot_sewer"])->orderBy('id', 'DESC');

        $start = Carbon::parse($data["start"])->format('Y-m-d');
        $end = Carbon::parse($data["end"])->format('Y-m-d');;

        $status = $data["status"];
        $width = $data["width"];
        $height = $data["height"];
        $color_id = $data["color_id"];
        $bag_gram = $data["bag_gram"];

        $shift_id = $data["shift_id"];
        $sewer_machine_id = $data["sewer_machine_id"];



        if ($shift_id) {
            $sewerProductions->where("shift_id", $shift_id);
        }

        if ($sewer_machine_id) {
            $sewerProductions->where("sewer_machine_id", $sewer_machine_id);
        }

        if ($shift_id) {
            $sewerProductions->where("shift_id", $shift_id);
        }

        if ($height) {
            $sewerProductions->where("height", $height);
        }

        if ($width) {
            $sewerProductions->where("width", $width);
        }


        if ($status) {
            $sewerProductions->with("pivot_sewer")->whereHas('pivot_sewer', function ($query) use ($status) {
                $query->where('status', $status);
            });
        }

        if ($bag_gram) {
            $sewerProductions->where("bag_gram", $bag_gram);
        }

        if ($color_id) {
            $sewerProductions->where('color_id', $color_id);
        }





        if ($start != $currentDateFormat) {
            $sewerProductions->whereBetween('date', [$start, $end]);
        }

        $sewerDatas = $sewerProductions->get();

        $sewerIds = $sewerProductions->get()->pluck("id")->toArray();

        $sewerProductionsSumBagQty = $sewerProductions->sum("produced_bag_qty");
        $sewerProductionsSumDefectiveBagQty = $sewerProductions->sum("defective_bag_qty");
        $sewerProductionsSumDefectiveBagQtyRepair = $sewerProductions->sum("defective_repair_qty");

        $sewerProductionsamount = PivotSewer::whereIn("sewer_production_id", $sewerIds)->sum("spent_amount");
        // dd($sewerProductionsamount->spentAmount);
        $html_data = '';

        for ($x = 0; $x < count($sewerDatas); $x++) {
            $statusTitle = '';
            if ($sewerDatas[$x]->pivot_sewer[0]->status == "working") {
                $statusTitle = "Işlenilýär";
            } else {
                $statusTitle = "Tamamlandy";
            }

            $rulonDynamic = '';

            if ($sewerDatas[$x]->is_sewed == 1) {
                $rulonDynamic = '#Rulon' . ($sewerDatas[$x]->pivot_sewer[0]->rulon_action->product_id ?? 0) . '- ' . ($sewerDatas[$x]->pivot_sewer[0]->rulon_action->product->width ?? "") . ' x ' . ($sewerDatas[$x]->pivot_sewer[0]->rulon_action->product->gram ?? "") . ' m2, ' . ($sewerDatas[$x]->pivot_sewer[0]->rulon_action->product->bag_type->name ?? "") . ', ' . ($sewerDatas[$x]->color->name ?? "");
            } else {
                $rulonDynamic = 'Sürülmedik sürüldi, reňki: '.($sewerDatas[$x]->color->name ?? "");
            }

            $dateTitle =  ($sewerDatas[$x]->date == null ? "" : Carbon::parse($sewerDatas[$x]->date)->format('d.m.Y'));


            $html_data .= '<tr>
                        <td style="font-weight: bold;">' . ($x + 1) . '</td>
                        <td>' . $dateTitle . '</td>
                        <td style="font-weight: bold;"> #Dikiş' . $sewerDatas[$x]->id . '</td>
                        <td>'.$rulonDynamic.'
                        </td>
                        <td><span class="badge badge-soft-success"
                                style="font-size: 14px;">' . number_format($sewerDatas[$x]->pivot_sewer[0]->amount, 2) . ' kg</span>
                        </td>
                        <td><span class="badge badge-soft-primary"
                                style="font-size: 14px;">ini: ' . ($sewerDatas[$x]->width ?? "") . '- boyy:' . ($sewerDatas[$x]->height ?? "") . ' </span>
                        </td>


                        <td><a href="#" style="font-weight: bold;">' . ($sewerDatas[$x]->sewer_machine->name ?? "") . '</a></td>


                        <td>' . (number_format($sewerDatas[$x]->bag_gram ?? 0, 2)) . ' gr</td>

                        <td style="color: darkgreen !important;">' . ($sewerDatas[$x]->produced_bag_qty ?? 0) . '</td>
                        <td style="color: darkred !important;">' . ($sewerDatas[$x]->defective_bag_qty ?? 0) . '</td>
                        <td style="color: darkred !important;">' . ($sewerDatas[$x]->defective_repair_qty ?? 0) . '</td>
                        <td>' . number_format($sewerDatas[$x]->pivot_sewer[0]->spent_amount, 2) . ' kg</td>
                        <td>' . number_format($sewerDatas[$x]->pivot_sewer[0]->left_amount, 2) . ' kg</td>
                        <td><span class="badge badge-soft-warning"
                        style="font-size: 14px;">' . $statusTitle . '</span></td>

                        <td>' . $sewerDatas[$x]->note . ' turba: ' . $sewerDatas[$x]->pipe_weight . '</td>
                    </tr>';
        }

        if ($sewerDatas) {
            return [
                '#sewer_report_datas' => $html_data,
                '#all_amount' => '
                                    <div class="col-md-3">
                                        <div class="card bg-info text-white-50">
                                            <div class="card-body">
                                                <h5 class="text-white" style="text-transform: uppercase;margin-bottom: 0;"><i class="mdi mdi-bullseye-arrow me-3"></i> Dikilen Halta: ' . number_format($sewerProductionsSumBagQty) . ' sany</h5>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="card bg-danger text-white-50">
                                            <div class="card-body">
                                                <h5 class="text-white" style="text-transform: uppercase;margin-bottom: 0;"><i class="mdi mdi-bullseye-arrow me-3"></i> BRAK Halta: ' . number_format($sewerProductionsSumDefectiveBagQty) . ' sany</h5>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="card bg-warning text-white-50">
                                            <div class="card-body">
                                                <h5 class="text-white" style="text-transform: uppercase;margin-bottom: 0;"><i class="mdi mdi-bullseye-arrow me-3"></i> Sürülmedik Halta: ' . number_format($sewerProductionsSumDefectiveBagQtyRepair) . ' sany</h5>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="card bg-info text-white-50">
                                            <div class="card-body">
                                                <h5 class="text-white" style="text-transform: uppercase;margin-bottom: 0;"><i class="mdi mdi-bullseye-arrow me-3"></i> Sarp Edilen Çig mal: ' . number_format($sewerProductionsamount, 2) . ' kg</h5>
                                            </div>
                                        </div>
                                    </div>',
            ];
        } else {
            Flash::error("Yalnyshlyk bar!!");
        }
    }

    public function onCreateSewerProduction()
    {
        $user = \Auth::user();
        $currentDate = Carbon::now();

        $currentDateFormat =  $currentDate->format('Y-m-d');

        $data = post();

        if ($data["is_sewed"] == 1) {
            $currentRulonAction = RulonAction::where("id", $data["rulon_action_id"])->first();
            $rulonAmountSum = $currentRulonAction->amount;
            $stock = Stock::where("type", 'rulon')->first();
        }
        //  dd($leftAmount);

        $createSewer = new SewerModel();
        $createSewer->shift_id = $data["shift_id"];
        $createSewer->sewer_machine_id = $data["sewer_machine_id"];
        $createSewer->produced_bag_qty = 0;
        $createSewer->defective_bag_qty = 0;
        $createSewer->user_id = $user->id;
        $createSewer->note = $data["note"] ?? '';
        $createSewer->rulon_action_id = $data["is_sewed"] ? $data["rulon_action_id"] : 0;
        $createSewer->width = (float) $data["width"];
        $createSewer->height = (float) $data["height"];
        $createSewer->is_sewed = $data["is_sewed"];
        $createSewer->bag_gram = (float) $data["bag_gram"];
        $createSewer->color_id = $data["color_id"];
        $createSewer->date = Carbon::parse($data["date"])->format('Y-m-d');
        $createSewer->save();

        $createPivotSewer = new PivotSewer();
        $createPivotSewer->rulon_action_id = $createSewer->rulon_action_id;
        $createPivotSewer->sewer_production_id = $createSewer->id;
        $createPivotSewer->left_amount = 0;
        $createPivotSewer->amount = $rulonAmountSum ?? 0;
        $createPivotSewer->save();

        if ($createSewer->is_sewed == 1) {
            $createResult = new RulonAction();
            $createResult->product_id = $currentRulonAction->product_id;
            $createResult->type = 'outbox';
            $createResult->amount = -$rulonAmountSum;
            $createResult->stock_id = $stock->id;
            $createResult->user_id = $user->id;
            $createResult->note = "#Dikiş" . $createSewer->id . " üçin çykaryldy";
            $createResult->save();
        }


        if ($createSewer && $createPivotSewer) {

            Flash::success("Maglumatlar Ustunlikli Goshuldy");
            return Redirect::refresh();
        } else {
            Flash::error("Yalnyshlyk bar!!");
            return Redirect::refresh();
        }
    }

    public function onDeleteSewerItem()
    {
        $data = post();
        $user = \Auth::user();
        $sewer = SewerModel::where("id", $data["sewerId"])->with(['pivot_sewer', 'rulon_action.product'])->first();

        if ($sewer) {

            if ($sewer->produced_bag_qty > 0 && $sewer->is_sewed == 1) {
                $stock = Stock::where("type", 'rulon')->first();

                $createResult = new RulonAction();
                $createResult->product_id = $sewer->rulon_action->product_id;
                $createResult->type = 'inbox';
                $createResult->amount = (float)$sewer->pivot_sewer[0]->spent_amount;
                $createResult->stock_id = $stock->id;
                $createResult->user_id = $user->id;
                $createResult->note = "#Dikiş" . $sewer->id . " maglumat girizidi, soňundan pozulan";
                $createResult->save();


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

                $createResultBag = new BagAction();
                $createResultBag->product_id = $sewer->id;
                $createResultBag->type = 'outbox';
                $createResultBag->status_accountant = "new";
                $createResultBag->status_director = "new";
                $createResultBag->note = "#Dikiş" . $sewer->id . " maglumat girizidi, soňundan pozulan";
                $createResultBag->amount = -$sewer->produced_bag_qty;
                $createResultBag->stock_id = $stockBag->id;
                $createResultBag->user_id = $user->id;
                $createResultBag->save();
            } elseif ($sewer->produced_bag_qty == 0) {
                $stock = Stock::where("type", 'rulon')->first();

                $createResult = new RulonAction();
                $createResult->product_id = $sewer->rulon_action->product_id;
                $createResult->type = 'inbox';
                $createResult->amount = (float)$sewer->pivot_sewer[0]->amount;
                $createResult->stock_id = $stock->id;
                $createResult->user_id = $user->id;
                $createResult->note = "#Dikiş" . $sewer->id . " maglumat girizidi, soňundan pozulan";
                $createResult->save();
            }elseif ($sewer->is_sewed == 0 && $sewer->produced_bag_qty > 0) {

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

                $createResultBag = new BagAction();
                $createResultBag->product_id = $sewer->id;
                $createResultBag->type = 'outbox';
                $createResultBag->status_accountant = "new";
                $createResultBag->status_director = "new";
                $createResultBag->note = "#Dikiş" . $sewer->id . " sürülmedik, soňundan pozulan";
                $createResultBag->amount = -$sewer->produced_bag_qty;
                $createResultBag->stock_id = $stockBag->id;
                $createResultBag->user_id = $user->id;
                $createResultBag->save();

            }
        }

        $sewer->delete();

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