<?php

namespace App\Http\Controllers\User;

use App\DigitalMoney;
use App\Http\Controllers\Controller;
use App\OrderDigitalMoney;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class DigitalMoneyController extends Controller
{
    private $digital;

    public function __construct(Request $request)
    {
        if ($request->get('currency_id', false)) {
            $this->digital = DigitalMoney::query()
                ->where('id', '=', $request->get('currency_id'))
                ->where('approved', '=', 1)
                ->first();
        }
    }

    public function indexBuy(Request $request, $name)
    {
        if ($request->get('currency_id', false))
            return $this->buy($request);


        $digital = DigitalMoney::query()
            ->where('name', '=', $name)
            ->where('approved', '=', 1)
            ->first();

        if (!$digital)
            return redirect()->route('dashboard');

        return view('user.currency.buy', [
            'digital' => $digital
        ]);
    }

    public function indexSell(Request $request, $name)
    {
        if ($request->get('currency_id', false))
            return $this->sell($request);

        $digital = DigitalMoney::query()
            ->where('name', '=', $name)
            ->where('approved', '=', 1)
            ->first();

        if (!$digital)
            return redirect()->route('dashboard');

        return view('user.currency.sell', [
            'digital' => $digital,
        ]);
    }

    public function sell($request) {
        $digital = $this->digital;
        $user = Auth::user();
        $result = null;
        if (!$digital){
            return response()->json([
                'status' => false,
                'currency' => false,
                'message' => 'درخواست ارز مورد نظر پشتبانی نمی شه'
            ]);
        }
        DB::beginTransaction();

        try {
            $final_price = $request->get('quantity') * $digital->sell_money;
            $final_price = $final_price * 1;
            $quantity = $request->get('quantity');
            $tracking_code = rand(1111, 9999) . strtoupper(getSetting('app_name')) . $quantity;

            $order_money = new OrderDigitalMoney();
            $order_money->user_id = $user->getAuthIdentifier();
            $order_money->digital_money_id = $digital->id;
            $order_money->quantity = $quantity;
            $order_money->final_price = $final_price;
            $order_money->currency_price = $digital->sell_money;
            $order_money->order_type = 'sell';
            $order_money->payment_type = $request->get('pay_method');
            $order_money->status = 'pending';
            $order_money->description = $request->get('description');
            $order_money->tracking_code = $tracking_code;
            $order_money->save();
            DB::commit();
            $result = [
                'status' => true,
                'message' =>  'درخواست فروش '. $digital->name_fa  . ' شما هست ' . $quantity . ' شماره پیگیری ' . $tracking_code . '  لطفا بخش توضیحات فروش مطالعه کنید '
            ];
        }catch (\Exception $e){
            DB::rollBack();
            return response()->json([
                'status' => false,
                'message' => 'مشکلی پیش آمد در مراحل فروش شما لطفا دوباره تلاش کن.' . $e
            ]);
        }
        return response()->json($result);
    }

    public function buy($request) {
        $digital = $this->digital;
        $user = Auth::user();
        $result = null;
        if (!$digital){
            return response()->json([
                'status' => false,
                'currency' => false,
                'message' => 'درخواست ارز مورد نظر پشتبانی نمی شه'
            ]);
        }


        DB::beginTransaction();
        try {
            $pay_method = $request->get('pay_method');
            $final_price =  (int) $request->get('quantity') * (int) $digital->buy_money;
            $final_price = $final_price * 1;
            $quantity = $request->get('quantity');
            $tracking_code = rand(1111, 9999) . strtoupper(getSetting('app_name')) . $quantity;
            if ($digital->quantity > $quantity) {
                $order_money = new OrderDigitalMoney();
                $order_money->user_id = $user->getAuthIdentifier();
                $order_money->digital_money_id = $digital->id;
                $order_money->quantity = $quantity;
                $order_money->final_price = $final_price;
                $order_money->currency_price = $digital->buy_money;
                $order_money->order_type = 'buy';
                $order_money->payment_type = $pay_method;
                $order_money->wallet_currency = $request->get('wallet_currency');
                $order_money->status = 'pending';
                $order_money->description = $request->get('description');
                $order_money->tracking_code = $tracking_code;
                $order_money->save();

                try {
                    if ($pay_method === 'wallet') {
                        $wallet = $user->wallet;
                        if ($wallet > $final_price) {
                            $user->wallet = $wallet - $final_price;
                            if ($user->save()){
                                $order_money->status = 'confirm';
                                $order_money->save();
                                $digital->quantity = $digital->quantity - $quantity;
                                $digital->save();
                                $result = [
                                    'status' => true,
                                    'message' =>  'تعداد خریدار شد '. $digital->name_fa  . ' شما هست ' . $quantity . ' شماره پیگیری ' . $tracking_code
                                ];
                            }else {
                                $result = [
                                    'status' => false,
                                    'message' => 'مشکل پیش امد لطفا دوباره تلاش کنید'
                                ];
                                return false;
                            }

                        }else {
                            $result = [
                                'status' => false,
                                'message' => 'موجودی کیف پول خود را شارژ کنید.'
                            ];
                            return false;
                        }
                    }
                }catch (\Exception) {
                    DB::rollBack();
                    return response()->json($result);
                }
            } else {
                $result = [
                    'status' => false,
                    'message' => 'موجودی ' .$digital->name_fa .' کم تر از مقدار خرید شما هست '
                ];
                return false;
            }

            DB::commit();

        }catch (\Exception $e) {
            DB::rollBack();
            return response()->json($result);
        }
        return response()->json($result);
    }

    public function indexOrders () {

        $orders_buy = OrderDigitalMoney::query()->with(['digitalMoney' => function ($query) {
            $query->select(['id', 'name_fa', 'logo']);
        }, 'user'=> function ($query) {
            $query->select(['id', 'name', 'family']);
        }])
            ->where('user_id', '=', Auth::user()->getAuthIdentifier())
            ->where('order_type', '=', 'buy')
            ->orderByDesc('created_at')
            ->paginate('25', ['*'], 'page_confirm');

        $orders_sell = OrderDigitalMoney::query()->with(['digitalMoney' => function ($query) {
            $query->select(['id', 'name_fa', 'logo']);
        }, 'user'=> function ($query) {
            $query->select(['id', 'name', 'family']);
        }])
            ->where('user_id', '=', Auth::user()->getAuthIdentifier())
            ->where('order_type', '=', 'sell')
            ->orderByDesc('created_at')
            ->paginate('25', ['*'], 'page_pending');

        return view('user.currency.order', [
            'orders_buy' => $orders_buy,
            'orders_sell' => $orders_sell
        ]);
    }
}
