Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
36 kB
1
Indexable
Never
<?php

namespace App\Http\Controllers\CMS;

use App\Http\Controllers\Controller;
use App\Jobs\AdminNotificationSenderJob;
use App\Jobs\NotificationSenderJob;
use App\Models\Addon;
use App\Models\Address;
use App\Models\AppUser;
use App\Models\Discount;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\OrderStatus;
use App\Models\ServiceItem;
use App\Models\SmsValidation;
use App\Models\StaticInfo;
use App\Models\Status;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Mike42\Escpos\PrintConnectors\NetworkPrintConnector;
use Mike42\Escpos\Printer;
use PDF;

class PosController extends Controller
{
    public function getCategoryItems($category_id = null){
        return response()->json([
            'category_items'=>ServiceItem::where('category_id', $category_id)->get()
        ]);
    }

    public function openOrder(Request $request, $order_id = null)
    {
        if ($order_id == null){
            $modal_items =ServiceItem::query()->get();
            return view('cms.pos.index',compact('modal_items'));
        }
        else {
            $order = Order::query()->find($order_id);

            $request->request->add(['user_prices'=> $order->user->prices??null]);
            $modal_items =ServiceItem::query()->get();
            return view('cms.pos.index', compact('order','modal_items'));
        }
    }

    public function getUser($phone)
    {
        return response()->json([
            'user' => AppUser::query()->where('phone', str_replace(" ", "", $phone))->first()
        ]);
    }


