HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/qas.sports-crowd.com/app/Http/Controllers/PaymentGatewayController.php
<?php

namespace App\Http\Controllers;

use App\Core\CorporateIdentity\Application\CorporateIdentityService;
use App\Core\Experience\Domain\ValueObjects\ExperiencePaymentStatusEnum;
use App\Core\Parameter\Application\ParameterService;
use App\Core\Payment\PaymentServicesEnum;
use App\Core\Payment\PaymentStatusEnum;
use App\Core\Ticket\Application\TicketService;
use App\GatewayPayment;
use App\Models\Experience\ExperiencePayment;
use App\Parameter;
use App\Services\ExperienceService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use DataTables;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;

class PaymentGatewayController extends Controller
{
    protected $util;
    protected $ticketService;
    protected $experienceService;
    protected $parameterService;

    public function __construct()
    {
        $this->util = new UtilController();
        $this->ticketService = new TicketService();
        $this->experienceService = new ExperienceService();
        $this->parameterService = new ParameterService();
    }

    public function index()
    {
        $enable_payment_gateway_authorizing_email = $this->parameterService->getEnablePaymentGatewayAuthorizingEmail();
        $payment_gateway_authorizing_email = $this->parameterService->getPaymentGatewayAuthorizingEmail();
        $corporateIdentity = CorporateIdentityService::get();
        return view('paymentGateway.list', compact('enable_payment_gateway_authorizing_email', 'payment_gateway_authorizing_email', 'corporateIdentity'));
    }

    public function create()
    {
        $corporateIdentity = CorporateIdentityService::get();
        return view('paymentGateway.create')->with('types', PaymentServicesEnum::ALLOWED_VALUES)->with('corporateIdentity', $corporateIdentity);
    }

    public function selection($type, $paymentObjectId)
    {
        $request = new Request([
            'type' => $type
        ]);
        $gateways = json_decode($this->getActived($request)->getContent())->data;

        $corporateIdentity = CorporateIdentityService::get();
        $urlComplement = '';
        $paymentDetails = [];
        try {
            $paymentObjectId = Crypt::decrypt($paymentObjectId);
        } catch (\Exception $e) {
            return $this->paymentInvalidResponse();
        }

        switch ($type) {
            case 'ticket':
                $urlComplement = '&ticketId=' . $paymentObjectId . '&appOrigin=ticket';

                $payment = $this->ticketService->find($paymentObjectId);
                if (!$payment) {
                    return $this->paymentNotFoundResponse();
                } else if (Carbon::parse($payment->created_at)->addMinutes(30) < now()) {
                    return $this->paymentExpiredResponse();
                } else if ($payment->payment_state == PaymentStatusEnum::CONFIRMED) {
                    return $this->paymentConfirmedResponse();
                }

                $paymentDetails = [
                    'return_page' => '/web_ticketing',
                    'duration' => Carbon::parse($payment->created_at)->addMinutes(30)->diffInSeconds(now()),
                    'title' => 'Compra de boleterĂ­a',
                    'plan' => 'Boletas ' . (count($payment->ticket_user_blocks) > 0 ? $payment->ticket_user_blocks[0]->match_event->name : ''),
                    'amount' => count($payment->ticket_user_blocks) ?? 0,
                    'date' => count($payment->ticket_user_blocks) > 0 ? $payment->ticket_user_blocks[0]->match_event->event_start : '',
                    'location' => count($payment->ticket_user_blocks) > 0 ? $payment->ticket_user_blocks[0]->match_event->stadium_to_play : '',
                    'price' => $payment->subtotal ?? 0,
                    'discount' => $payment->discount ?? 0,
                    'subtotal' => $payment->subtotal ?? 0,
                    'serviceCharge' => $payment->service_charge ?? 0,
                    'total' => $payment->total ?? 0,
                ];
                $paymentDetails = json_decode(json_encode($paymentDetails));

                break;
            case 'experience':
                $urlComplement = '&experiencePaymentId=' . $paymentObjectId . '&appOrigin=experience';

                $payment = $this->experienceService->findExperiencePayment($paymentObjectId);
                if (!$payment) {
                    return $this->paymentNotFoundResponse();
                } else if (Carbon::parse($payment->created_at)->addMinutes(30) < now() || $payment->status == ExperiencePaymentStatusEnum::EXPIRED) {
                    return $this->paymentExpiredResponse();
                } else if ($payment->status == ExperiencePaymentStatusEnum::CONFIRMED) {
                    return $this->paymentConfirmedResponse();
                }

                $paymentDetails = [
                    'return_page' => '/web_experiences',
                    'duration' => Carbon::parse($payment->created_at)->addMinutes(30)->diffInSeconds(now()),
                    'title' => $payment->experience_plan_price->plan->experience->name,
                    'plan' => $payment->experience_plan_price->plan->name,
                    'amount' => $payment->amount ?? 0,
                    'date' => $payment->experience_plan_price->plan->experience->start_datetime,
                    'location' => $payment->experience_plan_price->plan->experience->event_place,
                    'price' => $payment->price ?? 0,
                    'discount' => $payment->discount ?? 0,
                    'subtotal' => $payment->subtotal ?? 0,
                    'serviceCharge' => $payment->service_charge ?? 0,
                    'total' => $payment->total ?? 0,
                ];
                $paymentDetails = json_decode(json_encode($paymentDetails));

                break;
        }

        return view('paymentGateway.pay.index', compact('gateways', 'corporateIdentity', 'urlComplement', 'paymentDetails'));
    }

