<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\PaymentTransaction;
use App\Models\SubscribePlan;
use App\Models\UserSubscriber;
use App\Traits\BaseApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Shetabit\Multipay\Invoice;
use Shetabit\Payment\Facade\Payment;

class PayController extends Controller
{
    use BaseApiResponse;

    public function pay(Request $request)
    {
        $validation = $request->validate([
            'subscribe_plan_id' => 'required|exists:subscribe_plans,id',
        ]);

        $subscribePlan = SubscribePlan::findOrFail($request->subscribe_plan_id);

        try {
            $invoice = (new Invoice)->amount($subscribePlan->price);

            $callback = 'https://ghaafapp.ir';
            $payment = Payment::callbackUrl($callback . '/payment/callback')
                ->purchase($invoice, function ($driver, $transaction_id) use ($subscribePlan) {
                    PaymentTransaction::create([
                        'user_id' => auth()->user()->id,
                        'subscribe_plan_id' => $subscribePlan->id,
                        'transaction_id' => $transaction_id,
                        'amount' => $subscribePlan->price,
                        'status' => 'pending',
                    ]);
                })
                ->pay();

            return $this->success(['url' => $payment]);
        } catch (\Exception $e) {
            Log::error('Payment initiation failed: ' . $e->getMessage());
            return $this->failed('Payment initialization failed', $e->getMessage());
        }
    }

    public function callback(Request $request)
    {
        try {
            $url = 'http://bitpay.ir/payment/gateway-result-second';
            $api = '066fd-d622e-690a9-be618-ddf02bc6059bbbd67c317bb340d1';
            $trans_id = $request->input('trans_id');
            $id_get = $request->input('id_get');
            $result = $this->get($url, $api, $trans_id, $id_get);
            $parseDecode = json_decode($result);
            if ($parseDecode->status == 1) {

                $transaction = PaymentTransaction::where('transaction_id', $id_get)->first();
                $transaction->update([
                    'status' => 'success',
                ]);

                $expiredAt = now()->addDays($transaction->subscribePlan->expired_day);

                UserSubscriber::where('user_id', $transaction->user_id)->delete();
                $transaction->user->userSubscribers()->create([
                    'subscribe_plan_id' => $transaction->subscribe_plan_id,
                    'expired_at' => $expiredAt,
                ]);

                return $this->success([], 'Payment Successful', 'Subscription successfully activated.');
            }

            return $this->failed([], ['title' => 'Payment Failed', 'message' => 'Payment verification failed.']);
        } catch (\Exception $e) {
            Log::info('error in callback function', ['error' => $e->getMessage()]);
            return $this->failed([], ['title' => 'Payment Failed', 'message' => 'Payment verification failed.']);
        }
    }


    private function send($url, $api, $amount, $redirect, $factorId, $name, $email, $description)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "api=$api&amount=$amount&redirect=$redirect&factorId=$factorId&name=$name&email=$email&description=$description");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    private function get($url, $api, $trans_id, $id_get)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "api=$api&id_get=$id_get&trans_id=$trans_id&json=1");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }
}