    public function store(Request $request)
    {

        $params = $request->all();
        $expressOrder = key_exists('express_order', $params) && $params['express_order'] == "on";
        $sameAddress = key_exists('same_address', $params) && $params['same_address'] == "on";
        $collectionDate = Carbon::parse($params['collection_date']);
        $deliveryDate = Carbon::parse($params['delivery_date']);
        $checkPhone = AppUser::query()->where('phone')->count();
        if ($checkPhone > 0)
            return response()->json(['message' => 'Phone already exists.'], 500);
        if ($collectionDate->isBefore(Carbon::now()))
            return response()->json(['message' => 'Collection date cannot be in past.'], 500);


        if (!key_exists('user_id', $params) || $params['user_id'] == '') {
            $ch = AppUser::query()
                ->where('phone', str_replace(" ", "", $params['phone']))
                ->first();
            if ($ch == null) {
                $appUser = new AppUser();
                $appUser->email = $params['email'];
                $appUser->name = $params['name'];
                $appUser->alias_name = $params['alias_name'];
                $appUser->user_note = $params['user_note'];
                $appUser->phone = str_replace(" ", "", $params['phone']);
                $appUser->save();
            }else{
                $appUser = $ch;
            }

        } else {
            $appUser = AppUser::query()->find($params['user_id']);
            if ($appUser == null)
                return response()->json(['message' => 'user not found'], 500);
        }
        $collectionAddress = json_decode($params['collection_address'], true);
        if ($collectionAddress == null)
            return response()->json(['message' => 'error in pickup address'], 500);
        $collectionAddress['coordinates'] = explode(',', $collectionAddress['coordinates']);
        $deliveryAddress = null;
        if (!$sameAddress)
            $deliveryAddress = json_decode($params['delivery_address'], true);

        if ($deliveryAddress == null && !$sameAddress)
            return response()->json(['message' => 'error in delivery address'], 500);

        if (key_exists('_id', $collectionAddress)) {
            $userCollectionAddress = $appUser->addresses()->find($collectionAddress['_id']);
        } else {
            if ($collectionAddress['name'] != 'Atlantis') {
                $userCollectionAddress = new Address();
                foreach ($collectionAddress as $k => $v) {
                    $userCollectionAddress->$k = $v;
                }
                $appUser->addresses()->save($userCollectionAddress);
            } else {
                $userCollectionAddress = $collectionAddress;
            }
        }
        if ($sameAddress || $deliveryAddress == null)
            $userDeliverAddress = $userCollectionAddress;
        else {
            if (key_exists('_id', $deliveryAddress)) {
                $userDeliverAddress = $appUser->addresses()->find($deliveryAddress['_id']);
            } else {
                if ($deliveryAddress['name'] != 'Atlantis') {
                    $userDeliverAddress = new Address();
                    foreach ($deliveryAddress as $k => $v) {
                        $userDeliverAddress->$k = $v;
                    }
                    $userDeliverAddress =
                        $appUser->addresses()->save($userDeliverAddress);
                } else {
                    $userDeliverAddress = $deliveryAddress;
                }

            }
        }

        $sub_total = 0;
        $discount = 0;
        $addons = 0;
        $total = 0;
        $orderDetailsList = [];
        if ($request->input('order_details') != null) {
            $orderD = json_decode($request->input('order_details'), true);
            foreach ($orderD as $obItem) {
                $od = new OrderDetail();
                $od->quantity = (int)$obItem['quantity'];
                $od->discount = $obItem['discount'];
                $od->price = floatval($obItem['price']);

                $od->item_type = $obItem['item_type'];
                $od->addons = $obItem['addons'];
                $od->item = $obItem['item'];
                $od->sub_total = $obItem['sub_total'];
                $od->discount_total = $obItem['discount_total'];
                $od->addons_total = $obItem['addons_total'];
                $od->total = $obItem['sub_total'] + $obItem['addons_total'] - $obItem['discount_total'];
                $od->express_order = $obItem['express_order'];
                $od->item_note = $obItem['item_note'];
                $this->saveImagesAndNotes($od, $obItem['note'] ?? null, $obItem['images'] ?? []);

                $sub_total += $od->sub_total;
                $discount += $od->discount_total;
                $addons += $od->addons_total;
                $total += $od->total;

                $orderDetailsList[] = $od;
            }
        }


        $new = Status::query()->where('slug_name', 'new')->first();
        $orderStatus = new OrderStatus();
        $orderStatus->user_id = auth()->user()->_id;
        $orderStatus->status_id = $new->_id;
        $order = new Order();
        $order->user_id = $appUser->_id;
        $order->code = generateRandomString(8, 2);
        $order->collection_date = $collectionDate->toDateTimeString();
        $order->delivery_date = $deliveryDate->toDateTimeString();
        $order->express_order = $expressOrder;
        $order->total = $total;
        $order->source = $request->input('source');
        $order->sub_total = $sub_total;
        $order->discount = $discount;
        $order->addons = $addons;
        $order->delivery_note = @$params['delivery_note'];
        $order->collection_note = @$params['collection_note'];
        $order->collection_address = is_array($userCollectionAddress) ? $userCollectionAddress : $userCollectionAddress->toArray();
        $order->delivery_address = is_array($userDeliverAddress) ? $userDeliverAddress : $userDeliverAddress->toArray();
        $order->status_id = $orderStatus->status_id;
        $order->save();
        $order->orderDetails()->saveMany($orderDetailsList);
        $order->statuses()->save($orderStatus);
        if( $appUser->discount != null ){
            $order->discount_percentage = $appUser->discount;
            $user_discount = floatval(number_format((($sub_total + $addons) * $appUser->discount / 100), 2, '.', ''));
            $order->discount = $user_discount;
            $order->save();
        }
        if ($request->input('action') == 'collection') {
            $collection = Status::query()->where('slug_name', 'collection')->first();
            $orderStatus = new OrderStatus();
            $orderStatus->user_id = auth()->user()->_id;
            $orderStatus->status_id = $collection->_id;
            $order->statuses()->save($orderStatus);

            $collection = Status::query()->where('slug_name', 'validation')->first();
            $orderStatus = new OrderStatus();
            $orderStatus->user_id = auth()->user()->_id;
            $orderStatus->status_id = $collection->_id;
            $order->statuses()->save($orderStatus);

            $collection = Status::query()->where('slug_name', 'processing')->first();
            $orderStatus = new OrderStatus();
            $orderStatus->user_id = auth()->user()->_id;
            $orderStatus->status_id = $collection->_id;
            $order->status_id = $collection->_id;
            $order->save();
            $order->statuses()->save($orderStatus);
            $order->putItemsInZones();
            $this->checkInvoiceNumbers();
            if ( $request->has('payment_type') ){
                $order->paid_amount = $order->total;
                if ($request->input('payment_type') =='credit')
                    $order->paid_amount = 0;


                $order->payment_type = $request->input('payment_type');
                $order->payment_status = 'paid';
                if ( $request->input('payment_type') == 'card')
                    $order->pos_device = auth()->user()->pos_device ?? '';
                $order->save();
            }

        }

        try {
            dispatch(new AdminNotificationSenderJob("New Order from " .
                $order->user->name . " with code:#" . $order->code));
        } catch (\Exception $e) {

        }

        return response()->json(['order' => $order], 200);

    }


