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

class MachineProduction extends ComponentBase
{


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


    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;"> #' . ($machineProductions[$x]->id) . '</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>
                    </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;"> #' . $machineProductionsFiltered[$x]->id . '</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 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,
                    ));
            }

            $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++) {
                $html_data .= '<tr>
                        <td style="font-weight: bold;">' . ($x + 1) . '</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>
                    </tr>';
            }

            if ($createProductionMachine &&  $updateResult) {

                Flash::success("Hasabat Ustunlikli Goşuldy");
                return [
                    '#machine_datas' => $html_data,
                ];
            } else {
                Flash::error("Yalnyshlyk bar!!");
            }
        }
    }
}
