<?php

namespace Modules\Superadmin\Http\Controllers;

use \Notification;
use App\Business;
use App\System;
use App\Utils\ModuleUtil;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Modules\Superadmin\Entities\Package;

use Modules\Superadmin\Entities\Subscription;
use Modules\Superadmin\Notifications\SubscriptionOfflinePaymentActivationConfirmation;

use Pesapal;
use Razorpay\Api\Api;
use Srmklive\PayPal\Services\ExpressCheckout;
use Stripe\Charge;

use Stripe\Customer;
use Stripe\Stripe;
use Paystack;
use Yajra\DataTables\Facades\DataTables;

class SubscriptionController extends BaseController
{
    protected $provider;

    public function __construct(ModuleUtil $moduleUtil = null)
    {
        if (! defined('CURL_SSLVERSION_TLSv1_2')) {
            define('CURL_SSLVERSION_TLSv1_2', 6);
        }

        if (! defined('CURLOPT_SSLVERSION')) {
            define('CURLOPT_SSLVERSION', 6);
        }

        $this->moduleUtil = $moduleUtil;
    }

    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
        if (!auth()->user()->can('superadmin.access_package_subscriptions')) {
            abort(403, 'Unauthorized action.');
        }

        $business_id = request()->session()->get('user.business_id');

        //Get active subscription and upcoming subscriptions.
        $active = Subscription::active_subscription($business_id);

        $nexts = Subscription::upcoming_subscriptions($business_id);
        $waiting = Subscription::waiting_approval($business_id);

        $packages = Package::active()->orderby('sort_order')->get();

        //Get all module permissions and convert them into name => label
        $permissions = $this->moduleUtil->getModuleData('superadmin_package');
        $permission_formatted = [];
        foreach ($permissions as $permission) {
            foreach ($permission as $details) {
                $permission_formatted[$details['name']] = $details['label'];
            }
        }

        $intervals = ['days' => __('lang_v1.days'), 'months' => __('lang_v1.months'), 'years' => __('lang_v1.years')];