    public function update(Request $request, $id)
    {

        $params = $request->all();

        $order = Order::query()->findOrFail($id);
        $action = $request->input('action', 'update');
        $appUser = $order->user;
        $appUser->alias_name = $params['alias_name'];
        $appUser->user_note = $params['user_note'];
        $appUser->save();


        if ($action == 'force_delete') {
            $order->forceDelete();
            return response()->json(['message' => 'success']);
        }

        if ($action == 'cancel') {
            if (!in_array($order->status->slug_name, ['processing', 'delivery'])) {
                $cancel = Status::query()->where('slug_name', 'canceled')->first();
                $orderStatus = new OrderStatus();
                $orderStatus->user_id = auth()->user()->_id;
                $orderStatus->status_id = $cancel->_id;
                $order->status_id = $orderStatus->status_id;
                $order->save();
                $order->statuses()->save($orderStatus);

                dispatch(new NotificationSenderJob('order-canceled', $order->_id));

                return response()->json(['message' => 'success']);
            } else {
                return response()->json(['message' => 'Order status not  allowing to cancel the order.'], 500);

            }

        }
        else if ($action == 'accept') {
            $processing = Status::query()->where('slug_name', 'processing')->first();
            $orderStatus = new OrderStatus();
            $orderStatus->user_id = auth()->user()->_id;
            $orderStatus->status_id = $processing->_id;
            $order->status_id = $orderStatus->status_id;
            $order->save();
            $order->statuses()->save($orderStatus);
            $order->putItemsInZones();

            if ( $order->user->is_special_member){
                //nothing
            }else{
                $infos = StaticInfo::query()->first();
                if ($infos != null && $infos->delivery_fees != '' && $infos->delivery_fees != null) {
                    if ($order->total > 0 && $infos->delivery_free_min != null &&
                        $order->total < $infos->delivery_free_min) {
                        if ($order->delivery_charge > 0) {
                            $old_delivery = $order->delivery_charge;
                            $order->delivery_charge = $infos->delivery_fees;
                            $total = $order->total;
                            $total += ($infos->delivery_fees - $old_delivery);
                            $order->total = $total;
                        } else {
                            $order->delivery_charge = $infos->delivery_fees;
                            $total = $order->total;
                            $total += $infos->delivery_fees;
                            $order->total = $total;
                        }

                    } else {
                        if ($order->delivery_charge > 0) {
                            $old_delivery = $order->delivery_charge;
                            $order->delivery_charge = 0;
                            $total = $order->total;
                            $total -= $old_delivery;
                            $order->total = $total;
                        } else {
                            $order->delivery_charge = 0;
                        }

                    }
            }

                $order->save();
            }

            $this->checkInvoiceNumbers();
            dispatch(new NotificationSenderJob('request-payment',$order->_id,true, true));

            return response()->json(['message' => 'success']);

        }

        else if ($action == 'back_to_shop') {
            $processing = Status::query()->where('slug_name', 'processing')->first();
            $orderStatus = new OrderStatus();
            $orderStatus->user_id = auth()->user()->_id;
            $orderStatus->status_id = $processing->_id;
            $order->status_id = $orderStatus->status_id;
            $order->save();
            $order->statuses()->save($orderStatus);
            $order->putItemsInZones();

            return response()->json(['message' => 'success']);
        }

        else if ($action == 'deliver') {
            $delivery = Status::query()->where('slug_name', 'delivery')->first();
            $done = Status::query()->where('slug_name', 'done')->first();

            $orderStatus = new OrderStatus();
            $orderStatus->user_id = auth()->user()->_id;
            $order->delivered_by = auth()->user()->_id;
            $orderStatus->status_id = $delivery->_id;
            $order->status_id = $orderStatus->status_id;
            $order->statuses()->save($orderStatus);
            $orderStatus = new OrderStatus();
            $orderStatus->user_id = auth()->user()->_id;
            $order->delivered_by = auth()->user()->_id;
            $orderStatus->status_id = $done->_id;
            $order->status_id = $orderStatus->status_id;
            $order->statuses()->save($orderStatus);
//            if (!in_array($order->user->is_business_account, ["true", true])) {
            $order->paid_amount = $order->total;
            if ($request->input('payment_type') =='credit')
                $order->paid_amount = 0;

                $order->payment_type = $request->input('payment_type');
                $order->payment_status = 'paid';
                $order->pos_device = auth()->user()->pos_device ?? '';
//            }

            $order->save();

            $order->removeItemsFromZones();


            return response()->json(['status' => true, 'order' => $order]);

        }
        else if ($action == 'update' || $action == 'send_to_client') {
            $sameAddress = key_exists('same_address', $params) && $params['same_address'] == "on";
            $collectionAddress = json_decode($params['collection_address'], true);
            $collectionAddress['coordinates'] = is_array($collectionAddress['coordinates']) ?
                $collectionAddress['coordinates'] : explode(',', $collectionAddress['coordinates']);
            $deliveryAddress = null;
            if (!$sameAddress)
                $deliveryAddress = json_decode($params['delivery_address'], true);
            if (key_exists('_id', $collectionAddress)) {
                $userCollectionAddress = $appUser->addresses()->find($collectionAddress['_id']);
            } else {
                if ($collectionAddress['name'] != 'Atlantis') {
                    $userCollectionAddress = new Address();
                    foreach ($collectionAddress as $k => $v) {
                        $userCollectionAddress->$k = $v;
                    }
                    $appUser->addresses()->save($userCollectionAddress);
                } else {
                    $userCollectionAddress = $collectionAddress;
                }

            }
            if ($sameAddress || $deliveryAddress == null)
                $userDeliverAddress = $userCollectionAddress;
            else {
                if (key_exists('_id', $deliveryAddress)) {
                    $userDeliverAddress = $appUser->addresses()->find($deliveryAddress['_id']);
                } else {
                    if ($deliveryAddress['name'] != 'Atlantis') {
                        $userDeliverAddress = new Address();
                        foreach ($deliveryAddress as $k => $v) {
                            $userDeliverAddress->$k = $v;
                        }
                        $userDeliverAddress =
                            $appUser->addresses()->save($userDeliverAddress);
                    } else {
                        $userDeliverAddress = $deliveryAddress;
                    }
                }
            }


            $order->collection_address = !is_array($userCollectionAddress)?$userCollectionAddress->toArray(): $userCollectionAddress;
            $order->delivery_address = !is_array($userDeliverAddress)?$userDeliverAddress->toArray():$userDeliverAddress;
            $order->delivery_note = @$params['delivery_note'];
            $order->collection_note = @$params['collection_note'];
            $deliveryDate = Carbon::parse($params['delivery_date']);
            $collectionDate = Carbon::parse($params['collection_date']);
            $sub_total = 0;
            $discount = 0;
            $promo_discount = 0;
            $total_quantities = 0;
            $addons = 0;
            $express_order = $request->input('express_order') == "on" ? true : false;

            $orderDetailsList = [];
            if ($request->input('order_details') != null)
                $orderD = json_decode($request->input('order_details'), true);
            foreach ($orderD as $obItem) {
                $od = new OrderDetail();
                $od->quantity = (int)$obItem['quantity'];
                $od->discount = @$obItem['discount'];
                $od->price = floatval($obItem['price']);

                $od->item_type = $obItem['item_type'];
                $od->addons = @$obItem['addons'];
                $od->item = $obItem['item'];
                $od->sub_total = $obItem['sub_total'];
                $od->discount_total = $obItem['discount_total'];
                $od->addons_total = array_key_exists('addons_total', $obItem) ? $obItem['addons_total'] : 0;
                $od->total = $obItem['sub_total'] + (array_key_exists('addons_total', $obItem) ? $obItem['addons_total'] : 0) - $obItem['discount_total'];
                $od->express_order = $obItem['express_order'];
                $od->item_note = @$obItem['item_note'];
                $this->saveImagesAndNotes($od, $obItem['note'] ?? null, $obItem['images'] ?? []);

                $sub_total += $od->sub_total;
                $discount += $od->discount_total;
                $addons += $od->addons_total;

                $orderDetailsList[] = $od;
            }

            if ($order->promo_id != null) {
                $promo_discount = floatval(number_format(($sub_total + $addons) *
                    $order->promo->percentage / 100, 2, '.', ''));
            } else {
                $promo_discount = 0;
            }
//            if ($request->input('discount_id', null) != null) {
//                $discountObject = Discount::query()->findOrFail($request->input('discount_id'));
//                $order->discount_id = $discountObject->_id;
//                if ($discountObject->type == 'total' && ($sub_total + $addons) >= $discountObject->min_total_amount) {
//                    $discount += ($sub_total + $addons) * floatval($discountObject->percentage) / 100;
//                } else if ($discountObject->type == 'quantity' && $total_quantities >= intval($discountObject->min_total_quantity)) {
//                    $discount += ($sub_total + $addons) * floatval($discountObject->percentage) / 100;
//                }
//            }else
// the update of discount amount
if ($request->input('discount_amount')!= null){
    $order->discount_percentage = $request->input('discount_percentage');
    $order->discount_amount = $request->input('discount_amount');
    $discount += floatval(number_format($request->input('discount_amount'), 2, '.', ''));
} elseif ( $request->input('discount_percentage') != null ){
                    $order->discount_percentage = $request->input('discount_percentage');
                    $discount += floatval(number_format((($sub_total + $addons) * $request->input('discount_percentage') / 100), 2, '.', ''))
                         ;
                }

            $order->collection_date = $collectionDate->toDateTimeString();
            $order->delivery_date = $deliveryDate->toDateTimeString();
            $order->express_order = $express_order;
            $order->sub_total = floatval(number_format($sub_total, 2, '.', ''));
            $order->discount = floatval(number_format($discount, 2, '.', ''));
            $order->addons = floatval(number_format($addons, 2, '.', ''));
            $order->promo_discount = floatval(number_format($promo_discount, 2, '.', ''));
            $order->total = floatval(number_format($sub_total + $addons - $discount - $promo_discount, 2, '.', ''));

            if ( $order->user->is_special_member){
                //do nothing
                $order->delivery_charge = 0;

            }else{
                if ( $order->delivery_charge == null  ){
                    $infos = StaticInfo::query()->first();
                    if ($infos != null && $infos->delivery_fees != null) {
                        if ($order->total > 0 && $infos->delivery_free_min != null &&
                            $order->total < $infos->delivery_free_min) {
                            if ($order->delivery_charge > 0) {
                                $order->delivery_charge = $infos->delivery_fees;
                                $order->total =  $order->delivery_charge +
                                    floatval(number_format($sub_total + $addons - $discount - $promo_discount, 2, '.', ''));
                            } else {
                                $order->delivery_charge = $infos->delivery_fees;
                                $order->total =  $order->delivery_charge +
                                    floatval(number_format($sub_total + $addons - $discount - $promo_discount, 2, '.', ''));
                            }

                        } else {
                            if ($order->delivery_charge > 0) {
                                $order->delivery_charge = 0;
                                $order->total =  $order->delivery_charge +
                                    floatval(number_format($sub_total + $addons - $discount - $promo_discount, 2, '.', ''));
                            } else {
                                $order->delivery_charge = 0;
                            }

                        }
                    }
                }else{

                    $order->delivery_charge = $request->input('delivery_fees');
                    $order->total = $request->input('delivery_fees')+
                        floatval(number_format($sub_total + $addons - $discount - $promo_discount, 2, '.', ''));;
                }
            }


            $order->save();
            $order->orderDetails()->delete();
            $order->orderDetails()->saveMany($orderDetailsList);

            if ($action == 'send_to_client') {
                $new = Status::query()->where('slug_name', 'pending-acceptance')->first();
                $orderStatus = new OrderStatus();
                $orderStatus->user_id = auth()->user()->_id;
                $orderStatus->status_id = $new->_id;
                $order->status_id = $orderStatus->status_id;

                $order->save();
                $order->statuses()->save($orderStatus);

                dispatch(new NotificationSenderJob('request-payment', $order->_id, true, true));
            }

            return redirect()->back();
        }

        return response()->json(['message' => 'Something wrong happened.'], 500);

    }

