<?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 DB;
use Romanah\Gokbakja\Models\BagColor;
use Romanah\Gokbakja\Models\BagSize;
use Romanah\Gokbakja\Models\BagType;
use Romanah\Gokbakja\Models\Machine;
use Romanah\Gokbakja\Models\PivotSewer;

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::where("machine_production_id", $machinProdId)->with(["sewer_production", "machin_production"])->get();

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

        // var_dump(count($productions));

        if (count($productions) == 0) {
            $html_data = '';
        } {
            $html_data = '<div class="modal-header">
                            <h5 class="modal-title" id="mySmallModalLabel">#Rulon' . $machinProdId . ' Agramy: ' . $productions[0]->machin_production->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>';
        }



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

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

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

        $colors = BagColor::get();
        $types = BagType::get();
        $sizes = BagSize::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;">Enjam</label>
                                    <select class="form-control select2" name="machine_id">
                                        <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;">Sene</label>
                                    <input type="date" name="date" class="form-control" placeholder="Sene" value="'.($production->date != null ? Carbon::parse($production->date)->format('Y-m-d') : "").'">

                                </div>
                                <div class="col-md-12 mt-3">
                                    <label style="color: black;">Ölçeg</label>
                                    <select class="form-control select2" name="size_id">
                                        <option value="0">Ölçeg Saýla</option>';

                                        for ($x = 0; $x < count($sizes); $x++) {
                                            $html_data .='<option value="'.$sizes[$x]->id.'" '.($production->size_id == $sizes[$x]->id ? 'selected' : '').'>'.$sizes[$x]->name.'</option>';
                                        }

                                    $html_data .='</select>
                                </div>
                                <div class="col-md-12 mt-3">
                                    <label style="color: black;">Görnüşi</label>
                                    <select class="form-control select2" name="type_id">
                                        <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;">Reňki</label>
                                    <select class="form-control select2" name="color_id">
                                        <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" class="form-control"
                                        placeholder="Mukdar (kg)" value="'.$production->produced_weight.'">
                                </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.'">
                                </div>
                                <input type="hidden" name="production_id" value="'.$production->id.'">
                                <div class="col-md-12 mt-3">
                                    <button 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()
    {

        $html_data = '';

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

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

        $html_data = '';
        for ($x = 0; $x < count($machineProductions); $x++) {
            // 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><a href="#" style="font-weight: bold;">' . $machineProductions[$x]->building_name . '</a></td>
                        <td>' . $machineProductions[$x]->machine->name . '</td>
                        <td>' . $machineProductions[$x]->bag_size->name . '</td>
                        <td>' . $machineProductions[$x]->bag_type->name . '</td>
                        <td>' . ($machineProductions[$x]->color->name ?? "") . '</td>
                        <td><span class="badge badge-soft-success"
                                style="font-size: 14px;">' . number_format($machineProductions[$x]->produced_weight) . ' kg</span>
                        </td>
                        <td>' . $machineProductions[$x]->employee_name . '</td>
                        <td>' . $machineProductions[$x]->mechanic_name . '</td>
                        <td>' . $machineProductions[$x]->note . '</td>
                        <td> <a href="#" data-request="onSetFormUpdate" data-bs-toggle="modal" data-bs-target=".bs-example-modal-lg" data-request-data="machineProdId: ' . $machineProductions[$x]->id . '" style="font-weight: bold;color: darkred;"> ÜÝTGET </a> </td>
                    </tr>';
        }

        return  $html_data;
    }

    public function onReport()
    {

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

        $data = post();


        $machineProductions = ProductionMachineModel::select('id', 'is_finished', 'type_id', 'size_id', 'machine_id', 'produced_weight', 'employee_id', 'mechanic_id', 'note', 'date', 'color_id', 'building_name', 'employee_name', 'mechanic_name')
            ->with(['bag_type', 'bag_size', 'machine.building', 'employee', 'mechanic', 'color'])
            ->orderBy('id', 'DESC');

        $machineProductionsCalc = ProductionMachineModel::select('id', 'is_finished', 'type_id', 'size_id', 'machine_id', 'produced_weight', 'employee_id', 'mechanic_id', 'note', 'date', 'color_id', 'building_name', 'employee_name', 'mechanic_name')
            ->with(['bag_type', 'bag_size', 'machine.building', 'employee', 'mechanic', 'color'])
            ->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"];
        $size = $data["size_id"];
        $type = $data["type_id"];
        // $is_finished = $data["is_finished"];


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

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

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

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

        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->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();


        $finishedRulons = $machineProductionsCalc->where('is_finished', 1)->count();
        $leftAllRulons = (count($machineProductionsFiltered) - $finishedRulons);
        // $pivotSewersWorking = PivotSewer::select('id', 'status', 'machine_production_id')
        //     ->where('status', 'working')
        //     ->get()
        //     ->pluck('machine_production_id')
        //     ->toArray();






        $machineProductionsSum = $machineProductions->sum("produced_weight");
        $machineLeftProductionsSum = 0;
        $allSpent = 0;

        $html_data = '';

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




            if ($machineProductionsFiltered[$x]->date != null) {
                $dateFormat = $machineProductionsFiltered[$x]->date->format("d.m.Y");
            } else {
                $dateFormat = "";
            }

            $spent = '<span class="badge badge-soft-warning"
                   style="font-size: 14px;">' . number_format($machineProductionsFiltered[$x]->spentSum, 2) . ' kg</span>';

            $left = number_format(($machineProductionsFiltered[$x]->produced_weight - $machineProductionsFiltered[$x]->spentSum), 2);

            if ($left == 0) {
                $left = 'Gutardy';
            }

            $allSpent += $machineProductionsFiltered[$x]->spentSum;
            $machineLeftProductionsSum += ($machineProductionsFiltered[$x]->produced_weight - $machineProductionsFiltered[$x]->spentSum);

            $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"> #Rulon' . $machineProductionsFiltered[$x]->id . '</a></td>
                        <td><a href="#" style="font-weight: bold;">' . $dateFormat . '</a></td>
                        <td><a href="#" style="font-weight: bold;">' . $machineProductionsFiltered[$x]->building_name . '</a></td>
                        <td>' . $machineProductionsFiltered[$x]->machine->name . '</td>
                        <td>' . $machineProductionsFiltered[$x]->bag_size->name . '</td>
                        <td>' . $machineProductionsFiltered[$x]->bag_type->name . '</td>
                        <td><span class="badge badge-soft-primary"
                                style="font-size: 14px;">' . number_format($machineProductionsFiltered[$x]->produced_weight) . ' kg</span>
                        </td>
                        <td>
                            ' . $spent . '
                        </td>
                        <td><span class="badge badge-soft-success"
                                style="font-size: 14px;">' . $left . '</span>
                        </td>

                        <td>' . $machineProductionsFiltered[$x]->employee_name . '</td>
                        <td>' . $machineProductionsFiltered[$x]->mechanic_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) . '<br>Ulanylan Rulon: ' . $finishedRulons . '<br>Sklatdaky: ' . $leftAllRulons . '</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-primary 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> Sklatda: ' . number_format($machineLeftProductionsSum, 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> Ulanylan: ' . number_format($allSpent, 2) . ' kg</h5>
                                                </div>
                                            </div>
                                        </div>',
            ];
        } else {
            Flash::error("Yalnyshlyk bar!!");
        }
    }


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

        $updateProductionMachine = ProductionMachineModel::where("id", $data["production_id"])->first();
        $updateProductionMachine->type_id = $data["type_id"];
        $updateProductionMachine->size_id = $data["size_id"];
        $updateProductionMachine->machine_id = $data["machine_id"];
        $updateProductionMachine->color_id = $data["color_id"];
        $updateProductionMachine->produced_weight = $data["produced_weight"];
        $updateProductionMachine->note = $data["note"];
        $updateProductionMachine->date = Carbon::parse($data["date"])->format('Y-m-d');
        $updateProductionMachine->save();

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

    }

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

        $data = post();

        if (empty($data["produced_weight"]) || $data["type_id"] == 0 || $data["size_id"] == 0 || $data["machine_id"] == 0) {
            Flash::error("Gutulary Dolduryn!");
            return [
                '#validationq' => '  Gutulary Dolduryn!',
            ];
        } else {
            $createProductionMachine = new ProductionMachineModel();

            $createProductionMachine->type_id = $data["type_id"];
            $createProductionMachine->size_id = $data["size_id"];
            $createProductionMachine->machine_id = $data["machine_id"];
            $createProductionMachine->color_id = $data["color_id"];
            $createProductionMachine->produced_weight = $data["produced_weight"];
            $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(
                        'employee_id' => $productionMachine->machine->employee->id,
                        'mechanic_id' => $productionMachine->machine->mechanic->id,
                        'employee_name' => $productionMachine->machine->employee->name,
                        'mechanic_name' => $productionMachine->machine->mechanic->name,
                        '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();
            }
        }
    }
}
