<?php

namespace Romanah\Gokbakja\Components;

use Cms\Classes\ComponentBase;
use Romanah\Gokbakja\Models\Product as ProductModel;
use Romanah\Gokbakja\Models\Production as ProductionModel;
use Romanah\Gokbakja\Models\ProductionMachine as ProductionMachineModel;
use Romanah\Gokbakja\Models\PivotProduction as PivotProductionModel;
use Redirect;
use Carbon\Carbon;
use Flash;
// use Illuminate\Validation\Validator;
use Validator;
use ValidationException;
use DB;
use Romanah\Gokbakja\Models\BagColor;
use Romanah\Gokbakja\Models\BagSize;
use Romanah\Gokbakja\Models\BagType;
use Romanah\Gokbakja\Models\Journal;
use Romanah\Gokbakja\Models\Machine;
use Romanah\Gokbakja\Models\PivotSewer;
use Romanah\Gokbakja\Models\RulonAction;

class MachineProduction extends ComponentBase
{


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

    public function onModalSetMachineData()
    {

        $data = post();
        $machinProdId = $data["machineProdId"];

        $productions = PivotSewer::whereHas("rulon_action", function ($q) use ($machinProdId) {
            $q->where('product_id', $machinProdId);
        })->with(["sewer_production", "rulon_action.product"])->get();

        $machineProductionData = ProductionMachineModel::where('id', $machinProdId)->first();

        $allBagQty = 0;
        $allSpent = 0;
        $allLeft = 0;

        //dd(count($productions));

        if (count($productions) > 0) {
            $html_data = '<div class="modal-header">
                            <h5 class="modal-title" id="mySmallModalLabel">#Rulon' . $machinProdId . ' Agramy: ' . $machineProductionData->produced_weight . ' kg</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>
                        <div class="modal-body">

                        <table id="datatable-buttons2" class="table table-striped table-bordered dt-responsive nowrap"
                                        style="border-collapse: collapse; border-spacing: 0; width: 100%;">

                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>#Rulon Kody</th>
                                                <th>#Dikiş Kody</th>
                                                <th>Dikiş Senesi</th>
                                                <th>Dikilen Halta Mukdary</th>
                                                <th>Mukdary (kg)</th>
                                                <th>Ulanylan (kg)</th>
                                                <th>Galyndy (kg)</th>
                                                <th>Status</th>
                                            </tr>
                                        </thead>
                        ';

            for ($x = 0; $x < count($productions); $x++) {
                $allBagQty += $productions[$x]->sewer_production->produced_bag_qty;
                $allSpent += $productions[$x]->spent_amount;
                $allLeft += $productions[$x]->left_amount;

                $html_data .= '<tr>
                                <td>' . ($x + 1) . '</td>
                                <td>#Rulon' . $productions[$x]->machine_production_id . '</td>
                                <td>#Dikiş' . $productions[$x]->sewer_production_id . '</td>
                                <td>' . ($productions[$x]->sewer_production->date == null ? "" : Carbon::parse($productions[$x]->sewer_production->date)->format('d.m.Y')) . '</td>
                                <td>' . ($productions[$x]->sewer_production->produced_bag_qty) . '</td>
                                <td>' . $productions[$x]->amount . ' kg</td>
                                <td>' . $productions[$x]->spent_amount . ' kg</td>
                                <td>' . $productions[$x]->left_amount . ' kg</td>
                                <td>' . $productions[$x]->status . '</td>
                            </tr>';
            }
            $html_data .= '<tr style="background: #a2a9ff !important;">
                                                <td colspan="4" style="font-weight: 700;color: black;">JEMI</td>
                                                <td style="font-weight: 700;color: black;">' . $allBagQty . ' sany</td>
                                                <td></td>
                                                <td style="font-weight: 700;color: black;">' . $allSpent . ' kg</td>
                                                <td style="font-weight: 700;color: black;"></td>
                                                <td></td>
                                            </tr>';

            $html_data .= '</table></div>';
        } else {
            $html_data = '<div class="modal-header">
                                <h5 class="modal-title" id="mySmallModalLabel">Maglumat Yok</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"
                                    aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <p></p>
                            </div>';
        }



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

    public function onSetFormUpdate()
    {
        $data = post();
        $machinProdId = $data["machineProdId"];

        $user = \Auth::user();

        $production = ProductionMachineModel::where("id", $machinProdId)->first();

        $colors = BagColor::get();
        $types = BagType::get();
        $machines = Machine::get();

        $html_data = '<div class="modal-header">
                            <h5 class="modal-title" id="mySmallModalLabel">#Rulon' . $machinProdId . ' Agramy: ' . $production->produced_weight . ' kg</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>
                        <div class="modal-body">';
        $html_data .= '<form data-request="onUpdateMachineProduction" data-request-flash>
                            <div class="row">

                                <div class="col-md-12 mt-3">
                                <label style="color: black;">Jogapkär</label>
                                    <input type="text" name="employee_name" class="form-control" placeholder="Jogapkär" value="' . ($production->employee_name ?? "") . '" ' . ($production->user_id != $user->id ? 'disabled' : '') . '>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <label style="color: black;">Enjam</label>
                                    <select class="form-control select2" name="machine_id" ' . ($production->user_id != $user->id ? 'disabled' : '') . '>
                                        <option value="0">Enjam Saýla</option>';
        for ($x = 0; $x < count($machines); $x++) {
            $html_data .= '<option value="' . $machines[$x]->id . '" ' . ($production->machine_id == $machines[$x]->id ? 'selected' : '') . '>' . $machines[$x]->name . '</option>';
        }

        $html_data .= '</select>
                                </div>

                                <div class="col-md-12 mt-3">
                                <label style="color: black;">Gat sany</label>
                                    <select class="form-control select2" name="layer" ' . ($production->user_id != $user->id ? 'disabled' : '') . '>
                                        <option value="1">Rulon Gat sany</option>

                                        <option value="1" ' . ($production->layer == 1 ? 'selected' : '') . '>1 gat</option>
                                        <option value="2" ' . ($production->layer == 2 ? 'selected' : '') . '>2 gat</option>

                                    </select>
                                </div>
                                <div class="col-md-12 mt-3">
                                    <label style="color: black;">Sene</label>
                                    <input type="date" name="date" class="form-control" placeholder="Sene" value="' . ($production->date != null ? Carbon::parse($production->date)->format('Y-m-d') : "") . '" ' . ($production->user_id != $user->id ? 'disabled' : '') . '>

                                </div>

                                <div class="col-md-12 mt-3">
                                    <label style="color: black;">Görnüşi</label>
                                    <select class="form-control select2" name="type_id" ' . ($production->user_id != $user->id ? 'disabled' : '') . '>
                                        <option value="0">Görnüş Saýla</option>';
        for ($x = 0; $x < count($types); $x++) {
            $html_data .= '<option value="' . $types[$x]->id . '" ' . ($production->type_id == $types[$x]->id ? 'selected' : '') . '>' . $types[$x]->name . '</option>';
        }
        $html_data .= '</select>
                                </div>
                                <div class="col-md-12 mt-3">
                                <label style="color: black;">Ini</label>
                                <input type="number" name="width" step="0.01" class="form-control"
                                    placeholder="Ini" value="' . ($production->width ?? "") . '" ' . ($production->user_id != $user->id ? 'disabled' : '') . '>
                                </div>

                                <div class="col-md-12 mt-3">
                                <label style="color: black;">Gram</label>
                                    <input type="number" name="gram" step="0.01" class="form-control"
                                        placeholder="Gram" value="' . ($production->gram ?? "") . '" ' . ($production->user_id != $user->id ? 'disabled' : '') . '>
                                </div>
                                <div class="col-md-12 mt-3">
                                    <label style="color: black;">Reňki</label>
                                    <select class="form-control select2" name="color_id" ' . ($production->user_id != $user->id ? 'disabled' : '') . '>
                                        <option value="0">Reňk Saýla</option>';
        for ($x = 0; $x < count($colors); $x++) {
            $html_data .= '<option value="' . $colors[$x]->id . '" ' . ($production->color_id == $colors[$x]->id ? 'selected' : '') . '>' . $colors[$x]->name . '</option>';
        }
        $html_data .= '</select>
                                </div>
                                <div class="col-md-12 mt-3">
                                    <label style="color: black;">Öndürlen önüm (kg)</label>
                                    <input type="number" name="produced_weight" step="0.01" class="form-control"
                                        placeholder="Mukdar (kg)" value="' . ($production->produced_weight ?? "") . '" ' . ($production->user_id != $user->id ? 'disabled' : '') . '>
                                </div>
                                <div class="col-md-12 mt-3">
                                   <label style="color: black;">Brutto (kg)</label>
                                    <input type="number" name="brutto_kg" step="0.01" class="form-control"
                                        placeholder="Brutto (kg)" value="' . ($production->brutto_kg ?? "") . '" ' . ($production->user_id != $user->id ? 'disabled' : '') . '>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <label style="color: black;">Othod (kg)</label>
                                    <input type="number" name="defective_weight" step="0.01" class="form-control"
                                        placeholder="Othod (kg)" value="' . ($production->defective_weight ?? "") . '" ' . ($production->user_id != $user->id ? 'disabled' : '') . '>
                                </div>
                                <div class="col-md-12 mt-3">
                                    <label style="color: black;">Bellik</label>
                                    <input type="text" name="note" class="form-control" placeholder="Bellik" value="' . $production->note . '" ' . ($production->user_id != $user->id ? 'disabled' : '') . '>
                                </div>
                                <input type="hidden" name="production_id" value="' . $production->id . '">
                                <div class="col-md-12 mt-3">
                                    <button ' . ($production->user_id != $user->id ? 'disabled' : '') . ' type="submit" class="btn btn-primary waves-effect waves-light"
                                        style="width: 100%;">Üýtget</button>
                                </div>

                                </div>
                            </div>
                        </form>';
        $html_data .= '</div>';

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

    public function onDeleteProductionMachine()
    {
        $id = post('production_id');

        $productionDelete = ProductionMachineModel::Find($id);
        $productionDelete->delete();

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

    public function onRender()
    {

        $user = \Auth::user();
        $html_data = '';

        $crudProductionRulonq = $this->page["crudProductionRulon"];
        $inboxProductionRulonq = $this->page["inboxProductionRulon"];

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

        $machineProductions = ProductionMachineModel::with(['bag_type', 'machine.building', 'employee', 'mechanic', 'color', 'shift'])->orderBy('id', 'DESC')->get();

        $html_data = '';
        for ($x = 0; $x < count($machineProductions); $x++) {

            $inStock = RulonAction::where("product_id", $machineProductions[$x]->id)->count();

            $editBtn = '';

            if ($machineProductions[$x]->user_id != $user->id) {
                $editBtn = '<a href="#" style="font-weight: bold;color: darkred;"> Size degişli däl </a>';
            } else {
                if (!$inStock) {

                    $editBtn = $crudProductionRulonq ? '<button data-request="onSetFormUpdate" data-bs-toggle="modal" data-bs-target=".bs-example-modal-lg" data-request-data="machineProdId: ' . $machineProductions[$x]->id . '" type="button" class="btn btn-warning waves-light waves-effect"><i class="fa fa-pen"></i></button> &nbsp;&nbsp;' : '';

                    $editBtn .= $inboxProductionRulonq ? '<button data-request="onCreateAction" data-request-data="type: ' . ((string) "'inbox'") . ', itemId: ' . $machineProductions[$x]->id . '" data-request-confirm="Bu harydy sklada salmak iskleýäňizmi?" type="button" class="btn btn-success waves-light waves-effect"><i class="fa ri-upload-line"></i></button>' : '';
                } else {

                    $editBtn = '<a href="#" style="font-weight: bold;color: darkgreen;"> Sklada salyndy </a>';
                }
            }
            // dd($machineProductions[0]->bag_size);
            $html_data .= '<tr>
                        <td style="font-weight: bold;">' . ($x + 1) . '</td>
                        <td style="font-weight: bold;"><a type="button" data-request="onModalSetMachineData"
                        data-request-data="machineProdId: ' . $machineProductions[$x]->id . '"
                            data-bs-toggle="modal" data-bs-target=".bs-example-modal-lg" style="color: darkblue;"> #Rulon' . ($machineProductions[$x]->id) . '</a></td>
                        <td><a href="#">' . ($machineProductions[$x]->date == null ? "" : Carbon::parse($machineProductions[$x]->date)->format('d.m.Y')) . '</a></td>
                        <td>' . ($machineProductions[$x]->shift->desc ?? '') . '</td>
                        <td>' . $machineProductions[$x]->machine->name . '</td>
                        <td>' . $machineProductions[$x]->width . '</td>
                        <td>' . $machineProductions[$x]->gram . ' m2</td>
                        <td>' . $machineProductions[$x]->bag_type->name . '</td>
                        <td>' . ($machineProductions[$x]->color->name ?? "") . ', ' . $machineProductions[$x]->layer . ' gat</td>
                        <td><span class="badge badge-soft-success"
                                style="font-size: 14px;">' . number_format($machineProductions[$x]->produced_weight, 2) . ' kg</span>
                        </td>
                        <td><span class="badge badge-soft-warning"
                                style="font-size: 14px;">' . number_format($machineProductions[$x]->brutto_kg, 2) . ' kg</span>
                        </td>
                        <td><span class="badge badge-soft-primary"
                                style="font-size: 14px;">' . number_format($machineProductions[$x]->produced_length, 2) . ' m</span>
                        </td>
                        <td><span class="badge badge-soft-danger"
                                style="font-size: 14px;">' . number_format($machineProductions[$x]->defective_weight, 2) . ' kg</span>
                        </td>
                        <td>' . $machineProductions[$x]->employee_name . '</td>
                        <td>' . $machineProductions[$x]->note . '</td>
                        <td> ' . $editBtn . '  </td>
                    </tr>';
        }

        return  $html_data;
    }

    public function onReport()
    {

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

        $data = post();


        $machineProductions = ProductionMachineModel::with(['bag_type', 'bag_size', 'machine.building', 'employee', 'mechanic', 'color', 'shift'])
            ->orderBy('id', 'DESC');

        $machineProductionsCalc = ProductionMachineModel::with(['bag_type', 'bag_size', 'machine.building', 'employee', 'mechanic', 'color', 'shift'])
            ->orderBy('id', 'DESC');

        $start = Carbon::parse($data["start"])->format('Y-m-d');
        $end = Carbon::parse($data["end"])->format('Y-m-d');
        $machine = $data["machine_id"];
        // $mechanic = $data["mechanic_id"];
        $type = $data["type_id"];
        $shift = $data["shift_id"];

        $width = $data["width"];
        $employee_name = $data["employee_name"];
        $gram = $data["gram"];
        $layer = $data["layer"];
        // $is_finished = $data["is_finished"];


        // if ($is_finished) {
        //     $machineProductions->where("is_finished", (bool) $is_finished);
        // }

        if ($employee_name) {
            $machineProductions->where("employee_name", "like", "%" . $employee_name . "%");
            $machineProductionsCalc->where("employee_name", "like", "%" . $employee_name . "%");
        }

        if ($machine) {
            $machineProductions->where("machine_id", $machine);
            $machineProductionsCalc->where("machine_id", $machine);
        }

        if ($shift) {
            $machineProductions->where("shift_id", $shift);
            $machineProductionsCalc->where("shift_id", $shift);
        }

        // if ($mechanic) {
        //     $machineProductions->where("mechanic_id", $mechanic);
        //     $machineProductionsCalc->where("mechanic_id", $mechanic);
        // }

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

        if ($layer) {
            $machineProductions->where("layer", $layer);
            $machineProductionsCalc->where("layer", $layer);
        }

        if ($gram) {
            $machineProductions->where("gram", $gram);
            $machineProductionsCalc->where("gram", $gram);
        }

        if ($type) {
            $machineProductions->where("type_id", $type);
            $machineProductionsCalc->where("type_id", $type);
        }

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


        $machineProductionsFiltered = $machineProductions->get();
        $machineProductionsSum = $machineProductionsCalc->sum("produced_weight");
        $machineProductionsBruttoSum = $machineProductionsCalc->sum("brutto_kg");
        $machineProductionsDefectiveSum = $machineProductionsCalc->sum("defective_weight");

        $html_data = '';

        for ($x = 0; $x < count($machineProductionsFiltered); $x++) {


            $html_data .= '<tr>
                        <td style="font-weight: bold;">' . ($x + 1) . '</td>
                        <td style="font-weight: bold;"><a type="button" data-request="onModalSetMachineData"
                        data-request-data="machineProdId: ' . $machineProductionsFiltered[$x]->id . '"
                            data-bs-toggle="modal" data-bs-target=".bs-example-modal-lg" style="color: darkblue;"> #Rulon' . ($machineProductionsFiltered[$x]->id) . '</a></td>
                        <td><a href="#">' . ($machineProductionsFiltered[$x]->date == null ? "" : Carbon::parse($machineProductionsFiltered[$x]->date)->format('d.m.Y')) . '</a></td>
                        <td>' . ($machineProductionsFiltered[$x]->shift->desc ?? '') . '</td>
                        <td>' . $machineProductionsFiltered[$x]->machine->name . '</td>
                        <td>' . $machineProductionsFiltered[$x]->width . '</td>
                        <td>' . $machineProductionsFiltered[$x]->gram . ' m2</td>
                        <td>' . $machineProductionsFiltered[$x]->bag_type->name . '</td>
                        <td>' . ($machineProductionsFiltered[$x]->color->name ?? "") . ', ' . $machineProductionsFiltered[$x]->layer . ' gat</td>
                        <td><span class="badge badge-soft-success"
                                style="font-size: 14px;">' . number_format($machineProductionsFiltered[$x]->produced_weight, 2) . ' kg</span>
                        </td>
                        <td><span class="badge badge-soft-warning"
                                style="font-size: 14px;">' . number_format($machineProductionsFiltered[$x]->brutto_kg, 2) . ' kg</span>
                        </td>
                        <td><span class="badge badge-soft-primary"
                                style="font-size: 14px;">' . number_format($machineProductionsFiltered[$x]->produced_length, 2) . ' m</span>
                        </td>
                        <td><span class="badge badge-soft-danger"
                                style="font-size: 14px;">' . number_format($machineProductionsFiltered[$x]->defective_weight, 2) . ' kg</span>
                        </td>
                        <td>' . $machineProductionsFiltered[$x]->employee_name . '</td>
                        <td>' . $machineProductionsFiltered[$x]->note . '</td>
                    </tr>';
        }

        if ($machineProductionsFiltered) {
            return [
                '#machine_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;">Öndürlen Rulon: ' . count($machineProductionsFiltered) . '</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> Öndürlen: ' . number_format($machineProductionsSum, 2) . ' kg</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>Brutto Agramy: ' . number_format($machineProductionsBruttoSum, 2) . ' kg</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> Othod: ' . number_format($machineProductionsDefectiveSum, 2) . ' kg</h5>
                                                </div>
                                            </div>
                                        </div>',
            ];
        } else {
            Flash::error("Yalnyshlyk bar!!");
        }
    }


    public function onUpdateMachineProduction()
    {

        $user = \Auth::user();

        $data = post();
        $oldData = ProductionMachineModel::where("id", $data["production_id"])
            ->with(['bag_type', 'bag_size', 'machine.building', 'employee', 'mechanic', 'color'])
            ->first();





        $updateProductionMachine = ProductionMachineModel::where("id", $data["production_id"])
            ->with(['bag_type', 'bag_size', 'machine.building', 'employee', 'mechanic', 'color'])
            ->first();


        $metrOfRulon = (float)((float)($data["gram"] / 100) * ($data["width"] / 100)) * (int)$data["layer"];
        $metrOfAllRulon = (float) $data["produced_weight"] / $metrOfRulon;


        $updateProductionMachine->type_id = (int) $data["type_id"];
        $updateProductionMachine->width = $data["width"];
        $updateProductionMachine->gram = $data["gram"];
        $updateProductionMachine->brutto_kg = $data["brutto_kg"];
        $updateProductionMachine->layer = $data["layer"];
        $updateProductionMachine->machine_id = (int) $data["machine_id"];
        $updateProductionMachine->color_id = (int) $data["color_id"];
        $updateProductionMachine->produced_weight = $data["produced_weight"];
        $updateProductionMachine->produced_length = $metrOfAllRulon;
        $updateProductionMachine->defective_weight = $data["defective_weight"];
        $updateProductionMachine->note = $data["note"];
        $updateProductionMachine->date = Carbon::parse($data["date"])->format('Y-m-d');



        $contentJournal = array(
            "old_data" => $oldData,
            "new_data" => $updateProductionMachine,
        );

        $journal = new Journal();

        $journal->type = "ProductionMachine";
        $journal->content_id = $data["production_id"];
        $journal->user_id = $user->id;
        $journal->data = $contentJournal;
        $journal->save();

        $updateProductionMachine->save();

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


    protected function validateForm($data, $rules)
    {
        $validator = Validator::make($data, $rules);

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }
    }

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

        $data = post();


        if (empty($data["produced_weight"]) || $data["type_id"] == 0 || $data["machine_id"] == 0) {
            Flash::error("Gutulary Dolduryn!");
            return [
                '#validationq' => '  Gutulary Dolduryn!',
            ];
        } else {
            $dateq = Carbon::parse($data["date"])->format('Y-m-d');
            $bruttoq = $data["brutto_kg"];
            $layerq = $data["layer"];
            $produced_weightq = $data["produced_weight"];
            $machineq = $data["machine_id"];

            $rulonq = ProductionMachineModel::where('produced_weight', $produced_weightq)
                ->where('brutto_kg', $bruttoq)
                ->where('layer', $layerq)
                ->where('machine_id', $machineq)
                ->where('date', $dateq)
                ->first();

            if ($rulonq) {

                Flash::error("Bu Senede Haryt öň girizilen!!!");
                return Redirect::refresh();

            } else {

                $createProductionMachine = new ProductionMachineModel();

                $metrOfRulon = (float)((float)($data["gram"] / 100) * ($data["width"] / 100)) * (int)$data["layer"];
                $metrOfAllRulon = (float) $data["produced_weight"] / $metrOfRulon;

                $createProductionMachine->type_id = $data["type_id"];
                $createProductionMachine->width = $data["width"];
                $createProductionMachine->gram = $data["gram"];
                $createProductionMachine->brutto_kg = $data["brutto_kg"];
                $createProductionMachine->layer = $data["layer"];
                $createProductionMachine->machine_id = $data["machine_id"];
                $createProductionMachine->shift_id = $data["shift_id"];
                $createProductionMachine->color_id = $data["color_id"];
                $createProductionMachine->produced_weight = $data["produced_weight"];
                $createProductionMachine->produced_length = $metrOfAllRulon;
                $createProductionMachine->defective_weight = $data["defective_weight"];
                $createProductionMachine->employee_name = $data["employee_name"];
                $createProductionMachine->mechanic_name = $data["employee_name"];
                $createProductionMachine->note = $data["note"];
                $createProductionMachine->date = Carbon::parse($data["date"])->format('Y-m-d');
                $createProductionMachine->user_id = $user->id;
                $createProductionMachine->save();

                $productionMachine = ProductionMachineModel::where('id', $createProductionMachine->id)->with(['machine.employee', 'machine.mechanic', 'machine.building'])->first();
                // dd($productionMachine->machine->name);
                if ($productionMachine) {
                    $updateResult = ProductionMachineModel::where('id', $productionMachine->id)
                        ->update(array(
                            'building_name' => $productionMachine->machine->building->name,
                        ));
                }



                if ($createProductionMachine &&  $updateResult) {

                    Flash::success("Hasabat Ustunlikli Goşuldy");
                    return Redirect::refresh();
                } else {
                    Flash::error("Yalnyshlyk bar!!");
                    return Redirect::refresh();
                }
            }
        }
    }
}