    public function printTerminalPrinter(Request $request, $order_id)
    {
        $order = Order::query()->findOrFail($order_id);
        $collection = Status::query()->where('slug_name', 'validation')->first();
        $delivery = Status::query()->where('slug_name', 'delivery')->first();
        $collected_at = '';
        $delivered_at = '';
        if ($order->collected_by != null) {
            foreach ($order->statuses as $st) {
                if ($st->status_id == $collection->_id) {
                    $collected_at = $st->created_at->format('Y-m-d H:i');
                }

                if ($st->status_id == $delivery->_id) {
                    $delivered_at = $st->created_at->format('Y-m-d H:i');
                }

            }
        }

        return view('cms.orders.new-invoice-terminal',
            compact('order', 'collected_at', 'delivered_at'));
    }

    public function printTerminalPrinterAjax(Request $request, $order_id)
    {
        return response()->json([
            'view' => $this->printTerminalPrinter($request, $order_id)->render(),
        ]);
    }

    public function printTags(Request $request, $order_id, $item_id = null)
    {
        $order = Order::query()->findOrFail($order_id);
        $data = [];
        foreach ($order->orderDetails as $detail) {
            if ($item_id != null) {
                if ($detail['item']['_id'] == $item_id) {
                    $item = ServiceItem::query()->find($item_id);
                    $addons='';
                    if ( array_key_exists('addons',$detail) && is_array($detail['addons'])){
                        foreach ( $detail['addons'] as $add){
                            $addons.=','. (Addon::query()->find($add)->name??'');
                        }
                    }
                    if (isset($item) && $item->printing_tags != null) {
                        foreach ($item->printing_tags as $tag) {
                            for ($c = 0; $c < $detail->quantity; $c++)
                                $data[] =
                                    [
                                        'code' => $order->code,
                                        'name' => $order->user->name,
                                        'phone' => $order->user->phone,
                                        'zone' => $order->zones[$detail['item']['_id']] ?? null,
                                        'tag' => $tag,
                                        'addons' => $addons,
                                        'barcode' => $order->code
                                    ];
                        }
                    }
                }
            }
            else {
                    $item = ServiceItem::query()->find($detail['item']['_id']);
                $addons='';
                if ( array_key_exists('addons',$detail) && is_array($detail['addons'])){
                    foreach ( $detail['addons'] as $add){
                        $addons.=','. (Addon::query()->find($add)->name??'');
                    }
                }
                    if ($item !=null  && $item->printing_tags != null) {
                        foreach ($item->printing_tags as $tag) {
                            for ($c = 0; $c < $detail->quantity; $c++)
                                $data[] =
                                    [
                                        'code' => $order->code,
                                        'name' => $order->user->name,
                                        'phone' => $order->user->phone,
                                        'zone' => $order->zones[$detail['item']['_id']] ?? null,
                                        'tag' => $tag,
                                        'addons' => $addons,
                                        'barcode' => $order->code
                                    ];
                        }
                    }

            }
        }

        $data = (object)$data;
        $for_preview = true;
        return view('cms.orders.tags-thermal', compact('data', 'for_preview'));
    }