    public function tableFilter()
    {
        $obj = GatewayPayment::select('id', 'name', 'description', 'gw_url_prd', 'gw_url_sandbox', 'is_productive', 'active', 'image', 'valid_payments')->orderBy('id', 'DESC');

        return DataTables::of($obj)
            ->addColumn('actions', function ($obj) {
                return '
                    <i class="fa fa-pencil iconMini" onClick="clickEdit(' . $obj->id . ')" data-id="' . $obj->id . '" data-toggle="tooltip" data-placement="bottom" title="Editar"  style="cursor:pointer;"></i>
                    <i class="fa fa-trash iconMini" onClick="clickDelete(' . $obj->id . ')" data-id="' . $obj->id . '" data-toggle="tooltip" data-placement="bottom"  style="cursor:pointer;"></i>
                ';
            })
            ->editColumn('active', function ($obj) {
                if ($obj->active == 0) {
                    return '<div class="switch"><label><div class="checkbox checbox-switch switch-success"> <label> ' . __('messages.no') . ' <input type="checkbox" onChange="chk(' . $obj->id . ')" data-id="' . $obj->id . '" id="Checkactive' . $obj->id . '" name="Checkactivo" /> <span></span>' . __('messages.yes') . ' </label></div> </label> </div>';
                } else {
                    return '<div class="switch"><label> <div class="checkbox checbox-switch switch-success"> <label>   ' . __('messages.no') . ' <input type="checkbox" onChange="chk(' . $obj->id . ')" data-id="' . $obj->id . '" id="Checkactive' . $obj->id . '" name="Checkactivo" checked="" />
                        <span></span> ' . __('messages.yes') . ' </label> </div>  </label> </div>';
                }
            })
            ->editColumn('is_productive', function ($obj) {
                if ($obj->is_productive == 0) {
                    return '<div class="switch"><label><div class="checkbox checbox-switch switch-success"> <label> ' . __('messages.no') . ' <input type="checkbox" onChange="chkIsProductive(' . $obj->id . ')" data-id="' . $obj->id . '" id="chkIsProductive' . $obj->id . '" name="chkIsProductive" /> <span></span>' . __('messages.yes') . ' </label></div> </label> </div>';
                } else {
                    return '<div class="switch"><label> <div class="checkbox checbox-switch switch-success"> <label>   ' . __('messages.no') . ' <input type="checkbox" onChange="chkIsProductive(' . $obj->id . ')" data-id="' . $obj->id . '" id="chkIsProductive' . $obj->id . '" name="chkIsProductive" checked="" />
                        <span></span> ' . __('messages.yes') . ' </label> </div>  </label> </div>';
                }
            })
            ->editColumn('valid_payments', function ($obj) {
                $valid_payments = [];
                if ($obj->valid_payments) {
                    foreach (explode(',', $obj->valid_payments) as $item) {
                        $object = collect(PaymentServicesEnum::ALLOWED_VALUES)->where('value', $item)->first();
                        if ($object)
                            $valid_payments[] = $object['name'];
                    }
                }
                return implode(',', $valid_payments);
            })
            ->editColumn('image', function ($obj) {
                if (!$obj->image) {
                    return $this->util->generateEmptyImageColumn();
                } else {
                    $image = str_contains($obj->image, 'http') ? $obj->image : config('filesystems.disks.s3.url') . '/paymentGateway/' . $obj->image;
                    return $this->util->generateImageColumn($image, $obj->name, 'paymentGateway' . $obj->id);
                }
            })
            ->rawColumns(['actions', 'is_productive', 'active', 'image'])
            ->make(true);
    }

