<?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\ProductionMachine;
use Romanah\Gokbakja\Models\PivotSewer;

class Sewer extends ComponentBase
{

    public $sewers;

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



    // public function onRun() {
    //     $this->sewers = $this->loadSewers();
    // }

    public function onModalSetSewer()
    {

        $data = post();

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

        $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>
                                <div class="row">

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

                                        <select class="form-control select2" name="status">
                                            <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">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">
                                    <label class="form-label">Tikinçi</label>
                                    <input type="text" name="employee" class="form-control" value="' . $sewerProd->employee->name . '" disabled>
                                </div>

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

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

                                    </div>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Galyndy (kg) </label>

                                        <input type="number" name="left_amount" step="0.01" class="form-control"
                                            placeholder="Galyndy (kg)" value="' . ($sewerProd->pivot_sewer[0]->left_amount) . '" ' . ($sewerProd->pivot_sewer[0]->status == 'complated' ? "disabled" : "") . '>
                                    </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()->timezone('UTC +05:00');

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

        $data = post();

        if ($data["produced_bag_qty"] == 0) {
            return Flash::error("Tikilen halta sanyny girizin");
        }elseif(!$data["produced_bag_qty"] && $data["status"] == "working"){

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

            $pivotSewer->status = $data["status"];
            $pivotSewer->save();

            if ($sewer && $pivotSewer) {
                Flash::success("Maglumatlar Ustunlikli Üýtgedildi");
                return Redirect::refresh();
            } else {
                return Flash::error("Yalnyshlyk bar!!");
                return Redirect::refresh();
            }
        } else {
            $sewer = SewerModel::where("id", $data["sewer_id"])->first();
            $pivotSewer = PivotSewer::where("sewer_production_id", $data["sewer_id"])->first();

            $spentCalc = (float)((float) $pivotSewer->amount - (float) $data["left_amount"]);

            $sewer->produced_bag_qty = (float) $data["produced_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) $data["left_amount"];
            $pivotSewer->spent_amount = (float) $spentCalc;
            $pivotSewer->status = $data["status"];
            $pivotSewer->save();

            if ($data["left_amount"] == 0 && $data["status"] == "complated") {
                $machinProduction = ProductionMachine::where("id", $pivotSewer->machine_production_id)->first();
                $machinProduction->is_finished = true;
                $machinProduction->save();
            }else{
                return Flash::error("Status tamamlamaly!");
            }

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

    public function onRender()
    {

        $html_data = '';

        $sewerDatas = SewerModel::with(["employee", "machin_production.bag_size", "machin_production.bag_type", "machin_production.color", "pivot_sewer"])->orderBy('id', 'DESC')->get();
        // dd($sewerDatas);
        for ($x = 0; $x < count($sewerDatas); $x++) {
            $statusTitle = '';
            if ($sewerDatas[$x]->pivot_sewer[0]->status == "working") {
                $statusTitle = "Işlenilýär";
            } else {
                $statusTitle = "Tamamlandy";
            }

            $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 style="font-weight: bold;"> #' . $sewerDatas[$x]->id . '</td>
                        <td><span class="badge badge-soft-primary"
                                style="font-size: 14px;">ini: ' . ($sewerDatas[$x]->width ?? "") . '- boyy:' . ($sewerDatas[$x]->height ?? "") . ' </span>
                        </td>
                        <td> #' . $sewerDatas[$x]->machin_production->id . '- ' . ($sewerDatas[$x]->machin_production->bag_size->width ?? "") . 'x' . ($sewerDatas[$x]->machin_production->bag_size->height ?? "") . 'm2, ' . ($sewerDatas[$x]->machin_production->bag_type->name ?? "") . ', ' . ($sewerDatas[$x]->machin_production->color->name ?? "") . '
                        </td>
                        <td><a href="#" style="font-weight: bold;">' . $sewerDatas[$x]->employee->name . '</a></td>
                       <td>' . $dateTitle . '</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>' . $sewerDatas[$x]->produced_bag_qty . '</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 . '</td>
                        <td>
                        <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"
                                    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>
                        </td>
                    </tr>';
        }

        return  $html_data;
    }

    public function onReportSewer()
    {

        $currentDate = Carbon::now()->timezone('UTC +05:00');
        $currentDateFormat =  $currentDate->format('Y-m-d');

        $data = post();


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

        $start = Carbon::parse($data["start"])->format('Y-m-d');
        $end = Carbon::parse($data["end"])->format('Y-m-d');;
        $employee = $data["employee_id"];
        $min = $data["min"];
        $max = $data["max"];
        $status = $data["status"];
        $width = $data["width"];
        $height = $data["height"];



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

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

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

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

        if ($min) {
            $sewerProductions->whereRaw('produced_bag_qty >' . ($min - 1));
        }

        if ($max) {
            $sewerProductions->whereRaw('produced_bag_qty <' . ($max + 1));
        }



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

        $sewerDatas = $sewerProductions->get();

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

        $sewerProductionsSumBagQty = $sewerProductions->sum("produced_bag_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";
            }

            $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 style="font-weight: bold;"> #' . $sewerDatas[$x]->id . '</td>
                        <td><span class="badge badge-soft-primary"
                                style="font-size: 14px;">ini: ' . ($sewerDatas[$x]->width ?? "") . '- boyy:' . ($sewerDatas[$x]->height ?? "") . ' </span>
                        </td>
                        <td> #' . $sewerDatas[$x]->machin_production->id . '- ' . ($sewerDatas[$x]->machin_production->bag_size->width ?? "") . 'x' . ($sewerDatas[$x]->machin_production->bag_size->height ?? "") . 'm2, ' . ($sewerDatas[$x]->machin_production->bag_type->name ?? "") . ', ' . ($sewerDatas[$x]->machin_production->color->name ?? "") . '
                        </td>
                        <td><a href="#" style="font-weight: bold;">' . $sewerDatas[$x]->employee->name . '</a></td>
                       <td>' . $dateTitle . '</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>' . $sewerDatas[$x]->produced_bag_qty . '</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 . '</td>

                    </tr>';
        }

        if ($sewerDatas) {
            return [
                '#sewer_report_datas' => $html_data,
                '#all_amount' => '<div class="col-md-6">
                                        <h3 class="card-title" style="font-size: 22px;color: #1e2038;">Tikinçiler Boýunça Umumy</h3>
                                        <p class="card-title-desc" style="color: #6c6ff5;">Hasabat</p>
                                    </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> Jemi Dikilen Halta: ' . number_format($sewerProductionsSumBagQty) . ' 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> Jemi Sarp Edilen Çig mal: ' . number_format($sewerProductionsamount, 2) . ' kg</h5>
                                            </div>
                                        </div>
                                    </div>',
            ];
        } else {
            Flash::error("Yalnyshlyk bar!!");
        }
    }

    public function onCreateSewerProduction()
    {
        $currentDate = Carbon::now()->timezone('UTC +05:00');

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

        $data = post();

        $machineProduction = ProductionMachine::where("id", $data["machine_production_id"])->first();

        $machineProductionSpent = PivotSewer::where("machine_production_id", $data["machine_production_id"])->sum('spent_amount');

        $leftAmount = 0;
        if ($machineProduction->produced_weight > $machineProductionSpent) {
            $calcLeft = ((float) $machineProduction->produced_weight - (float) $machineProductionSpent);

            $leftAmount = $calcLeft;
        } elseif ($machineProduction->produced_weight == $machineProductionSpent) {
            $leftAmount = 0;
        } else {
            $leftAmount = 0;
        }

        //  dd($leftAmount);

        $createSewer = new SewerModel();
        $createSewer->employee_id = $data["employee_id"];
        $createSewer->produced_bag_qty = 0;
        $createSewer->note = $data["note"] ?? '';
        $createSewer->machine_production_id = $data["machine_production_id"];
        $createSewer->width = (float) $data["width"];
        $createSewer->height = (float) $data["height"];
        $createSewer->date = Carbon::parse($data["date"])->format('Y-m-d');
        $createSewer->save();

        $createPivotSewer = new PivotSewer();
        $createPivotSewer->machine_production_id = $createSewer->machine_production_id;
        $createPivotSewer->sewer_production_id = $createSewer->id;
        $createPivotSewer->left_amount = 0;
        $createPivotSewer->amount = $leftAmount;
        $createPivotSewer->save();


        if ($createSewer && $createPivotSewer) {

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