        return view('superadmin::subscription.index')
            ->with(compact('packages', 'active', 'nexts', 'waiting', 'permission_formatted', 'intervals'));
    }

    /**
     * Show pay form for a new package.
     * @return Response
     */
    public function pay($package_id, $form_register = null)
    {
        if (!auth()->user()->can('superadmin.access_package_subscriptions')) {
            abort(403, 'Unauthorized action.');
        }

        try {
            DB::beginTransaction();

            $business_id = request()->session()->get('user.business_id');

            $package = Package::active()->find($package_id);

            //Check if superadmin only package
            if ($package->is_private == 1 && !auth()->user()->can('superadmin')) {
                $output = ['success' => 0, 'msg' => __('superadmin::lang.not_allowed_for_package')];
                return redirect()
                    ->back()
                    ->with('status', $output);
            }

            //Check if one time only package
            if (empty($form_register) && $package->is_one_time) {
                $count_subcriptions = Subscription::where('business_id', $business_id)
                    ->where('package_id', $package_id)
                    ->count();

                if ($count_subcriptions > 0) {
                    $output = ['success' => 0, 'msg' => __('superadmin::lang.maximum_subscription_limit_exceed')];
                    return redirect()
                        ->back()
                        ->with('status', $output);
                }
            }

            //Check for free package & subscribe it.
            if ($package->price == 0) {
                $gateway = null;
                $payment_transaction_id = 'FREE';
                $user_id = request()->session()->get('user.id');

                $this->_add_subscription($business_id, $package, $gateway, $payment_transaction_id, $user_id);

                DB::commit();

                if (empty($form_register)) {
                    $output = ['success' => 1, 'msg' => __('lang_v1.success')];
                    return redirect()
                        ->action('\Modules\Superadmin\Http\Controllers\SubscriptionController@index')
                        ->with('status', $output);
                } else {
                    $output = ['success' => 1, 'msg' => __('superadmin::lang.registered_and_subscribed')];
                    return redirect()
                        ->action('\Modules\Superadmin\Http\Controllers\SubscriptionController@index')
                        ->with('status', $output);
                }
            }

            $gateways = $this->_payment_gateways();

            $system_currency = System::getCurrency();

            DB::commit();

            if (empty($form_register)) {
                $layout = 'layouts.app';
            } else {
                $layout = 'layouts.auth';
            }

            $user = request()->session()->get('user');

            $offline_payment_details = System::getProperty('offline_payment_details');

            return view('superadmin::subscription.pay')
                ->with(compact('package', 'gateways', 'system_currency', 'layout', 'user', 'offline_payment_details'));
        } catch (\Exception $e) {
            DB::rollBack();

            \Log::emergency("File:" . $e->getFile(). "Line:" . $e->getLine(). "Message:" . $e->getMessage());

            $output = ['success' => 0, 'msg' => "File:" . $e->getFile(). "Line:" . $e->getLine(). "Message:" . $e->getMessage()];

            return redirect()
                ->action('\Modules\Superadmin\Http\Controllers\SubscriptionController@index')
                ->with('status', $output);
        }
    }

    /**
     * Show pay form for a new package.
     * @return Response
     */
    public function registerPay($package_id)
    {
        return $this->pay($package_id, 1);
    }

    /**
     * Save the payment details and add subscription details
     * @return Response
     */
    public function confirm($package_id, Request $request)
    {
        if (!auth()->user()->can('superadmin.access_package_subscriptions')) {
            abort(403, 'Unauthorized action.');
        }

        try {

            //Disable in demo
            if (config('app.env') == 'demo') {
                $output = [
                    'success' => 0,
                    'msg' => 'Feature disabled in demo!!'
                ];

                return back()->with('status', $output);
            }

            //Confirm for pesapal payment gateway
            if (isset($this->_payment_gateways()['pesapal']) && (strpos($request->merchant_reference, 'PESAPAL') !== false)) {
                return $this->confirm_pesapal($package_id, $request);
            }

            DB::beginTransaction();

            $business_id = request()->session()->get('user.business_id');
            $business_name = request()->session()->get('business.name');
            $user_id = request()->session()->get('user.id');
            $package = Package::active()->find($package_id);

            //Call the payment method
            $pay_function = 'pay_' . request()->gateway;
            $payment_transaction_id = null;

            if (method_exists($this, $pay_function)) {
                $payment_transaction_id = $this->$pay_function($business_id, $business_name, $package, $request);
            }

            //Add subscription details after payment is successful
            $subscription = $this->_add_subscription($business_id, $package, request()->gateway, $payment_transaction_id, $user_id);

            // ERP Sousait:
            // Se o usuário veio do cadastro público, ele foi criado com allow_login = 0.
            // Nesse caso, após pagamento aprovado, geramos token de confirmação por e-mail.
            $confirmation_user = User::find($user_id);
            $requires_customer_confirmation = false;
            $confirmation_token = null;

            if (!empty($confirmation_user) && (int) $confirmation_user->allow_login === 0 && request()->gateway != 'offline') {
                $confirmation_token = str_random(64);
                $confirmation_user->remember_token = hash('sha256', $confirmation_token);
                $confirmation_user->save();

                $requires_customer_confirmation = true;
            }

            DB::commit();

            if ($requires_customer_confirmation) {
                try {
                    $this->sendCustomerPaymentConfirmationEmail(
                        $confirmation_user,
                        $package,
                        $subscription,
                        $confirmation_token
                    );
                } catch (\Exception $mailException) {
                    \Log::warning(
                        'Falha ao enviar e-mail de confirmação do cadastro ERP Sousait. ' .
                        'User ID: ' . $confirmation_user->id . ' - Erro: ' . $mailException->getMessage()
                    );
                }

                \Auth::logout();
                $request->session()->flush();
                $request->session()->regenerate();

                $output = [
                    'success' => 1,
                    'msg' => 'Pagamento aprovado! Enviamos um e-mail de confirmação para liberar o acesso ao ERP Sousait.'
                ];

                return redirect('/login')->with('status', $output);
            }

            $msg = __('lang_v1.success');

            if (request()->gateway == 'offline') {
                $msg = __('superadmin::lang.notification_sent_for_approval');
            }

            $output = ['success' => 1, 'msg' => $msg];

        } catch (\Exception $e) {
            DB::rollBack();

            \Log::emergency("File:" . $e->getFile(). "Line:" . $e->getLine(). "Message:" . $e->getMessage());

            $output = [
                'success' => 0,
                'msg' => $e->getMessage()
            ];
        }

        return redirect()
            ->action('\Modules\Superadmin\Http\Controllers\SubscriptionController@index')
            ->with('status', $output);
    }

    public function confirmCustomerRegistration($user_id, $token, Request $request)
    {
        try {
            $user = User::find($user_id);

            if (empty($user)) {
                return redirect('/login')->with('status', [
                    'success' => 0,
                    'msg' => 'Link de confirmação inválido.'
                ]);
            }

            $expected_token = $user->remember_token;
            $received_token = hash('sha256', $token);

            if (empty($expected_token)) {
                if (!empty($user) && (int) $user->allow_login === 1) {
                    return redirect('/login')->with('status', [
                        'success' => 1,
                        'msg' => 'Cadastro já confirmado anteriormente. Faça login normalmente para acessar o ERP Sousait.'
                    ]);
                }

                return redirect('/login')->with('status', [
                    'success' => 0,
                    'msg' => 'Não foi possível confirmar este cadastro. O link pode estar expirado, incompleto ou já ter sido utilizado. Se você já confirmou o cadastro, faça login normalmente.'
                ]);
            }

            if (!hash_equals($expected_token, $received_token)) {
                return redirect('/login')->with('status', [
                    'success' => 0,
                    'msg' => 'Link de confirmação inválido. Acesse novamente pelo link recebido no e-mail de confirmação.'
                ]);
            }

            $user->allow_login = 1;
            $user->remember_token = null;
            $user->save();

            $business = Business::find($user->business_id);

            try {
                $this->sendRegistrationConfirmedAdminEmail($business, $user);
            } catch (\Exception $mailException) {
                \Log::warning(
                    'Falha ao enviar e-mail ao Admsys após confirmação do cliente. ' .
                    'User ID: ' . $user->id . ' - Erro: ' . $mailException->getMessage()
                );
            }

            return redirect('/login')->with('status', [
                'success' => 1,
                'msg' => 'E-mail confirmado com sucesso! Agora você já pode acessar o ERP Sousait.'
            ]);

        } catch (\Exception $e) {
            \Log::emergency("File:" . $e->getFile() . "Line:" . $e->getLine() . "Message:" . $e->getMessage());

            return redirect('/login')->with('status', [
                'success' => 0,
                'msg' => 'Não foi possível confirmar o cadastro. Tente novamente ou entre em contato com o suporte.'
            ]);
        }
    }

    private function sendCustomerPaymentConfirmationEmail($user, $package, $subscription, $token)
    {
        if (empty($user->email)) {
            return;
        }

        $business = Business::find($user->business_id);
        $business_name = !empty($business) ? $business->name : 'sua empresa';

        $confirm_url = url('/erp-registration/confirm/' . $user->id . '/' . $token);

        $package_name = !empty($package) ? $package->name : 'Plano ERP Sousait';
        $package_price = !empty($package) && isset($package->price)
            ? 'R$ ' . number_format((float) $package->price, 2, ',', '.')
            : 'Não informado';

        $owner_name = trim(
            ($user->surname ? $user->surname . ' ' : '') .
            ($user->first_name ? $user->first_name . ' ' : '') .
            ($user->last_name ? $user->last_name : '')
        );

        $html = '
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Confirme seu cadastro - ERP Sousait</title>
</head>
<body style="margin:0; padding:0; background-color:#eef4f8; font-family:Arial, Helvetica, sans-serif; color:#1f2d3d;">

    <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#eef4f8" style="background-color:#eef4f8; padding:24px 0; margin:0;">
        <tr>
            <td align="center" style="padding:0 12px;">

                <table width="620" cellpadding="0" cellspacing="0" border="0" bgcolor="#ffffff" style="width:620px; max-width:620px; background-color:#ffffff; border:1px solid #dce8f1; border-collapse:collapse;">

                    <tr>
                        <td bgcolor="#0f2f46" style="background-color:#0f2f46; padding:24px 30px; color:#ffffff; font-family:Arial, Helvetica, sans-serif;">
                            <div style="font-size:12px; text-transform:uppercase; letter-spacing:2px; color:#65d4ff; font-weight:bold;">
                                ERP SOUSAIT
                            </div>

                            <h1 style="margin:8px 0 0 0; font-size:24px; line-height:1.3; color:#ffffff; font-weight:bold;">
                                Confirme seu cadastro
                            </h1>

                            <p style="margin:8px 0 0 0; font-size:14px; line-height:1.5; color:#d8eef9;">
                                Seu pagamento foi aprovado. Falta apenas confirmar seu e-mail para liberar o acesso.
                            </p>
                        </td>
                    </tr>

                    <tr>
                        <td style="padding:26px 30px; font-family:Arial, Helvetica, sans-serif;">

                            <p style="font-size:15px; line-height:1.6; margin:0 0 14px 0; color:#1f2d3d;">
                                Olá, <strong>' . e($owner_name) . '</strong>.
                            </p>

                            <p style="font-size:15px; line-height:1.6; margin:0 0 18px 0; color:#1f2d3d;">
                                Recebemos a confirmação de pagamento da empresa <strong>' . e($business_name) . '</strong> no <strong>ERP Sousait</strong>.
                                Para proteger sua conta, clique no botão abaixo e confirme seu e-mail.
                            </p>

                            <table width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse; margin:0 0 22px 0;">
                                <tr>
                                    <td colspan="2" bgcolor="#f2f8fc" style="background-color:#f2f8fc; color:#0d5f8f; padding:12px 14px; font-size:15px; font-weight:bold; border-bottom:1px solid #e5edf3;">
                                        Dados da assinatura
                                    </td>
                                </tr>
                                <tr>
                                    <td width="200" bgcolor="#fbfdff" style="width:200px; padding:10px 14px; border-bottom:1px solid #e5edf3; font-size:13px; color:#607080; font-weight:bold; background-color:#fbfdff;">
                                        Empresa
                                    </td>
                                    <td style="padding:10px 14px; border-bottom:1px solid #e5edf3; font-size:14px; color:#1f2d3d;">
                                        ' . e($business_name) . '
                                    </td>
                                </tr>
                                <tr>
                                    <td width="200" bgcolor="#fbfdff" style="width:200px; padding:10px 14px; border-bottom:1px solid #e5edf3; font-size:13px; color:#607080; font-weight:bold; background-color:#fbfdff;">
                                        Plano
                                    </td>
                                    <td style="padding:10px 14px; border-bottom:1px solid #e5edf3; font-size:14px; color:#1f2d3d;">
                                        ' . e($package_name) . '
                                    </td>
                                </tr>
                                <tr>
                                    <td width="200" bgcolor="#fbfdff" style="width:200px; padding:10px 14px; border-bottom:1px solid #e5edf3; font-size:13px; color:#607080; font-weight:bold; background-color:#fbfdff;">
                                        Valor
                                    </td>
                                    <td style="padding:10px 14px; border-bottom:1px solid #e5edf3; font-size:14px; color:#1f2d3d;">
                                        ' . e($package_price) . '
                                    </td>
                                </tr>
                            </table>

                            <table cellpadding="0" cellspacing="0" border="0" style="margin:20px 0 22px 0;">
                                <tr>
                                    <td align="center" bgcolor="#168fd3" style="background-color:#168fd3; padding:12px 22px;">
                                        <a href="' . e($confirm_url) . '"
                                           target="_blank"
                                           style="font-family:Arial, Helvetica, sans-serif; font-size:14px; font-weight:bold; color:#ffffff !important; text-decoration:none; display:inline-block;">
                                            Confirmar meu cadastro
                                        </a>
                                    </td>
                                </tr>
                            </table>

                            <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#fff7e6" style="background-color:#fff7e6; border-collapse:collapse; margin:0;">
                                <tr>
                                    <td width="4" bgcolor="#f5a623" style="width:4px; background-color:#f5a623;"></td>
                                    <td style="padding:13px 15px; font-size:14px; line-height:1.5; color:#5c4600; font-family:Arial, Helvetica, sans-serif;">
                                        <strong>Segurança:</strong> se você não realizou este cadastro, ignore esta mensagem.
                                        O acesso ao ERP só será liberado após a confirmação deste e-mail.
                                    </td>
                                </tr>
                            </table>

                        </td>
                    </tr>

                    <tr>
                        <td bgcolor="#0f2f46" style="background-color:#0f2f46; padding:16px 30px; color:#b9d8e8; font-size:12px; text-align:center; line-height:1.5; font-family:Arial, Helvetica, sans-serif;">
                            <strong style="color:#ffffff;">ERP Sousait</strong><br>
                            Gestão empresarial simples, clara e integrada.
                        </td>
                    </tr>

                </table>

            </td>
        </tr>
    </table>

</body>
</html>';

        \Mail::send([], [], function ($message) use ($user, $html, $business_name) {
            $fromAddress = env('MAIL_FROM_ADDRESS', env('MAIL_USERNAME'));
            $fromName = env('MAIL_FROM_NAME', 'ERP Sousait');

            if (!empty($fromAddress)) {
                $message->from($fromAddress, $fromName);
            }

            $message->to($user->email)
                ->subject('Confirme seu cadastro no ERP Sousait')
                ->setBody($html, 'text/html');
        });
    }

    private function sendRegistrationConfirmedAdminEmail($business, $user)
    {
        $adminEmail = env('ADMIN_REGISTRATION_EMAIL', 'admsys@sousait.net');

        if (empty($adminEmail)) {
            return;
        }

        $businessName = !empty($business) ? $business->name : 'Empresa não identificada';

        $ownerName = trim(
            ($user->surname ? $user->surname . ' ' : '') .
            ($user->first_name ? $user->first_name . ' ' : '') .
            ($user->last_name ? $user->last_name : '')
        );

        $html = '
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Cadastro confirmado - ERP Sousait</title>
</head>
<body style="margin:0; padding:0; background:#eef4f8; font-family:Arial, Helvetica, sans-serif; color:#1f2d3d;">
    <table width="100%" cellpadding="0" cellspacing="0" style="background:#eef4f8; padding:30px 0;">
        <tr>
            <td align="center">
                <table width="680" cellpadding="0" cellspacing="0" style="background:#ffffff; border-radius:14px; overflow:hidden; box-shadow:0 8px 24px rgba(15,40,70,0.12);">
                    <tr>
                        <td style="background:linear-gradient(135deg,#092033,#0d5f8f); padding:30px 36px; color:#ffffff;">
                            <div style="font-size:13px; text-transform:uppercase; letter-spacing:1.4px; color:#65d4ff; font-weight:bold;">
                                ERP Sousait
                            </div>
                            <h1 style="margin:10px 0 6px; font-size:26px; line-height:1.3;">
                                Cadastro confirmado pelo cliente
                            </h1>
                            <p style="margin:0; font-size:15px; color:#d8eef9;">
                                O cliente confirmou o e-mail após o pagamento aprovado.
                            </p>
                        </td>
                    </tr>

                    <tr>
                        <td style="padding:28px 36px;">
                            <p style="font-size:15px; line-height:1.6; margin:0 0 20px;">
                                Um novo acesso foi liberado no ERP Sousait.
                            </p>

                            <table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse; margin-bottom:24px;">
                                <tr>
                                    <td colspan="2" style="background:#f2f8fc; color:#0d5f8f; padding:12px 14px; font-size:16px; font-weight:bold; border-radius:8px 8px 0 0;">
                                        Dados principais
                                    </td>
                                </tr>
                                <tr>
                                    <td style="width:220px; padding:11px 14px; border-bottom:1px solid #e5edf3; font-size:13px; color:#607080; font-weight:bold; background:#fbfdff;">Empresa</td>
                                    <td style="padding:11px 14px; border-bottom:1px solid #e5edf3; font-size:14px; color:#1f2d3d;">' . e($businessName) . '</td>
                                </tr>
                                <tr>
                                    <td style="width:220px; padding:11px 14px; border-bottom:1px solid #e5edf3; font-size:13px; color:#607080; font-weight:bold; background:#fbfdff;">Responsável</td>
                                    <td style="padding:11px 14px; border-bottom:1px solid #e5edf3; font-size:14px; color:#1f2d3d;">' . e($ownerName) . '</td>
                                </tr>
                                <tr>
                                    <td style="width:220px; padding:11px 14px; border-bottom:1px solid #e5edf3; font-size:13px; color:#607080; font-weight:bold; background:#fbfdff;">Usuário</td>
                                    <td style="padding:11px 14px; border-bottom:1px solid #e5edf3; font-size:14px; color:#1f2d3d;">' . e($user->username) . '</td>
                                </tr>
                                <tr>
                                    <td style="width:220px; padding:11px 14px; border-bottom:1px solid #e5edf3; font-size:13px; color:#607080; font-weight:bold; background:#fbfdff;">E-mail</td>
                                    <td style="padding:11px 14px; border-bottom:1px solid #e5edf3; font-size:14px; color:#1f2d3d;">' . e($user->email) . '</td>
                                </tr>
                            </table>
                        </td>
                    </tr>

                    <tr>
                        <td style="background:#092033; padding:18px 36px; color:#aac7d8; font-size:12px; text-align:center;">
                            ERP Sousait • Mensagem automática gerada após confirmação do cliente.
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>';

        \Mail::send([], [], function ($message) use ($adminEmail, $html, $businessName) {
            $fromAddress = env('MAIL_FROM_ADDRESS', env('MAIL_USERNAME'));
            $fromName = env('MAIL_FROM_NAME', 'ERP Sousait');

            if (!empty($fromAddress)) {
                $message->from($fromAddress, $fromName);
            }

            $message->to($adminEmail)
                ->subject('Cadastro confirmado no ERP Sousait - ' . $businessName)
                ->setBody($html, 'text/html');
        });
    }

    /**
     * Confirm for pesapal gateway
     * when payment gateway is PesaPal payment gateway request package_id
     * is transaction_id & merchant_reference in session contains
     * the package_id.
     *
     * @return Response
     */
    protected function confirm_pesapal($transaction_id, $request)
    {
        $merchant_reference = $request->merchant_reference;
        $pesapal_session = $request->session()->pull('pesapal');

        if ($pesapal_session['ref'] == $merchant_reference) {
            $package_id = $pesapal_session['package_id'];

            $business_id = request()->session()->get('user.business_id');
            $business_name = request()->session()->get('business.name');
            $user_id = request()->session()->get('user.id');
            $package = Package::active()->find($package_id);

            $this->_add_subscription($business_id, $package, 'pesapal', $transaction_id, $user_id);
            $output = ['success' => 1, 'msg' => __('superadmin::lang.waiting_for_confirmation')];

            return redirect()
                ->action('\Modules\Superadmin\Http\Controllers\SubscriptionController@index')
                ->with('status', $output);
        }
    }

    /**
     * Stripe payment method
     * @return Response
     */
    protected function pay_stripe($business_id, $business_name, $package, $request)
    {
        Stripe::setApiKey(env('STRIPE_SECRET_KEY'));

        $metadata = ['business_id' => $business_id, 'business_name' => $business_name, 'stripe_email' => $request->stripeEmail, 'package_name' => $package->name];
        // $customer = Customer::create(array(
        //     'email' => $request->stripeEmail,
        //     'source'  => $request->stripeToken,
        //     'metadata' => $metadata
        // ));

        $system_currency = System::getCurrency();

        $charge = Charge::create([
            'amount'   => $package->price*100,
            'currency' => strtolower($system_currency->code),
            "source" => $request->stripeToken,
            //'customer' => $customer
            'metadata' => $metadata
        ]);

        return $charge->id;
    }

    /**
     * Offline payment method
     * @return Response
     */
    protected function pay_offline($business_id, $business_name, $package, $request)
    {

        //Disable in demo
        if (config('app.env') == 'demo') {
            $output = ['success' => 0,
                'msg' => 'Feature disabled in demo!!'
            ];
            return back()->with('status', $output);
        }

        //Send notification
        $email = System::getProperty('email');
        $business = Business::find($business_id);

        if (!$this->moduleUtil->IsMailConfigured()) {
            return null;
        }
        $system_currency = System::getCurrency();
        $package->price = $system_currency->symbol . number_format($package->price, 2, $system_currency->decimal_separator, $system_currency->thousand_separator);

        Notification::route('mail', $email)
            ->notify(new SubscriptionOfflinePaymentActivationConfirmation($business, $package));

        return null;
    }

    private function getPaypalCurrencyCode()
    {
        $system_currency = System::getCurrency();
        $paypal_currency = strtoupper($system_currency->code);

        if (config('paypal.mode') == 'sandbox') {
            $paypal_currency = strtoupper(env('PAYPAL_SANDBOX_CURRENCY', $system_currency->code));
        }

        if (config('paypal.mode') == 'live') {
            $paypal_currency = strtoupper(env('PAYPAL_LIVE_CURRENCY', $system_currency->code));
        }

        return $paypal_currency;
    }

    /**
     * Paypal payment method
     * @return Response
     */
    protected function pay_paypal($business_id, $business_name, $package, $request)
    {
        $paypal_currency = $this->getPaypalCurrencyCode();
        $provider = new ExpressCheckout();

        $token = $request->get('token');
        $PayerID = $request->get('PayerID');

        \Log::info('PayPal confirm callback received', [
            'package_id' => $package->id,
            'business_id' => $business_id,
            'token_present' => !empty($token),
            'payer_id_present' => !empty($PayerID),
            'paypal_currency' => $paypal_currency,
            'paypal_mode' => config('paypal.mode')
        ]);

        $response = $provider
            ->setCurrency($paypal_currency)
            ->getExpressCheckoutDetails($token);

        \Log::info('PayPal getExpressCheckoutDetails response', [
            'ack' => isset($response['ACK']) ? $response['ACK'] : null,
            'invnum' => isset($response['INVNUM']) ? $response['INVNUM'] : null,
            'short_message' => isset($response['L_SHORTMESSAGE0']) ? $response['L_SHORTMESSAGE0'] : null,
            'long_message' => isset($response['L_LONGMESSAGE0']) ? $response['L_LONGMESSAGE0'] : null,
            'response' => $response
        ]);

        $ack = isset($response['ACK']) ? strtoupper($response['ACK']) : '';

        if (!in_array($ack, ['SUCCESS', 'SUCCESSWITHWARNING'])) {
            $error = 'Falha ao consultar detalhes da transação PayPal.';

            if (!empty($response['L_LONGMESSAGE0'])) {
                $error .= ' Detalhe PayPal: ' . $response['L_LONGMESSAGE0'];
            }

            throw new \Exception($error);
        }


        $data = [];

        $paypalItemName = env('PAYPAL_ITEM_NAME', 'ERP Sousait - Assinatura');
        $paypalDescription = env('PAYPAL_ORDER_DESCRIPTION', 'ERP Sousait - Assinatura');
        $paypalInvoicePrefix = env('PAYPAL_INVOICE_PREFIX', 'ERP-SOUSAIT');

        $invoice_id = isset($response['INVNUM'])
            ? $response['INVNUM']
            : $paypalInvoicePrefix . '-' . str_random(8);



        $data['items'] = [
            [
                'name' => $paypalItemName . ' - ' . $package->name,
                'price' => (float) $package->price,
                'qty' => 1,
                'desc' => $paypalDescription
            ]
        ];

        $data['invoice_id'] = $invoice_id;
        $data['invoice_description'] = $paypalDescription;
        $data['return_url'] = action('\Modules\Superadmin\Http\Controllers\SubscriptionController@confirm', [$package->id]) . '?gateway=paypal';
        $data['cancel_url'] = action('\Modules\Superadmin\Http\Controllers\SubscriptionController@pay', [$package->id]);
        $data['total'] = (float) $package->price;



        \Log::info('PayPal doExpressCheckoutPayment request', [
            'package_id' => $package->id,
            'invoice_id' => $invoice_id,
            'paypal_currency' => $paypal_currency,
            'data' => $data
        ]);

        $payment_status = $provider
            ->setCurrency($paypal_currency)
            ->doExpressCheckoutPayment($data, $token, $PayerID);

        \Log::info('PayPal doExpressCheckoutPayment response', [
            'payment_status' => $payment_status
        ]);

        $status = isset($payment_status['PAYMENTINFO_0_PAYMENTSTATUS'])
            ? strtoupper($payment_status['PAYMENTINFO_0_PAYMENTSTATUS'])
            : null;

        if (in_array($status, ['COMPLETED', 'PENDING', 'PROCESSED'])) {
            return $invoice_id;
        }

        $error = 'Falha ao concluir pagamento PayPal.';

        if (!empty($payment_status['L_LONGMESSAGE0'])) {
            $error .= ' Detalhe PayPal: ' . $payment_status['L_LONGMESSAGE0'];
        } elseif (!empty($payment_status['PAYMENTINFO_0_PAYMENTSTATUS'])) {
            $error .= ' Status: ' . $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
        }

        throw new \Exception($error);
    }

    /**
     * Paypal payment method - redirect to paypal url for payments
     *
     * @return Response
     */
    public function paypalExpressCheckout(Request $request, $package_id)
    {
        //Disable in demo
        if (config('app.env') == 'demo') {
            $output = [
                'success' => 0,
                'msg' => 'Feature disabled in demo!!'
            ];

            return back()->with('status', $output);
        }

        // Get package details.
        $package = Package::active()
            ->notPrivate()
            ->find($package_id);

        if (empty($package)) {
            return back()->with('status', [
                'success' => 0,
                'msg' => 'Plano inválido ou indisponível.'
            ]);
        }

        $data = [];

        $paypalItemName = env('PAYPAL_ITEM_NAME', 'ERP Sousait - Assinatura');
        $paypalDescription = env('PAYPAL_ORDER_DESCRIPTION', 'ERP Sousait - Assinatura');
        $paypalInvoicePrefix = env('PAYPAL_INVOICE_PREFIX', 'ERP-SOUSAIT');

        $data['items'] = [
            [
                'name' => $paypalItemName . ' - ' . $package->name,
                'price' => (float) $package->price,
                'qty' => 1,
                'desc' => $paypalDescription
            ]
        ];

        $data['invoice_id'] = $paypalInvoicePrefix . '-' . str_random(8);
        $data['invoice_description'] = $paypalDescription;
        $data['return_url'] = action('\Modules\Superadmin\Http\Controllers\SubscriptionController@confirm', [$package_id]) . '?gateway=paypal';
        $data['cancel_url'] = action('\Modules\Superadmin\Http\Controllers\SubscriptionController@pay', [$package_id]);
        $data['total'] = (float) $package->price;

        $system_currency = System::getCurrency();
        $provider = new ExpressCheckout();
        $paypal_currency = $this->getPaypalCurrencyCode();

        \Log::info('PayPal setExpressCheckout request', [
            'package_id' => $package_id,
            'package_name' => $package->name,
            'package_price' => $package->price,
            'system_currency' => $system_currency->code,
            'paypal_currency' => $paypal_currency,
            'paypal_mode' => config('paypal.mode'),
            'data' => $data
        ]);

        $response = $provider
            ->setCurrency($paypal_currency)
            ->setExpressCheckout($data);

        \Log::info('PayPal setExpressCheckout response', [
            'response' => $response
        ]);

        if (empty($response['paypal_link'])) {
            $error_msg = 'Falha ao iniciar pagamento PayPal. Verifique credenciais, moeda e conta Sandbox.';

            if (!empty($response['L_LONGMESSAGE0'])) {
                $error_msg .= ' Detalhe PayPal: ' . $response['L_LONGMESSAGE0'];
            } elseif (!empty($response['L_SHORTMESSAGE0'])) {
                $error_msg .= ' Detalhe PayPal: ' . $response['L_SHORTMESSAGE0'];
            }

            \Log::error('PayPal não retornou paypal_link', [
                'response' => $response
            ]);

            return back()->with('status', [
                'success' => 0,
                'msg' => $error_msg
            ]);
        }

        return redirect($response['paypal_link']);
    }
    /**
     * Razor pay payment method
     * @return Response
     */
    protected function pay_razorpay($business_id, $business_name, $package, $request)
    {
        $razorpay_payment_id = $request->razorpay_payment_id;
        $razorpay_api = new Api(env('RAZORPAY_KEY_ID'), env('RAZORPAY_KEY_SECRET'));

        $payment = $razorpay_api->payment->fetch($razorpay_payment_id)->capture(['amount'=> $package->price*100]); // Captures a payment

        if (empty($payment->error_code)) {
            return $payment->id;
        } else {
            $error_description = $payment->error_description;
            throw new \Exception($error_description);
        }
    }

    /**
     * Redirect the User to Paystack Payment Page
     * @return Url
     */
    public function getRedirectToPaystack()
    {
        return Paystack::getAuthorizationUrl()->redirectNow();
    }

    /**
     * Obtain Paystack payment information
     * @return void
     */
    public function postPaymentPaystackCallback()
    {
        $payment = Paystack::getPaymentData();
        $business_id = $payment['data']['metadata']['business_id'];
        $package_id = $payment['data']['metadata']['package_id'];
        $gateway = $payment['data']['metadata']['gateway'];
        $payment_transaction_id = $payment['data']['reference'];
        $user_id = $payment['data']['metadata']['user_id'];

        if ($payment['status']) {
            //Add subscription
            $this->_add_subscription($business_id, $package_id, $gateway, $payment_transaction_id, $user_id);

            return redirect()
                ->action('\Modules\Superadmin\Http\Controllers\SubscriptionController@index')
                ->with('status', ['success' => 1, 'msg' => __('lang_v1.success')]);
        } else {
            return redirect()
                ->action('\Modules\Superadmin\Http\Controllers\SubscriptionController@pay', [$package_id])
                ->with('status', ['success' => 0, 'msg' => __('messages.something_went_wrong')]);
        }
    }

    /**
     * Obtain Flutterwave payment information
     *
     * @return response
     */
    public function postFlutterwavePaymentCallback(Request $request)
    {
        $url = "https://api.flutterwave.com/v3/transactions/".$request->get('transaction_id')."/verify";
        $header = [
            "Content-Type: application/json",
            "Authorization: Bearer ".env('FLUTTERWAVE_SECRET_KEY')
        ];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => $header,
        ]);
        $response = curl_exec($curl);
        curl_close($curl);

        $payment = json_decode($response, true);

        if ($payment['status'] == 'success') {
            //Add subscription
            $business_id = $payment['data']['meta']['business_id'];
            $package_id = $payment['data']['meta']['package_id'];
            $gateway = $payment['data']['meta']['gateway'];
            $payment_transaction_id = $payment['data']['tx_ref'];
            $user_id = $payment['data']['meta']['user_id'];

            $this->_add_subscription($business_id, $package_id, $gateway, $payment_transaction_id, $user_id);

            return redirect()
                ->action('\Modules\Superadmin\Http\Controllers\SubscriptionController@index')
                ->with('status', ['success' => 1, 'msg' => __('lang_v1.success')]);
        } else {
            return redirect()
                ->action('\Modules\Superadmin\Http\Controllers\SubscriptionController@pay', [$package_id])
                ->with('status', ['success' => 0, 'msg' => __('messages.something_went_wrong')]);
        }
    }

    /**
     * Show the specified resource.
     * @return Response
     */
    public function show($id)
    {
        if (!auth()->user()->can('superadmin.access_package_subscriptions')) {
            abort(403, 'Unauthorized action.');
        }

        $business_id = request()->session()->get('user.business_id');

        $subscription = Subscription::where('business_id', $business_id)
            ->with(['package', 'created_user', 'business'])
            ->find($id);

        $system_settings = System::getProperties([
            'invoice_business_name',
            'email',
            'invoice_business_landmark',
            'invoice_business_city',
            'invoice_business_zip',
            'invoice_business_state',
            'invoice_business_country'
        ]);
        $system = [];
        foreach ($system_settings as $setting) {
            $system[$setting['key']] = $setting['value'];
        }

        return view('superadmin::subscription.show_subscription_modal')
            ->with(compact('subscription', 'system'));
    }

    /**
     * Retrieves list of all subscriptions for the current business
     *
     * @return \Illuminate\Http\Response
     */
    public function allSubscriptions()
    {
        if (!auth()->user()->can('superadmin.access_package_subscriptions')) {
            abort(403, 'Unauthorized action.');
        }

        $business_id = request()->session()->get('user.business_id');

        $subscriptions = Subscription::where('subscriptions.business_id', $business_id)
            ->leftjoin(
                'packages as P',
                'subscriptions.package_id',
                '=',
                'P.id'
            )
            ->leftjoin(
                'users as U',
                'subscriptions.created_id',
                '=',
                'U.id'
            )
            ->addSelect(
                'P.name as package_name',
                DB::raw("CONCAT(COALESCE(U.surname, ''), ' ', COALESCE(U.first_name, ''), ' ', COALESCE(U.last_name, '')) as created_by"),
                'subscriptions.*'
            );
        return Datatables::of($subscriptions)
            ->editColumn(
                'start_date',
                '@if(!empty($start_date)){{@format_date($start_date)}}@endif'
            )
            ->editColumn(
                'end_date',
                '@if(!empty($end_date)){{@format_date($end_date)}}@endif'
            )
            ->editColumn(
                'trial_end_date',
                '@if(!empty($trial_end_date)){{@format_date($trial_end_date)}}@endif'
            )
            ->editColumn(
                'package_price',
                '<span class="display_currency" data-currency_symbol="true">{{$package_price}}</span>'
            )
            ->editColumn(
                'created_at',
                '@if(!empty($created_at)){{@format_date($created_at)}}@endif'
            )
            ->filterColumn('created_by', function ($query, $keyword) {
                $query->whereRaw("CONCAT(COALESCE(U.surname, ''), ' ', COALESCE(U.first_name, ''), ' ', COALESCE(U.last_name, '')) like ?", ["%{$keyword}%"]);
            })
            ->addColumn('action', function ($row) {
                return '<button type="button" class="btn btn-primary btn-xs btn-modal" data-container=".view_modal" data-href="' . action("\Modules\Superadmin\Http\Controllers\SubscriptionController@show", $row->id) .'" ><i class="fa fa-eye" aria-hidden="true"></i> ' . __("messages.view") . '</button>';
            })
            ->rawColumns(['package_price', 'action'])
            ->make(true);
    }
}