    public function store(Request $request)
    {
        try {
            if (GatewayPayment::where([['name', $request->input('name')], ['client_public', $request->input('client_public')]])->first()) {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.already_exists', ['name' => $request->input('tag')]), "data" => null));
            }
            if ($model = GatewayPayment::create($request->all())) {
                $this->registerLog(Auth::user()->id, 'Crear pasarela de pago', json_encode($request->all()), "Create", $this->getModule($request));
                return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.created_successfully'), "data" => $model->id));
            } else {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_creating'), "data" => null));
            }
        } catch (\Exception $e) {
            return response(
                array(
                    "r" => false,
                    "type" => "error",
                    "title" => "Oops...",
                    "m" => __($e->getMessage()),
                    "data" => null
                )
            );
        }
    }

    public function edit($id)
    {
        $paymentGateway = GatewayPayment::findOrFail($id);
        $corporateIdentity = CorporateIdentityService::get();
        return view('paymentGateway.edit', compact('paymentGateway'))->with('types', PaymentServicesEnum::ALLOWED_VALUES)->with('corporateIdentity', $corporateIdentity);
    }

    public function update(Request $request, $id)
    {
        try {
            $request['id'] = $id;
            if (GatewayPayment::where([['id', '!=', $id], ['name', $request->input('name')], ['client_public', $request->input('client_public')]])->first()) {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.already_exists', ['name' => $request->input('name')]), "data" => null));
            }
            if (GatewayPayment::where('id', $id)->update($request->all())) {
                $this->registerLog(Auth::user()->id, 'Actualizar pasarela de pago', json_encode($request->all()), "Update", $this->getModule($request));
                return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.updated_successfully'), "data" => $id));
            } else {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_updating'), "data" => null));
            }
        } catch (\Exception $e) {
            return response(
                array(
                    "r" => false,
                    "type" => "error",
                    "title" => "Oops...",
                    "m" => __($e->getMessage()),
                    "data" => null
                )
            );
        }
    }

    public function destroy(Request $request, $id)
    {
        try {
            $gateway = GatewayPayment::findOrFail($id);
            if (GatewayPayment::where('id', $id)->delete()) {
                $this->registerLog(Auth::user()->id, 'Eliminar pasarela de pago', json_encode($gateway), "Delete", $this->getModule($request));
                return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.deleted_successfully'), "data" => null));
            } else {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_removing'), "data" => null));
            }
        } catch (\Illuminate\Database\QueryException $e) {
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.delete_relation_data'), "data" => null));
        }
    }

    public function activate(Request $request)
    {
        try {
            $id = $request['id'];
            $state = $request['state'];

            $gateway = GatewayPayment::find($id);
            $gateway->active = $state;
            $gateway->update();

            $this->registerLog(Auth::user()->id, 'Activar/Desactivar pasarela de pago', json_encode($gateway), "Update", $this->getModule($request));
            return array('r' => true, 'd' => null, 'm' => __('messages.updated_successfully'));
        } catch (\Throwable $th) {
            return array('r' => false, 'd' => null, 'm' => __('messages.error_updating'));
        }
    }

