<?php

namespace App\Services;

use App\Models\User;
use App\Models\Deposit;
use App\Http\Controllers\Admin\MailController;
use App\Models\Plan;
use App\Models\Rank;
use App\Models\Wallet;
use App\Models\Subscription;
use App\Models\Transaction;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Carbon\Carbon;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\Image\ImagickImageBackEnd;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
use GuzzleHttp\Client;

class PaymentService
{
    public static function pay()
    {
        $rand = rand(10000, 99999);
        $order_id = 'CFA-'.$rand;
        try{
            //make payment request
            $pay = Http::nowPayment()->post('/payment', [
                "price_amount" => request()->amount,
                "price_currency" => "usd",
                "pay_currency" => request()->currency,
                "ipn_callback_url" => "https://nowpayments.io",
                "order_id" => $order_id,
                "order_description" => 'Deposit',
                "is_fixed_rate" => true,
                "is_fee_paid_by_user" => false
            ]);

            $payment = $pay->collect();
            
            // dd($payment);

            //Create Qr code
            $qr_code = self::generateQRCode($payment['pay_address'], $payment['payment_id']);

            //Deposit payment
            $deposit = Deposit::create([
                'user_id' => auth()->user()->id,
                'payment_id' => $payment['payment_id'],
                'qr_code' => $qr_code['filename'],
                'amount' => request()->amount,
                'network' => $payment['network'],
                'type' => request()->type ? request()->type : null,
                'status' => null
            ]);

            return [
                'deposit' => $deposit,
            ];
        } catch (\Exception $e) {
            // dd($errorMessage);
            return [
                'error' => $e->getMessage(),
            ];
        }
    }


    public static function payInfo($deposit)
    {
        $pay = Http::nowPayment()->get('/payment/'.$deposit->payment_id);
        $payment = $pay->collect();
        // dd($payment['payment_status']);

        if(isset($payment['payment_status'])){
            if($payment['payment_status'] == 'finished'){
                if($deposit->status == null){
                    if($deposit->type == 'setup'){
        
                        $mail = new MailController();
                    
                        $mail->storeSetup(auth()->user()->username, auth()->user()->first_name, auth()->user()->email);
        
                        $update = User::where('id', $deposit->user_id)->update(['activated' => 1]); 
        
                        if(isset(auth()->user()->referrer))
                        {
                            $amount = 20/100 * $payment['actually_paid'];
                            $totalEarnings = auth()->user()->referrer->store_bonus + $amount;
                            User::where('id', auth()->user()->referrer->id)->update([
                                'store_bonus' => $totalEarnings,
                            ]);
        
                            $transaction = Transaction::create([
                                'user_id' => auth()->user()->referrer->id,
                                'amount' => $amount,
                                'status' => 1,
                                'type' => 'store_bonus',
                            ]);
                        }
                    } else {
                        $balance = auth()->user()->balance + $payment['actually_paid'] - 1;
                        
                        $update = User::where('id', $deposit->user_id)->update(['balance' => $balance]); 
                    }
                    $deposit = tap($deposit)->update([
                        'status' => 1,
                        'amount' => $payment['actually_paid'],
                    ]);
                }
                
            } elseif ($payment['payment_status'] == 'partially_paid'){ 
                //do nothing
                $percent = 20/100 * $payment['price_amount'];
                $sum = $payment['price_amount'] - $percent;
                // dd($sum);
                if($deposit->status == null){
                    if($deposit->type == 'setup'){
    
                        if($payment['actually_paid'] >= $sum){
    
                            $mail = new MailController();
                        
                            $mail->storeSetup(auth()->user()->username, auth()->user()->first_name, auth()->user()->email);
            
                            $update = User::where('id', $deposit->user_id)->update(['activated' => 1]); 
    
                            $deposit = tap($deposit)->update([
                                'status' => 1,
                                'amount' => $payment['actually_paid'],
                            ]);
            
                            if(isset(auth()->user()->referrer))
                            {
                                $amount = 20/100 * $deposit->amount;
                                $totalEarnings = auth()->user()->referrer->store_bonus + $amount;
                                User::where('id', auth()->user()->referrer->id)->update([
                                    'store_bonus' => $totalEarnings,
                                ]);
            
                                $transaction = Transaction::create([
                                    'user_id' => auth()->user()->referrer->id,
                                    'amount' => $amount,
                                    'status' => 1,
                                    'type' => 'store_bonus',
                                ]);
                            }
                        } else {
                            $deposit = tap($deposit)->update([
                                'status' => 2,
                            ]);
                        }
                    } else {
                        $balance = auth()->user()->balance + $payment['actually_paid'] - 1;
                        
                        $update = User::where('id', $deposit->user_id)->update(['balance' => $balance]); 
                        $deposit = tap($deposit)->update([
                            'status' => 1,
                            'amount' => $payment['actually_paid'],
                        ]);
                    }
                    
                }
    
            } elseif ($payment['payment_status'] == 'waiting'){ 
               //do nothing
    
            }elseif($payment['payment_status'] == 'failed'){
                $deposit = tap($deposit)->update([
                    'status' => 2
                ]);
                // dd('failed');          
            }elseif($payment['payment_status'] == 'expired'){
                $deposit = tap($deposit)->update([
                    'status' => 2
                ]);
                // dd('expired');       
            }
        }

        return [
            'payment' => $payment,
            'deposit' => $deposit,
        ];
    }
    

    public static function creditReferrer($deposit)
    {
        $user = User::find(Auth::id());     
        if(isset($user->referrer->referrer->referrer))
        {
            $amount = 0.10 * ($deposit->amount - 3);
            $done = Wallet::where('user_id', $user->referrer->referrer->referrer->id)->update([
                'cash_balance' => $user->referrer->referrer->referrer->wallet->cash_balance + $amount,
                'cash_commission' => $user->referrer->referrer->referrer->wallet->cash_balance + $amount,
            ]);
        }
        if(isset($user->referrer->referrer))
        {
            $amount = 0.15 * ($deposit->amount - 3);
            $done = Wallet::where('user_id', $user->referrer->referrer->id)->update([
                'cash_balance' => $user->referrer->referrer->wallet->cash_balance + $amount,
                'cash_commission' => $user->referrer->referrer->wallet->cash_balance + $amount,
            ]);
        }
        if(isset($user->referrer))
        {
            $amount = 0.25 * ($deposit->amount - 3);
            Wallet::where('user_id', $user->referrer->id)->update([
                'cash_balance' => $user->referrer->wallet->cash_balance + $amount,
                'cash_commission' => $user->referrer->wallet->cash_balance + $amount,
                'sales_volume' => $user->referrer->wallet->sales_volume + $deposit->plan->price,
            ]);
            $wallet = Wallet::where('user_id', $user->referrer->id)->first();
            $sales = self::updateRank($wallet);
        } else {
            //do nothing
        }
    }

    
    public static function generateQRCode($address, $payment_id)
    {
        $url = "https://qrcode.tec-it.com/API/QRCode?size=small&dpi=120&data=$address";
        // $data = [
        //     'chs' => '250x250', // QR code size
        //     'cht' => 'qr',
        //     'chl' => $address, // Crypto address
        // ];

        $client = new Client();
        $response = $client->request('GET', $url);

        // Save the QR code image to a file (optional)
        $filename = $payment_id.'.png';
        $folder = 'qr_codes'; // Folder name within the public folder
        $path = public_path($folder . '/' . $filename);
        file_put_contents($path, $response->getBody());

        // Return the path to the QR code image
        return [
            'filename' => $filename,
        ];
    }
}