<?php

namespace Salesloo\Frontend;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

use \Salesloo\Abstracts\Frontend;


/**
 * Salesloo Payment
 */
class Payment extends Frontend
{

    /**
     * construction
     */
    public function __construct()
    {
        $this->id       = 'payment';
        $this->template = 'payment.php';
        $this->target   = 'both';
        $this->title    = 'Payment';

        $vars = salesloo_vars();

        if (!isset($vars['__invoice'])) wp_redirect(salesloo_get_option('affiliate_general_redirect'));

        $invoice_id = salesloo_decrypt(sanitize_text_field($vars['__invoice']));
        $invoice = new \Salesloo\Invoice($invoice_id);

        if (!$invoice->ID) {
            wp_die('Not Found');
            exit;
        }

        if ($invoice->status == 'cancelled') {
            $this->template = 'payment-cancelled.php';
        }

        /**
         * completed invoice if total amount is lower than 1
         */
        if ($invoice->get_total() <= 0) {
            salesloo_update_invoice_status($invoice->ID, 'completed');
            $redirect = salesloo_url_thanks(salesloo_encrypt($invoice->ID));
            wp_redirect($redirect);
            exit;
        }
    }

    /**
     * handle action process
     */
    public function process_action($req)
    {
        global $___invoice;

        $process = \Salesloo\Invoice::instance()->get_payment_method()->handle_action($___invoice);

        /**
         * renew invoice data
         */
        if ($process) {
            wp_redirect(salesloo_url_payment(salesloo_encrypt($___invoice->ID)));
            exit;
        }
    }


    /**
     * handle load
     */
    public function load()
    {
        global $___salesloo;

        \Salesloo\Invoice::instance()->get_payment_method()->handle_load();
    }
}
