<?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\Order as OrderModel;
use Romanah\Gokbakja\Models\OrderItem as OrderItemModel;
use Romanah\Gokbakja\Models\Shipping as ShippingModel;
use Romanah\Gokbakja\Models\ShippingTransport as ShippingTransportModel;
use Romanah\Gokbakja\Models\Payment as PaymentModel;
use Redirect;
use Carbon\Carbon;
use Flash;
use DB;

class Order extends ComponentBase
{


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

    public function onReportOrder()
    {

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

        $data = post();


        $orders = OrderModel::with(["client", "shipping"])
                        ->withCount(['order_items as order_all_amount' => function ($query) {
                            $query->select(DB::raw('sum(amount)'));
                        }])
                        ->withCount(['order_items as order_all_price' => function ($query) {
                            $query->select(DB::raw('sum(price) * sum(amount)'));
                        }])
                        ->withCount(['payment as all_payments' => function ($query) {
                            $query->select(DB::raw('sum(amount)'));
                        }])
                        ->orderBy('id', 'DESC');


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

        $client_id = $data["client_id"];
        $note = $data["note"];


        if ($client_id) {
            $orders->where("client_id", $client_id);
        }

        if ($note) {
            $orders->where("note", "like", "%" . $note . "%");
        }

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

        $ordersFiltered = $orders->get();


        $html_data = '';

        for ($x = 0; $x < count($ordersFiltered); $x++) {
            $status = '';

            $html_data .= '<tr>
                            <td style="font-weight: bold;">' . ($x + 1) . '</td>
                            <td><a href="/order-detail/' . $ordersFiltered[$x]->id . '" style="font-weight: bold;">Sargyt #' . $ordersFiltered[$x]->id . '</a></td>
                            <td><a href="/order-detail/' . $ordersFiltered[$x]->id . '" style="font-weight: bold;">' . $ordersFiltered[$x]->client->name . '</a></td>
                            <td>' . $ordersFiltered[$x]->client->country . '</td>
                            <td>' . number_format($ordersFiltered[$x]->order_all_amount) . ' kg</td>
                            <td><span class="badge badge-soft-primary"
                                    style="font-size: 14px;">' . number_format($ordersFiltered[$x]->order_all_price) . ' $</span>
                            </td>
                            <td><span class="badge badge-soft-success"
                                    style="font-size: 14px;">' . number_format($ordersFiltered[$x]->all_payments) . ' $</span>
                            </td>
                            <td><a href="#" class="badge badge-soft-danger" style="font-size: 14px;">' .  number_format($ordersFiltered[$x]->order_all_price - $ordersFiltered[$x]->all_payments) . ' $</a>
                            </td>
                            <td>' . $ordersFiltered[$x]->created_at->format('d.m.Y') . '</td>
                            <td>' . $ordersFiltered[$x]->note . '</td>

                        </tr>';
        }

        if ($ordersFiltered) {
            return [
                '#orders_report_datas' => $html_data,

            ];
        } else {
            Flash::error("Yalnyshlyk bar!!");
        }
    }