    public function printTagsAjax(Request $request, $order_id, $item_id = null)
    {
        $order = Order::query()->findOrFail($order_id);
        $data = [];
        foreach ($order->orderDetails as $detail) {
            if ($item_id != null) {
                if ($detail['item']['_id'] == $item_id) {
                    $item = ServiceItem::query()->find($item_id);

                    if (isset($item) && $item->printing_tags != null) {
                        $addons='';
                        if (is_array($detail['addons'])){
                            foreach ( $detail['addons'] as $add){
                                $addons.=','. (Addon::query()->find($add)->name??'');
                            }
                        }
                        foreach ($item->printing_tags as $tag) {
                            for ($c = 0; $c < $detail->quantity; $c++)
                                $data[] =
                                    [
                                        'code' => $order->code,
                                        'name' => $order->user->name,
                                        'phone' => $order->user->phone,
                                        'zone' => $order->zones[$detail['item']['_id']] ?? null,
                                        'tag' => $tag,
                                        'addons' => $addons,
                                        'barcode' => $order->code
                                    ];
                        }
                    }
                }
            } else {
                if (array_key_exists('printing_tags', $detail['item'])) {
                    $item = ServiceItem::query()->find($detail['item']['_id']);

                    if (isset($item) && $item->printing_tags != null) {
                        $addons='';
                        if (  is_array($detail['addons'])){
                            foreach ( $detail['addons'] as $add){
                                $addons.=','. (Addon::query()->find($add)->name??'');
                            }
                        }
                        foreach ($item->printing_tags as $tag) {
                            for ($c = 0; $c < $detail->quantity; $c++)
                                $data[] =
                                    [
                                        'code' => $order->code,
                                        'name' => $order->user->name,
                                        'phone' => $order->user->phone,
                                        'zone' => $order->zones[$detail['item']['_id']] ?? null,
                                        'tag' => $tag,
                                        'addons' => $addons,
                                        'barcode' => $order->code
                                    ];
                        }
                    }
                }
            }
        }
        $temp = $data;
        $views = [];
        foreach ($temp as $item) {
            $data = [$item];
            $views[] = view('cms.orders.tags-thermal', compact('data'))->render();
        }
        return response()->json([
            'views' => $views,
        ]);
    }

