<?php

namespace App\Services;


use App\Models\Order;
use App\Models\PlanSchedule;
use App\Models\PurchasePlan;
use App\Models\Transaction;
use App\Traits\Notify;
use GPBMetadata\Google\Api\Auth;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Session;

class BasicService
{
    use Notify;
    protected $SendWhatsappMessageService;

    public function __construct(SendWhatsappMessageService $SendWhatsappMessageService)
    {
        $this->SendWhatsappMessageService = $SendWhatsappMessageService;
    }
    public function setEnv($value)
    {
        $envPath = base_path('.env');
        $env = file($envPath);
        foreach ($env as $env_key => $env_value) {
            $entry = explode("=", $env_value, 2);
            $env[$env_key] = array_key_exists($entry[0], $value) ? $entry[0] . "=" . $value[$entry[0]] . "\n" : $env_value;
        }
        $fp = fopen($envPath, 'w');
        fwrite($fp, implode($env));
        fclose($fp);
    }

    public function preparePaymentUpgradation($deposit)
    {
        try {
            if($deposit->depositable_type == PlanSchedule::class && ($deposit->status == 0 || $deposit->status == 2)){
                $deposit->status = 1;
                $deposit->save();

                $user = $deposit->user;
                $planSchedule = PlanSchedule::with(['planDetail','scheduleDetail'])->whereHas('planDetail', function ($query){
                    $query->where('status',1);
                })->findOrFail($deposit->depositable_id);

                if ($planSchedule){
                    $purchasePlan = $deposit->purchase_type == 'renew'
                        ? PurchasePlan::where('user_id', $deposit->user_id)
                            ->where('id', $deposit->purchase_id)
                            ->where('plan_id', $planSchedule->plan_id)
                            ->first()
                        : new PurchasePlan();

                    $purchasePlan->fill([
                        'user_id' => $user->id,
                        'deposit_id' => $deposit->id,
                        'gateway_id' => $deposit->payment_method_id,
                        'trx_id' => $deposit->trx_id,
                        'plan_id' => $planSchedule->plan_id,
                        'schedule_id' => $planSchedule->schedule_id,
                        'plan_name' => optional(optional($planSchedule->planDetail)->details)->plan_name,
                        'schedule_name' => optional(optional($planSchedule->scheduleDetail)->details)->name,
                        'days' => optional($planSchedule->scheduleDetail)->days,
                        'badge_name' => optional(optional($planSchedule->planDetail)->details)->badge_name,
                        'num_stores' => optional($planSchedule->planDetail)->num_stores,
                        'product_qty' => optional($planSchedule->planDetail)->product_qty,
                        'order_num' => optional($planSchedule->planDetail)->order_num,
                        'telegram_bot' => optional($planSchedule->planDetail)->telegram_bot,
                        'messenger_bot' => optional($planSchedule->planDetail)->messenger_bot,
                        'whatsapp_bot' => optional($planSchedule->planDetail)->whatsapp_bot,
                        'price' => $planSchedule->price,
                        'purchase_date' => Carbon::now(),
                        'type' => $deposit->purchase_type == 'renew' ? 'Renew' : 'Purchase',
                        'expiry_date' => Carbon::now()->addDays( (int) optional($planSchedule->scheduleDetail)->days),
                    ]);
                    $purchasePlan->save();

                    $amount = $deposit->payable_amount_in_base_currency;
                    $charge = getAmount($deposit->base_currency_charge);
                    $balance = null;
                    $trx_type = '+';
                    $remarks = 'payment Via ' . optional($deposit->gateway)->name;
                    $transactional_id = $purchasePlan->id;
                    $transactional_type = PurchasePlan::class;
                    $this->makeTransaction($user, $amount, $charge, $balance, $trx_type, $remarks, $transactional_id, $transactional_type);
                }else{
                    return back()->with('error','Plan Not Available.');
                }
                $params = [
                    'user' => optional($deposit->user)->username,
                    'amount' => currencyPosition($deposit->payable_amount_in_base_currency),
                    'topic' => 'Pricing Plan',
                    'transaction' => $deposit->trx_id,
                ];
                $actionAdmin = [
                    "name" => optional($deposit->user)->firstname . ' ' . optional($deposit->user)->lastname,
                    "image" => getFile(optional($deposit->user)->image_driver, optional($deposit->user)->image),
                    "link" => route('admin.payment.log'),
                    "icon" => "fas fa-list text-white"
                ];
                $this->adminMail('PAYMENT_PLAN_BY_USER', $params, $actionAdmin);
                $this->adminPushNotification('PAYMENT_PLAN_BY_USER', $params, $actionAdmin);
                $this->adminFirebasePushNotification('PAYMENT_PLAN_BY_USER', $params);

            }
            elseif($deposit->depositable_type == Order::class && $deposit->status == 0){
                $deposit->status = 1;
                $deposit->save();

                $user = $deposit->user;
                $order = Order::with('details')->find($deposit->depositable_id);

                if ($order){
                    $order->status = 1;
                    if (Session::get('bot_type') == null) {
                        $order->bot_type = "Messenger Bot";
                    } else {
                        $order->bot_type = "Telegram Bot";
                    }
                    $order->save();
//                    updateWallet($order->user_id, $order->payment_amount, 1);

                    $amount = $deposit->payable_amount_in_base_currency;
                    $charge = getAmount($deposit->base_currency_charge);
                    $balance = null;
                    $trx_type = '+';
                    $remarks = 'order Via ' . optional($deposit->userGateway)->name;
                    $transactional_id = $order->id;
                    $transactional_type = Order::class;
                    $this->makeTransaction($user, $amount, $charge, $balance, $trx_type, $remarks, $transactional_id, $transactional_type);
                    $this->SendWhatsappMessageService->sendOrderMessageWithPDF($order);
                }else{
                    return back()->with('error','Order Not Available.');
                }
                $params = [
                    'user' => optional($deposit->user)->username,
                    'amount' => currencyPosition($deposit->payable_amount_in_base_currency),
                    'topic' => 'Menu Order',
                    'transaction' => $deposit->trx_id,
                ];
                $actionAdmin = [
                    "name" => optional($deposit->user)->firstname . ' ' . optional($deposit->user)->lastname,
                    "image" => getFile(optional($deposit->user)->image_driver, optional($deposit->user)->image),
                    "link" => route('admin.payment.log'),
                    "icon" => "fas fa-list text-white"
                ];
                $this->adminMail('PAYMENT_ORDER_BY_USER', $params, $actionAdmin);
                $this->adminPushNotification('PAYMENT_ORDER_BY_USER', $params, $actionAdmin);
                $this->adminFirebasePushNotification('PAYMENT_ORDER_BY_USER', $params);
            }
        } catch (\Exception $e) {
        }

    }

    public function cryptoQR($wallet, $amount, $crypto = null)
    {
        $varb = $wallet . "?amount=" . $amount;
        return "https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=$varb&choe=UTF-8";
    }

    public function makeTransaction($user, $amount, $charge, $balance = null, $trx_type = null, $remarks = null, $transactional_id = null, $transactional_type = null)
    {
        $transaction = new Transaction();
        $transaction->user_id = $user->id;
        $transaction->amount = $amount;
        $transaction->charge = $charge;
        $transaction->balance = $balance;
        $transaction->trx_type = $trx_type;
        $transaction->remarks = $remarks;
        $transaction->transactional_id = $transactional_id;
        $transaction->transactional_type = $transactional_type;
        $transaction->save();
        return $transaction;
    }
}