    public function onReportLogistics()
    {

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

        $data = post();


        $shippingTransports = ShippingTransportModel::with("shipping.order")->orderBy('shipping_id', 'DESC');

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

        $transport = $data["transport_type"];
        $place = $data["place_now"];
        $status = $data["status"];
        $transport_no = $data["transport_no"];


        if ($transport) {
            $shippingTransports->where("transport_type", $transport);
        }

        if ($place) {
            $shippingTransports->where("place_now", "like", "%" . $place . "%");
        }

        if ($transport_no) {
            $shippingTransports->where("transport_no", "like", "%" . $transport_no . "%");
        }

        if ($status) {
            $shippingTransports->where("status", $status);
        }

        // if ($start != $currentDateFormat){
        //     $shippingTransports->whereBetween('created_at', [$start, $end]);
        // }

        $shippingTransportsFiltered = $shippingTransports->get();
        $shippingTransportsAmountLoaded = $shippingTransports->sum("loaded_amount");


        $html_data = '';

        for ($x = 0; $x < count($shippingTransportsFiltered); $x++) {
            $status = '';

            if($shippingTransportsFiltered[$x]->status == "loaded"){
                $status = '<span class="badge badge-soft-info"
                style="font-size: 14px;">ÝÜKLENDI</span>';
            }

            if($shippingTransportsFiltered[$x]->status == "loading"){
                $status = '<span class="badge badge-soft-primary"
                style="font-size: 14px;">ÝÜKLENÝÄR</span>';
            }

            if($shippingTransportsFiltered[$x]->status == "complated"){
                $status = '<span class="badge badge-soft-success"
                style="font-size: 14px;">ÝERINE ÝETIRILDI</span>';
            }

            $html_data .= '<tr>
                        <td style="font-weight: bold;">' . ($x + 1) . '</td>
                        <td><a href="/order-detail/logistics/'.$shippingTransportsFiltered[$x]->shipping->order->id.'" style="font-weight: bold;">' . $shippingTransportsFiltered[$x]->transport_type . '</a></td>
                       <td>' . $shippingTransportsFiltered[$x]->transport_no . '</td>
                       <td><a href="/order-detail/'.$shippingTransportsFiltered[$x]->shipping->order->id.'" style="font-weight: bold;">Sargyt #'.$shippingTransportsFiltered[$x]->shipping->order->id.'</a></td>
                       <td>' . $shippingTransportsFiltered[$x]->place_now . '</td>
                        <td><span class="badge badge-soft-success"
                                style="font-size: 14px;">' . $shippingTransportsFiltered[$x]->loaded_amount . ' kg</span>
                        </td>
                        <td>' . $status . '</td>
                        <td>' . $shippingTransportsFiltered[$x]->note . '</td>
                    </tr>';
        }

        if ($shippingTransportsFiltered) {
            return [
                '#logistics_report_datas' => $html_data,
                '#all_amount' => ' <div class="col-md-6">
                                        <h3 class="card-title" style="font-size: 22px;color: #1e2038;">Logistika Boýunça Umumy</h3>
                                        <p class="card-title-desc" style="color: #6c6ff5;">Hasabat</p>
                                    </div>
                                    <div class="col-md-6">
                                        <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> Ýük Mukdary: ' . number_format($shippingTransportsAmountLoaded) . ' kg</h5>
                                            </div>
                                        </div>
                                    </div>',
            ];
        } else {
            Flash::error("Yalnyshlyk bar!!");
        }
    }

    public function onRender()
    {

        $html_data = '';

        $orderDatas = OrderModel::with(["client", "shipping"])
            ->withCount(['order_items as order_all_amount' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])
            ->withCount(['order_items as order_all_price' => function ($query) {
                $query->select(DB::raw('sum(price) * sum(amount)'));
            }])
            ->withCount(['payment as all_payments' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])
            ->orderBy('id', 'DESC')
            ->get();


        for ($x = 0; $x < count($orderDatas); $x++) {
            $html_data .= '<tr>
                                <td style="font-weight: bold;">' . ($x + 1) . '</td>
                                <td><a href="/order-detail/' . $orderDatas[$x]->id . '" style="font-weight: bold;">Sargyt #' . $orderDatas[$x]->id . '</a></td>
                                <td><a href="/order-detail/' . $orderDatas[$x]->id . '" style="font-weight: bold;">' . $orderDatas[$x]->client->name . '</a></td>
                                <td>' . $orderDatas[$x]->client->country . '</td>
                                <td>' . number_format($orderDatas[$x]->order_all_amount) . ' kg</td>
                                <td><span class="badge badge-soft-primary"
                                        style="font-size: 14px;">' . number_format($orderDatas[$x]->order_all_price) . ' $</span>
                                </td>
                                <td><span class="badge badge-soft-success"
                                        style="font-size: 14px;">' . number_format($orderDatas[$x]->all_payments) . ' $</span>
                                </td>
                                <td><a href="#" class="badge badge-soft-danger" style="font-size: 14px;">' .  number_format($orderDatas[$x]->order_all_price - $orderDatas[$x]->all_payments) . ' $</a>
                                </td>
                                <td>' . $orderDatas[$x]->created_at->format('d.m.Y') . '</td>
                                <td>' . $orderDatas[$x]->note . '</td>
                                <td><a href="#" data-request="onDeleteOrder" data-request-confirm="Sargyt #' . $orderDatas[$x]->id . ' pozmak isleýäňizmi?" data-request-data="orderId: ' . $orderDatas[$x]->id . '" style="color: darkred;font-weight: bold;">POZ</a></td>
                            </tr>';
        }


        return  $html_data;
    }