    private function sendToPrinter($ip, $text = [], $barcode = null)
    {
//        try {
        $connector = new NetworkPrintConnector('192.168.1.250', 9100);
        $printer = new Printer($connector);
        foreach ($text as $t) {
            $printer->text($t);
        }
        if ($barcode != null) {
            $printer->barcode($barcode);
        }
        $printer->cut();
        $printer->close();
//        } catch (\Exception $e) {
//        }
    }


    public function printInvoice(Request $request, $order_id)
    {
        $order = Order::query()->findOrFail($order_id);
        $collection = Status::query()->where('slug_name', 'validation')->first();
        $delivery = Status::query()->where('slug_name', 'done')->first();
        $collected_at = '';
        $delivered_at = '';
        if ($order->collected_by != null) {
            foreach ($order->statuses as $st) {
                if ($st->status_id == $collection->_id) {
                    $collected_at = $st->created_at->format('d-m-Y H:i');
                }

                if ($st->status_id == $delivery->_id) {
                    $delivered_at = $st->created_at->format('d-m-Y H:i');
                }
            }
        }
        return view('cms.orders.new-invoice', compact('order', 'collected_at', 'delivered_at'));
    }

    public function printInvoiceAjax(Request $request, $order_id)
    {
        $order = Order::query()->findOrFail($order_id);
        return response()->json([
            'view' => $this->printInvoice($request, $order->_id)->render(),
        ]);
    }

