<?php

namespace Salesloo\Frontend;

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

use \Salesloo\Abstracts\Frontend;
use \Salesloo\Response;

/**
 * Salesloo Renew Order
 */
class Renew extends Frontend
{
    /**
     * construction
     */
    public function __construct()
    {

        $this->id       = 'renew';
        $this->template = 'renew.php';
        $this->target   = 'both';
        $this->title    = 'Renew Access';

        $order_id = salesloo_get_current_order_id();
        $order = salesloo_get_order($order_id);

        if (!is_user_logged_in()) {
            wp_redirect(salesloo_url_login());
            exit;
            //wp_die(__('Please logged in to view this page', 'salesloo'));
        }

        if (!$order) {
            wp_die('Ups, Invalid order and please contact admin');
        }

        if ($order->user_id != get_current_user_id()) {
            wp_die('Ups, Invalid access');
        }

        \Salesloo\Renew::instance()->prepare($order_id);

        $is_invoice_exists = \Salesloo\Renew::instance()->invoice_exists();
        if ($is_invoice_exists) {
            wp_redirect(salesloo_url_payment(salesloo_encrypt($is_invoice_exists)));
            exit;
        }
    }


    /**
     * process_action
     *
     * @return void
     */
    public function process_action($req)
    {

        if ($req->action == 'summary') {
            $summary = \Salesloo\Renew::instance()->summary();
            $filtered_summary = $summary;
            unset($filtered_summary['products']);
            unset($filtered_summary['total']);

            $res = [
                'summaries' => $filtered_summary,
                'total' => $summary['total']
            ];
            wp_send_json($res);
        }

        if ($req->action == 'choose_payment_method') {
            $updated = \Salesloo\Renew::instance()->choose_payment_method($req->method);
            if (is_wp_error($updated)) {
                wp_send_json(['message' => $updated->get_error_message()], 400);
            } else {
                wp_send_json(['message' => 'OK'], 200);
            }
        }

        \Salesloo\Renew::instance()->order();
    }



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

        if (empty(\Salesloo\Plugin::instance()->payment_method->active())) {
            wp_die('No Payments methods enabled, Please contact admin');
        }
    }
}