    public function onUpdatePaymentItem()
    {
        $data = post();
        $orderId = $this->param("orderId");


        $createPayment = PaymentModel::where("id", $data["payment_id"])->first();
        $createPayment->amount = $data["amount"];
        $createPayment->note = $data["note"];
        $createPayment->order_id = $orderId;
        $createPayment->save();

        $html_data = '';

        $paymentDatas = PaymentModel::where("order_id", $orderId)->orderBy('id', 'DESC')->get();

        for ($x = 0; $x < count($paymentDatas); $x++) {
            // dd($orderDatas[$x]->shipping->status);
            $html_data .= '<tr>
                                <td style="font-weight: bold;">' . ($x + 1) . '</td>
                                <td><a href="#" style="font-weight: bold;">' . $paymentDatas[$x]->amount . ' $</a></td>
                                <td><a href="#" style="font-weight: bold;">' . $paymentDatas[$x]->created_at->format('d.m.Y') . '</a></td>
                                <td>' . $paymentDatas[$x]->note . '</td>
                                <td><a href="#" data-request="onModalSetPayment"
                                    data-request-data="paymentId: ' . $paymentDatas[$x]->id . '"
                                    data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1" style="color: orange;"> Täzele </a></td>
                            </tr>';
        }

        $order = OrderModel::where("id", $orderId)->with(["client", "shipping"])
            ->withCount(['order_items as order_all_amount' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])
            ->withCount(['order_items as order_all_price' => function ($query) {
                $query->select(DB::raw('sum(price)'));
            }])
            ->first();

        $all = ($order->order_all_amount * $order->order_all_price);

        $allPaid = PaymentModel::where("order_id", $orderId)->sum("amount");
        $allNot = ($all - $allPaid);

        if ($createPayment) {

            Flash::success("Töleg Ustunlikli Goşuldy");
            return [
                '#payment_item_datas' => $html_data,
                '#allAmount' => $order->order_all_amount . " kg",
                '#allPrice' => $order->order_all_price . " $",
                '#all' => "Jemi Bahasy: " . number_format($all) . " $",
                '#all_payment' => "Jemi Tölenen Töleg: " . number_format($allPaid) . " $",
                '#all_not' => "Bergisi: " . number_format($allNot) . "$",
            ];
        } else {
            return Flash::error("Yalnyshlyk bar!!");
        }
        // }
    }