    private function saveImagesAndNotes(&$detail, $note = null, $images = [])
    {
        if ($note != null) {
            $_note = $detail['note'] ?? null;
            if ($_note == null) $_note = '';
            $_note .= ' \n ' . $note;
            $detail['note'] = $_note;
        }
        if (is_array($images) && sizeof($images) > 0) {
            $_images = $detail['images'] ?? null;
            if ($_images == null) $_images = [];
            foreach ($images as $image) {
                $_images[] = Storage::url($this->uploadAny($image, 'orders'));
            }
            $detail['images'] = $_images;
        }
    }

    private function checkInvoiceNumbers(){
        $info = StaticInfo::query()->first();
        if ($info != null && $info->start_date != null ){
            $processing = Status::query()->where('slug_name','processing')->first();
            $orders = Order::query()
                ->where(
                    'statuses', 'elemmatch',[
                    'status_id'=>$processing->_id,
                    'created_at'=>[
                        '$gte'=>Carbon::parse($info->start_date)->toDateTime()
                    ]
                ])
                ->whereNull('invoice_code')
                ->get();
            $counter = $info->invoice_serial;

            foreach ( $orders as $order){
                if ( $order->user->phone == "+97471201772" || $order->user->phone == "+9743204565"
                    ||$order->user->phone == "+974712017723"||$order->user->phone == "+97470366935"){
                    $order->invoice_code = "000000000";
                    $order->save();
                }else{
                    try{
                        $order->invoice_code = $counter++;
                        $order->save();
                    }catch (\Exception $exception){

                    }
                }

            }
            $info->invoice_serial = $counter;
            $info->save();
        }
    }
}
Leave a Comment