    public function isProductive(Request $request)
    {
        try {
            $id = $request['id'];
            $state = $request['state'];

            $gateway = GatewayPayment::find($id);
            $gateway->is_productive = $state;
            $gateway->update();

            $this->registerLog(Auth::user()->id, 'Productivo/Prueba pasarela de pago', json_encode($gateway), "Update", $this->getModule($request));
            return array('r' => true, 'd' => null, 'm' => __('messages.updated_successfully'));
        } catch (\Throwable $th) {
            return array('r' => false, 'd' => null, 'm' => __('messages.error_updating'));
        }
    }

    public function getById($id)
    {
        return GatewayPayment::find($id);
    }

    public function saveImage(Request $request)
    {
        try {
            $extension = $request->file('image')->getClientOriginalExtension();
            $filenametostore = $request->id . '.' . $extension;

            Storage::disk('s3')->put(config('s3.paymentGateway') . $filenametostore, fopen($request->file('image'), 'r+'), 'public');

            $gateway = GatewayPayment::find($request->id);
            $gateway->image = $filenametostore;
            $gateway->update();

            return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.updated_successfully'), "data" => null));
        } catch (\Throwable $th) {
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_updating'), "data" => $th->getMessage()));
        }
    }

    public function getActived(Request $request)
    {
        $type = $request->type;
        $gateway = $request->gateway;
        $collection = new CollectionInvoiceController();
        $availableCollectionInvoice = $collection->validateAvailableCollectionInvoice($type);
        if ($availableCollectionInvoice) {
            return response(array(
                "status" => true,
                "type" => "success",
                "title" => "ok",
                "message" => "",
                "data" => $availableCollectionInvoice
            ));
        }

        $query = GatewayPayment::query();

        if ($gateway && $gateway != 'undefined' && $gateway != 'null') {
            return response(array(
                "status" => true,
                "type" => "success",
                "title" => "ok",
                "message" => "",
                "data" => $query->select('id', 'name', 'image')->where('id', $gateway)->get()
            ));
        }

        if ($type == 'experience') {
            if ($request->has('paymentData') && isset($request->paymentData['experiencePaymentId'])) {
                $experiencePayment = ExperiencePayment::findOrFail($request->paymentData['experiencePaymentId']);
                $experience = $experiencePayment->experience_plan_price->plan->experience;

                if ($experience->paymentGateways->isNotEmpty()) {
                    $paymentGateways = $experience->paymentGateways->map(function ($paymentGateway) {
                        return $paymentGateway->id;
                    });
                    $query->whereIn('id', $paymentGateways);
                }
            }
        }

        $query->select('id', 'name', 'image');
        $query->where('active', true);
        $query->whereRaw('image IS NOT NULL');
        if (isset($type)) {
            $query->where(function ($q) use ($type) {
                $q->whereRaw("CONCAT(',', valid_payments, ',') LIKE ?", ["%,all,%"])
                    ->orWhereRaw("CONCAT(',', valid_payments, ',') LIKE ?", ["%,{$type},%"]);
            });
        }
        $parameters = Parameter::select('is_production_gateway')->first();
        $is_production = $parameters->is_production_gateway; // TRUE: Production ; FALSE: Test
        $query->where('is_productive', $is_production);

        return response(array(
            "status" => true,
            "type" => "success",
            "title" => "ok",
            "message" => "",
            "data" => $query->get()
        ));
    }

    public function paymentsValidator()
    {
        return view('payments.payments_validator');
    }

    private function paymentInvalidResponse()
    {
        return response()->view('paymentGateway.pay.error', ['code' => 404, 'error' => 'Pago inválido']);
    }

    private function paymentNotFoundResponse()
    {
        return response()->view('paymentGateway.pay.error', ['code' => 404, 'error' => 'Pago no encontrado']);
    }

    private function paymentExpiredResponse()
    {
        return response()->view('paymentGateway.pay.error', ['code' => 404, 'error' => 'Pago ha expirado']);
    }

    private function paymentConfirmedResponse()
    {
        return response()->view('paymentGateway.pay.error', ['code' => 200, 'error' => 'Pago ya confirmado']);
    }
}