<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Niubiz_paylink_gateway extends App_gateway
{
    public function __construct()
    {
        parent::__construct();

        $this->ci = &get_instance();

        $this->setId('niubiz_paylink');
        $this->setName('Niubiz Pago Link');

        $this->setSettings([
            [
                'name'          => 'niubiz_paylink_url',
                'label'         => 'Niubiz Pago Link URL',
                'type'          => 'input',
                'default_value' => '',
            ],
            [
                'name'          => 'description_dashboard',
                'label'         => 'settings_paymentmethod_description',
                'type'          => 'textarea',
                'default_value' => 'Pago de factura {invoice_number} mediante Niubiz Pago Link',
            ],
            [
                'name'          => 'currencies',
                'label'         => 'settings_paymentmethod_currencies',
                'default_value' => 'PEN,USD',
            ],
            [
                'name'          => 'instructions',
                'label'         => 'Instrucciones para el cliente',
                'type'          => 'textarea',
                'default_value' => 'Será redirigido a la plataforma segura de Niubiz. Ingrese el monto exacto de su factura y envíe su comprobante para validación administrativa.',
            ],
        ]);
    }

    public function process_payment($data)
    {
        $invoice = $data['invoice'];

        $paylink = trim($this->getSetting('niubiz_paylink_url'));

        if (empty($paylink)) {
            set_alert('danger', 'Niubiz Pago Link no está configurado. Agregue la URL del Pago Link en Settings > Payment Gateways.');
            redirect(site_url('invoice/' . $invoice->id . '/' . $invoice->hash));
        }

        $separator = strpos($paylink, '?') === false ? '?' : '&';

        $invoice_number = isset($invoice->number) ? $invoice->number : $invoice->id;
        $amount         = isset($data['amount']) ? $data['amount'] : $invoice->total;

        $redirect_url = $paylink . $separator . http_build_query([
            'invoice_id'     => $invoice->id,
            'invoice_number' => $invoice_number,
            'amount'         => $amount,
        ]);

        redirect($redirect_url);
    }

    public function get_action_url()
    {
        return '';
    }
}