<?php

namespace Modules\Store\Repositories;

use App\Jobs\SendGeneralEmail;
use App\Jobs\SendNotification;
use App\Traits\ImageStore;
use Illuminate\Support\Facades\DB;
use Modules\Payment\Entities\Checkout;
use Modules\Store\Entities\DeliveryProcess;
use Modules\Store\Entities\OrderPackageDetail;
use Modules\Store\Entities\ProductOrder;
use Modules\Wallet\Http\Controllers\WalletController;

class OrderRepository extends BaseRepository
{
    use ImageStore;


    public function model()
    {
        return ProductOrder::class;
    }

    function getAll()
    {
        return ProductOrder:: with('product', 'customer')->get();
    }

    public function pendingOrder($filterData)
    {
        $query = OrderPackageDetail::query()->whereHas('order', function ($q) {
            $q->where('is_cancelled', 0);
        })->where('is_cancelled', 0)->where('delivery_status', '<=', 3)->with('order', 'seller', 'shipping')->where('seller_id', auth()->user()->id)->groupby('order_id')->distinct();

        if (!empty($filterData['carrier'])) {
            $query = $query->where('carrier_id', $filterData['carrier']);
        }
        if (!empty($filterData['shipping_method'])) {
            $query = $query->where('shipping_method', $filterData['shipping_method']);
        }
        if (!empty($filterData['package_code'])) {
            $query = $query->where('package_code', $filterData['package_code']);
        }
        if (!empty($filterData['date_range_filter'])) {
            $query = $query->whereBetween(DB::raw('DATE(created_at)'), formatDateRangeData($filterData['date_range_filter']));
        }

        return $query->where('shipping_method', '!=', 0)->latest()->get();

    }

    public function orderInfoUpdate($data, $id)
    {
        $order = Checkout::findOrFail($id);
        $user = $order->user;
        $package = $order->packages->first();

        $last_delivery_state = DeliveryProcess::orderByDesc('id')->firstOrFail();

        if ($order->is_confirmed == 1 && $data['is_confirmed'] == 1) {
            foreach ($order->packages as $key => $package) {
                $package->update([
                    'delivery_status' => 2
                ]);
            }
        }

        if ($data['is_confirmed'] == 2) {
            $order->is_cancelled = 1;
            $order->cancel_reason_id = isset($data['cancel_reason_id']) ? $data['cancel_reason_id'] : null;
            foreach ($order->packages as $pkg) {
                $pkg->update([
                    'is_cancelled' => 1
                ]);
            }
        }

        if ($order->is_completed != $data['is_completed']) {

            SendNotification::dispatch('Store_Order', $user, [
                'name' => $user->name,
                'email' => $user->email,
                'order_no' => $order->order_number,
            ],[]);


        }

        $order->is_paid = $data['is_paid'];
        $order->is_confirmed = $data['is_confirmed'];
        $order->is_completed = $data['is_completed'];
        $order->save();

        if ($order->cancel_reason_id) {
            $refund_infos = [
                'amount' => $order->purchase_price,
                'customer_id' => $order->user_id
            ];
            $payment = new WalletController();
            $payment->returnAmountTowallet($refund_infos);

            SendNotification::dispatch('Store_Order_Cancel', $user, [
                'name' => $user->name,
                'email' => $user->email,
                'order_no' => $order->order_number,
                'cancel_reason' => $order->cancel_reason->name,
            ],[]);
        }

        return true;
    }

    public function updateDeliveryStatus($data, $id)
    {
        $order_package = OrderPackageDetail::find($id);
        $order = Checkout::find($order_package->order_id);
        $user = $order->user;
        $last_delivery_state = DeliveryProcess::orderByDesc('id')->firstOrFail();
        if ($data['delivery_status'] == $last_delivery_state->id && $order_package->delivery_status != $last_delivery_state->id) {
            $order_package->is_paid = 1;
        }

        $order_package->delivery_status = $data['delivery_status'];
        $order_package->last_updated_by = auth()->user()->id;
        $order_package->save();

        $total_is_paid = 0;
        $total_is_complete = 0;
        $total_package = 0;
        foreach ($order->packages as $key => $pack) {
            if ($pack->is_paid == 1) {
                $total_is_paid += 1;
            }
            if ($pack->delivery_status == $last_delivery_state->id) {
                $total_is_complete += 1;
            }
            $total_package += 1;
        }

        $order->order_status = $data['delivery_status'];
        if ($order->is_paid == 0 && $total_package == $total_is_paid) {
            $order->is_paid = 1;
        }
        if ($order->is_completed == 0 && $total_package == $total_is_complete) {
            $order->is_completed = 1;
        }
        $order->save();

        SendNotification::dispatch('Store_Order_Delivery_Status', $user, [
            'name' => $user->name,
            'email' => $user->email,
            'order_no' => $order->order_number,
            'delivery_status' => $order_package->DeliveryStateName,
        ],[]);

        return true;
    }


}