    public function onModalSetPayment()
    {

        $data = post();

        $paymentItem = PaymentModel::where("id", $data["paymentId"])->first();

        $html_data = '<div class="modal-header">
                            <h5 class="modal-title" id="mySmallModalLabel">Töleg Maglumatlaryny Üytegt</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form data-request="onUpdatePaymentItem" method="POST" data-request-flash>
                                <div class="row">


                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Mukdar ($)</label>
                                        <input type="number" name="amount" step="0.01" class="form-control"
                                            placeholder="Mukdar ($)" value="' . $paymentItem->amount . '">
                                    </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="' . $paymentItem->note . '">
                                    </div>
                                </div>

                                </div>
                                <input type="hidden" name="payment_id" value="' . $data["paymentId"] . '">
                                <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 onCreatePaymentItem()
    {
        $data = post();
        $orderId = $this->param("orderId");


        $createPayment = new PaymentModel();
        $createPayment->amount = $data["amount"];
        $createPayment->note = $data["note"];
        $createPayment->order_id = $orderId;
        $createPayment->save();

        $html_data = '';

        $paymentDatas = PaymentModel::where("order_id", $orderId)->orderBy('id', 'DESC')->get();

        for ($x = 0; $x < count($paymentDatas); $x++) {
            // dd($orderDatas[$x]->shipping->status);
            $html_data .= '<tr>
                                <td style="font-weight: bold;">' . ($x + 1) . '</td>
                                <td><a href="#" style="font-weight: bold;">' . $paymentDatas[$x]->amount . ' $</a></td>
                                <td><a href="#" style="font-weight: bold;">' . $paymentDatas[$x]->created_at->format('d.m.Y') . '</a></td>
                                <td>' . $paymentDatas[$x]->note . '</td>
                                <td><a href="#" data-request="onModalSetPayment"
                                    data-request-data="paymentId: ' . $paymentDatas[$x]->id . '"
                                    data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1" style="color: orange;"> Täzele </a></td>
                            </tr>';
        }

        $order = OrderModel::where("id", $orderId)->with(["client", "shipping"])
            ->withCount(['order_items as order_all_amount' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])
            ->withCount(['order_items as order_all_price' => function ($query) {
                $query->select(DB::raw('sum(price)'));
            }])
            ->first();

        $all = ($order->order_all_amount * $order->order_all_price);

        $allPaid = PaymentModel::where("order_id", $orderId)->sum("amount");
        $allNot = ($all - $allPaid);

        if ($createPayment) {

            Flash::success("Töleg Ustunlikli Goşuldy");
            return [
                '#payment_item_datas' => $html_data,
                '#allAmount' => $order->order_all_amount . " kg",
                '#allPrice' => $order->order_all_price . " $",
                '#all' => "Jemi Bahasy: " . number_format($all) . " $",
                '#all_payment' => "Jemi Tölenen Töleg: " . number_format($allPaid) . " $",
                '#all_not' => "Bergisi: " . number_format($allNot) . "$",
            ];
        } else {
            return Flash::error("Yalnyshlyk bar!!");
        }
        // }
    }

    public function onModalSetTransport()
    {

        $data = post();

        $transportItem = ShippingTransportModel::where("id", $data["transportId"])->first();

        $html_data = '<div class="modal-header">
                            <h5 class="modal-title" id="mySmallModalLabel">Transport Maglumatlaryny Üytegt</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form data-request="onUpdateTransportItem" method="POST" data-request-flash>
                                <div class="row">
                                <div class="col-md-12">
                                    <label class="form-label">Status Saýlaň</label>
                                    <select class="form-control select2" name="status">
                                        <option value="0">Saýla</option>

                                        <option value="loading" ' . ($transportItem->status == "loading" ? "selected" : "") . '>Ýüklenýär</option>
                                        <option value="loaded" ' . ($transportItem->status == "loaded" ? "selected" : "") . '>Ýüklendi</option>
                                        <option value="complated" ' . ($transportItem->status == "complated" ? "selected" : "") . '>Ýerine Ýetirildi</option>

                                    </select>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <label class="form-label">Transport Saýlaň</label>
                                    <select class="form-control select2" name="transport_type">
                                        <option value="0">Saýla</option>

                                        <option value="truck" ' . ($transportItem->transport_type == "truck" ? "selected" : "") . '>Tyr</option>
                                        <option value="train" ' . ($transportItem->transport_type == "train" ? "selected" : "") . '>Wagon</option>

                                    </select>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Ýüklenen Mukdar (kg)</label>
                                        <input type="number" name="loaded_amount" step="0.01" class="form-control"
                                            placeholder="Ýüklenen Mukdar (kg)" value="' . $transportItem->loaded_amount . '">
                                    </div>
                                </div>

                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Şu wagty ýeri</label>
                                        <input type="text" name="place_now" class="form-control"
                                            placeholder="Şu wagty ýeri" value="' . $transportItem->place_now . '">
                                    </div>
                                </div>
                                <div class="col-md-12 mt-3">
                                    <div>
                                        <label class="form-label">Transport No</label>
                                        <input type="text" name="transport_no" class="form-control"
                                            placeholder="Transport No" value="' . $transportItem->transport_no . '">
                                    </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="' . $transportItem->note . '">
                                    </div>
                                </div>

                                </div>
                                <input type="hidden" name="transport_id" value="' . $data["transportId"] . '">
                                <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 onUpdateTransportItem()
    {
        $data = post();
        $orderId = $this->param("orderId");

        $orderq = OrderModel::where("id", $orderId)
            ->withCount(['order_items as order_all_amount' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])->first();

        $transportAmountSum = ShippingTransportModel::where("shipping_id", $orderq->shipping_id)->sum('loaded_amount');

        $allLoadedAmount = $transportAmountSum + $data["loaded_amount"];

        // dd($allLoadedAmount);
        // if ($orderq->order_all_amount < $allLoadedAmount) {
        //     Flash::error("Yuklenen mukdar jemi edilen sargytdan uly");
        // } else {
        $createShippingTransport = ShippingTransportModel::where("id", $data["transport_id"])->first();

        $createShippingTransport->transport_type = $data["transport_type"];
        $createShippingTransport->place_now = $data["place_now"];
        $createShippingTransport->loaded_amount = $data["loaded_amount"];
        $createShippingTransport->transport_no = $data["transport_no"];
        $createShippingTransport->status = $data["status"];
        $createShippingTransport->note = $data["note"];
        $createShippingTransport->shipping_id = $orderq->shipping_id;
        $createShippingTransport->save();

        $html_data = '';

        $transportDatas = ShippingTransportModel::where("shipping_id", $orderq->shipping_id)->orderBy('id', 'DESC')->get();

        for ($x = 0; $x < count($transportDatas); $x++) {
            // dd($orderDatas[$x]->shipping->status);
            $html_data .= '<tr>
                                <td style="font-weight: bold;">' . ($x + 1) . '</td>
                                <td><a href="#" style="font-weight: bold;">' . $transportDatas[$x]->transport_type . '</a></td>
                                <td>' . $transportDatas[$x]->place_now . '</td>
                                <td>' . $transportDatas[$x]->loaded_amount . ' kg</td>
                                <td>' . $transportDatas[$x]->transport_no . '</td>
                                <td>' . $transportDatas[$x]->note . '</td>
                                <td><a href="#" data-request="onModalSetTransport"
                                data-request-data="transportId: ' . $transportDatas[$x]->id . '"
                                data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1" style="color: orange;"> Täzele </a></td>
                            </tr>';
        }

        $order = OrderModel::where("id", $orderId)->with(["client", "shipping"])
            ->withCount(['order_items as order_all_amount' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])
            ->withCount(['order_items as order_all_price' => function ($query) {
                $query->select(DB::raw('sum(price)'));
            }])
            ->first();

        $all = ($order->order_all_amount * $order->order_all_price);

        $allLoaded = ShippingTransportModel::where("shipping_id", $orderq->shipping_id)->sum("loaded_amount");

        if ($createShippingTransport) {

            Flash::success("Transport Ustunlikli Goşuldy");
            return [
                '#transport_item_datas' => $html_data,
                '#allAmount' => $order->order_all_amount . " kg",
                '#allPrice' => $order->order_all_price . " $",
                '#all' => "Jemi Bahasy: " . number_format($all) . " $",
                '#all_loaded' => "Jemi Ýüklenen Ýük: " . number_format($allLoaded) . " kg",
            ];
        } else {
            return Flash::error("Yalnyshlyk bar!!");
        }
        // }
    }


    public function onCreateTransportItem()
    {
        $data = post();
        $orderId = $this->param("orderId");

        $orderq = OrderModel::where("id", $orderId)
            ->withCount(['order_items as order_all_amount' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])->first();

        $transportAmountSum = ShippingTransportModel::where("shipping_id", $orderq->shipping_id)->sum('loaded_amount');

        $allLoadedAmount = $transportAmountSum + $data["loaded_amount"];

        // dd($allLoadedAmount);
        // if ($orderq->order_all_amount < $allLoadedAmount) {
        //     Flash::error("Yuklenen mukdar jemi edilen sargytdan uly");
        // } else {
        $createShippingTransport = new ShippingTransportModel();
        $createShippingTransport->transport_type = $data["transport_type"];
        $createShippingTransport->place_now = "Aşgabat";
        $createShippingTransport->loaded_amount = $data["loaded_amount"];
        $createShippingTransport->transport_no = $data["transport_no"];
        $createShippingTransport->note = $data["note"];
        $createShippingTransport->shipping_id = $orderq->shipping_id;
        $createShippingTransport->save();

        $html_data = '';

        $transportDatas = ShippingTransportModel::where("shipping_id", $orderq->shipping_id)->orderBy('id', 'DESC')->get();

        for ($x = 0; $x < count($transportDatas); $x++) {
            // dd($orderDatas[$x]->shipping->status);
            $html_data .= '<tr>
                                <td style="font-weight: bold;">' . ($x + 1) . '</td>
                                <td><a href="#" style="font-weight: bold;">' . $transportDatas[$x]->transport_type . '</a></td>
                                <td>' . $transportDatas[$x]->place_now . '</td>
                                <td>' . $transportDatas[$x]->loaded_amount . ' kg</td>
                                <td>' . $transportDatas[$x]->transport_no . '</td>
                                <td>' . $transportDatas[$x]->note . '</td>
                                <td><a href="#" data-request="onModalSetTransport"
                                data-request-data="transportId: ' . $transportDatas[$x]->id . '"
                                data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1" style="color: orange;"> Täzele </a></td>
                            </tr>';
        }

        $order = OrderModel::where("id", $orderId)->with(["client", "shipping"])
            ->withCount(['order_items as order_all_amount' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])
            ->withCount(['order_items as order_all_price' => function ($query) {
                $query->select(DB::raw('sum(price)'));
            }])
            ->first();

        $all = ($order->order_all_amount * $order->order_all_price);

        $allLoaded = ShippingTransportModel::where("shipping_id", $orderq->shipping_id)->sum("loaded_amount");

        if ($createShippingTransport) {

            Flash::success("Transport Ustunlikli Goşuldy");
            return [
                '#transport_item_datas' => $html_data,
                '#allAmount' => $order->order_all_amount . " kg",
                '#allPrice' => $order->order_all_price . " $",
                '#all' => "Jemi Bahasy: " . number_format($all) . " $",
                '#all_loaded' => "Jemi Ýüklenen Ýük: " . number_format($allLoaded) . " kg",
            ];
        } else {
            return Flash::error("Yalnyshlyk bar!!");
        }
        // }
    }

    // data-request="onModalSet" data-request-data="orderId: '.$orderDatas[$x]->id.', header: \''.$orderDatas[$x]->client->name.'\'" data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1"

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

        $order = OrderModel::where("id", $data["orderId"])->delete();

        $html_data = '';

        $orderDatas = OrderModel::with(["client", "shipping"])
            ->withCount(['order_items as order_all_amount' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])
            ->withCount(['order_items as order_all_price' => function ($query) {
                $query->select(DB::raw('sum(price)'));
            }])
            ->orderBy('id', 'DESC')
            ->get();


        for ($x = 0; $x < count($orderDatas); $x++) {
            $html_data .= '<tr>
                                <td style="font-weight: bold;">' . ($x + 1) . '</td>
                                <td><a href="/order-detail/' . $orderDatas[$x]->id . '" style="font-weight: bold;">Sargyt #' . $orderDatas[$x]->id . '</a></td>
                                <td><a href="/order-detail/' . $orderDatas[$x]->id . '" style="font-weight: bold;">' . $orderDatas[$x]->client->name . '</a></td>
                                <td>' . $orderDatas[$x]->client->country . '</td>
                                <td>' . number_format($orderDatas[$x]->order_all_amount) . ' kg</td>
                                <td><span class="badge badge-soft-primary"
                                        style="font-size: 14px;">' . number_format($orderDatas[$x]->order_all_price) . ' $</span>
                                </td>
                                <td><span class="badge badge-soft-success"
                                        style="font-size: 14px;">' . number_format($orderDatas[$x]->all_payments) . ' $</span>
                                </td>
                                <td><a href="#" class="badge badge-soft-danger" style="font-size: 14px;">' .  number_format($orderDatas[$x]->order_all_price - $orderDatas[$x]->all_payments) . ' $</a>
                                </td>
                                <td>' . $orderDatas[$x]->created_at->format('d.m.Y') . '</td>
                                <td>' . $orderDatas[$x]->note . '</td>
                                <td><a href="#" data-request="onDeleteOrder" data-request-confirm="Sargyt #' . $orderDatas[$x]->id . ' pozmak isleýäňizmi?" data-request-data="orderId: ' . $orderDatas[$x]->id . '" style="color: darkred;font-weight: bold;">POZ</a></td>
                            </tr>';
        }

        if ($order) {

            Flash::success("Sargyt Ustunlikli Pozuldy");
            return [
                '#order_datas' => $html_data,
            ];
        } else {
            return Flash::error("Yalnyshlyk bar!!");
        }
    }

    public function onModalSet()
    {

        $data = post();

        $orderItem = OrderItemModel::where("id", $data["orderItemId"])->first();

        $html_data = '<div class="modal-header">
                            <h5 class="modal-title" id="mySmallModalLabel">Sargyt Haryt Bahasy</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form data-request="onUpdateOrderItemPrice" method="POST" data-request-flash>
                                <input type="number" step="0.01" pattern="/^-?\d+\.?\d*$/"
                                    onKeyPress="if(this.value.length==4) return false;"
                                    name="price" class="form-control"
                                    placeholder="%"
                                    value="' . $orderItem->price . '">
                                <input type="hidden" name="id" value="' . $data["orderItemId"] . '">
                                <button type="submit"
                                    class="btn btn-primary waves-effect waves-light"
                                    data-bs-dismiss="modal"
                                    style="margin-top: 15px;width: 100%;">Üýtget</button>
                            </form>
                        </div>';

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

    public function onModalSetAmount()
    {

        $data = post();

        $orderItem = OrderItemModel::where("id", $data["orderItemId"])->first();

        $html_data = '<div class="modal-header">
                            <h5 class="modal-title" id="mySmallModalLabel">Sargyt Mukdary</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form data-request="onUpdateOrderItemAmount" method="POST" data-request-flash>
                                <input type="number" step="0.01" pattern="/^-?\d+\.?\d*$/"
                                    onKeyPress="if(this.value.length==4) return false;"
                                    name="amount" class="form-control"
                                    placeholder=""
                                    value="' . $orderItem->amount . '">
                                <input type="hidden" name="id" value="' . $data["orderItemId"] . '">
                                <button type="submit"
                                    class="btn btn-primary waves-effect waves-light"
                                    data-bs-dismiss="modal"
                                    style="margin-top: 15px;width: 100%;">Üýtget</button>
                            </form>
                        </div>';

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

    public function onUpdateOrderItemAmount()
    {
        // $this["currentMonth"] = $currentDate->format('m');
        $data = post();

        $orderItem = OrderItemModel::where("id", $data["id"])->first();

        $orderItem->amount = (float) $data["amount"];
        $orderItem->save();



        $html_data = '';

        $orderDatas = OrderItemModel::with(["type", "size"])->where("order_id", $orderItem->order_id)->orderBy('id', 'DESC')->get();

        for ($x = 0; $x < count($orderDatas); $x++) {
            // dd($orderDatas[$x]->shipping->status);
            $html_data .= '<tr>
                                <td style="font-weight: bold;">' . ($x + 1) . '</td>
                                <td><a href="#" style="font-weight: bold;">' . $orderDatas[$x]->type->name . '</a></td>
                                <td>' . $orderDatas[$x]->size->name . '</td>
                                <td><a href="#" data-request="onModalSet"
                                data-request-data="orderItemId: ' . $orderDatas[$x]->id . '"
                                data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1"
                                class="badge badge-soft-success"
                                style="font-size: 14px;">' . number_format($orderDatas[$x]->price) . ' $</a>
                                </td>
                                <td><a href="#" data-request="onModalSetAmount"
                                data-request-data="orderItemId: ' . $orderDatas[$x]->id . '"
                                data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1">' . $orderDatas[$x]->amount . '</a></td>
                                <td>' . $orderDatas[$x]->note . '</td>
                            </tr>';
        }

        $order = OrderModel::where("id", $orderItem->order_id)->with(["client", "shipping"])
            ->withCount(['order_items as order_all_amount' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])
            ->withCount(['order_items as order_all_price' => function ($query) {
                $query->select(DB::raw('sum(price)'));
            }])
            ->first();

        $all = ($order->order_all_amount * $order->order_all_price);

        if ($orderItem) {

            Flash::success("Sargyt Harydy Ustunlikli Goşuldy");
            return [
                '#order_item_datas' => $html_data,
                '#allAmount' => $order->order_all_amount . " kg",
                '#allPrice' => $order->order_all_price . " $",
                '#all' => "Jemi Bahasy: " . number_format($all) . " $",
            ];
        } else {
            return Flash::error("Yalnyshlyk bar!!");
        }
    }

    public function onUpdateOrderItemPrice()
    {
        // $this["currentMonth"] = $currentDate->format('m');
        $data = post();

        $orderItem = OrderItemModel::where("id", $data["id"])->first();

        $orderItem->price = (float) $data["price"];
        $orderItem->save();



        $html_data = '';

        $orderDatas = OrderItemModel::with(["type", "size"])->where("order_id", $orderItem->order_id)->orderBy('id', 'DESC')->get();

        for ($x = 0; $x < count($orderDatas); $x++) {
            // dd($orderDatas[$x]->shipping->status);
            $html_data .= '<tr>
                                <td style="font-weight: bold;">' . ($x + 1) . '</td>
                                <td><a href="#" style="font-weight: bold;">' . $orderDatas[$x]->type->name . '</a></td>
                                <td>' . $orderDatas[$x]->size->name . '</td>
                                <td><a href="#" data-request="onModalSet"
                                data-request-data="orderItemId: ' . $orderDatas[$x]->id . '"
                                data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1"
                                class="badge badge-soft-success"
                                style="font-size: 14px;">' . number_format($orderDatas[$x]->price) . ' $</a>
                                </td>
                                <td><a href="#" data-request="onModalSetAmount"
                                data-request-data="orderItemId: ' . $orderDatas[$x]->id . '"
                                data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1">' . $orderDatas[$x]->amount . '</a></td>
                                <td>' . $orderDatas[$x]->note . '</td>
                            </tr>';
        }

        $order = OrderModel::where("id", $orderItem->order_id)->with(["client", "shipping"])
            ->withCount(['order_items as order_all_amount' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])
            ->withCount(['order_items as order_all_price' => function ($query) {
                $query->select(DB::raw('sum(price)'));
            }])
            ->first();

        $all = ($order->order_all_amount * $order->order_all_price);

        if ($orderItem) {

            Flash::success("Sargyt Harydy Ustunlikli Goşuldy");
            return [
                '#order_item_datas' => $html_data,
                '#allAmount' => $order->order_all_amount . " kg",
                '#allPrice' => $order->order_all_price . " $",
                '#all' => "Jemi Bahasy: " . number_format($all) . " $",
            ];
        } else {
            return Flash::error("Yalnyshlyk bar!!");
        }
    }

    public function onCreateOrderItem()
    {
        $data = post();
        $orderId = $this->param("orderId");


        $createOrderItem = new OrderItemModel();
        $createOrderItem->amount = $data["amount"];
        $createOrderItem->order_id = $orderId;
        $createOrderItem->type_id = $data["type_id"];
        $createOrderItem->size_id = $data["size_id"];
        $createOrderItem->price = $data["price"];
        $createOrderItem->note = $data["note"];
        $createOrderItem->save();

        $html_data = '';

        $orderDatas = OrderItemModel::with(["type", "size"])->where("order_id", $orderId)->orderBy('id', 'DESC')->get();

        for ($x = 0; $x < count($orderDatas); $x++) {
            // dd($orderDatas[$x]->shipping->status);
            $html_data .= '<tr>
                                <td style="font-weight: bold;">' . ($x + 1) . '</td>
                                <td><a href="#" style="font-weight: bold;">' . $orderDatas[$x]->type->name . '</a></td>
                                <td>' . $orderDatas[$x]->size->name . '</td>
                                <td><a href="#" data-request="onModalSet"
                                data-request-data="orderItemId: ' . $orderDatas[$x]->id . '"
                                data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1"
                                class="badge badge-soft-success"
                                style="font-size: 14px;">' . number_format($orderDatas[$x]->price) . ' $</a>
                                </td>
                                <td><a href="#" data-request="onModalSetAmount"
                                data-request-data="orderItemId: ' . $orderDatas[$x]->id . '"
                                data-bs-toggle="modal" data-bs-target=".bs-example-modal-sm-1">' . $orderDatas[$x]->amount . '</a></td>
                                <td>' . $orderDatas[$x]->note . '</td>
                            </tr>';
        }

        $order = OrderModel::where("id", $orderId)->with(["client", "shipping"])
            ->withCount(['order_items as order_all_amount' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])
            ->withCount(['order_items as order_all_price' => function ($query) {
                $query->select(DB::raw('sum(price)'));
            }])
            ->first();

        $all = ($order->order_all_amount * $order->order_all_price);

        if ($createOrderItem) {

            Flash::success("Sargyt Harydy Ustunlikli Goşuldy");
            return [
                '#order_item_datas' => $html_data,
                '#allAmount' => $order->order_all_amount . " kg",
                '#allPrice' => $order->order_all_price . " $",
                '#all' => "Jemi Bahasy: " . number_format($all) . " $",
            ];
        } else {
            return Flash::error("Yalnyshlyk bar!!");
        }
    }


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

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

        $data = post();




        $createOrder = new OrderModel();
        $createOrder->client_id = $data["client_id"];
        $createOrder->note = $data["note"];
        $createOrder->shipping_id = 0;
        $createOrder->save();

        $createShipping = new ShippingModel();
        $createShipping->order_id = $createOrder->id;
        $createShipping->status = 'not_loaded';
        $createShipping->employee_id = 0;
        $createShipping->place_now = "Aşgabat";
        $createShipping->loaded_amount = 0;
        $createShipping->note = "";
        $createShipping->save();


        $createOrder->shipping_id = $createShipping->id;
        $createOrder->save();

        $html_data = '';

        $orderDatas = OrderModel::with(["client", "shipping"])
            ->withCount(['order_items as order_all_amount' => function ($query) {
                $query->select(DB::raw('sum(amount)'));
            }])
            ->withCount(['order_items as order_all_price' => function ($query) {
                $query->select(DB::raw('sum(price)'));
            }])
            ->orderBy('id', 'DESC')
            ->get();


        for ($x = 0; $x < count($orderDatas); $x++) {
            $html_data .= '<tr>
                                <td style="font-weight: bold;">' . ($x + 1) . '</td>
                                <td><a href="/order-detail/' . $orderDatas[$x]->id . '" style="font-weight: bold;">Sargyt #' . $orderDatas[$x]->id . '</a></td>
                                <td><a href="/order-detail/' . $orderDatas[$x]->id . '" style="font-weight: bold;">' . $orderDatas[$x]->client->name . '</a></td>
                                <td>' . $orderDatas[$x]->client->country . '</td>
                                <td>' . number_format($orderDatas[$x]->order_all_amount) . ' kg</td>
                                <td><span class="badge badge-soft-primary"
                                        style="font-size: 14px;">' . number_format($orderDatas[$x]->order_all_price) . ' $</span>
                                </td>
                                <td><span class="badge badge-soft-success"
                                        style="font-size: 14px;">' . number_format($orderDatas[$x]->all_payments) . ' $</span>
                                </td>
                                <td><a href="#" class="badge badge-soft-danger" style="font-size: 14px;">' .  number_format($orderDatas[$x]->order_all_price - $orderDatas[$x]->all_payments) . ' $</a>
                                </td>
                                <td>' . $orderDatas[$x]->created_at->format('d.m.Y') . '</td>
                                <td>' . $orderDatas[$x]->note . '</td>
                                <td><a href="#" data-request="onDeleteOrder" data-request-confirm="Sargyt #' . $orderDatas[$x]->id . ' pozmak isleýäňizmi?" data-request-data="orderId: ' . $orderDatas[$x]->id . '" style="color: darkred;font-weight: bold;">POZ</a></td>
                            </tr>';
        }

        if ($createOrder) {

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