<?php

namespace Salesloo;

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

/**
 * Request action
 */
class Request
{
    public $data;

    /**
     * construct
     * 
     * set request var from ajax input
     */
    public function __construct()
    {
        $input = file_get_contents("php://input");
        $request = json_decode($input, true);

        $url_params = $_GET;
        if (isset($url_params['q'])) {
            unset($url_params['q']);
        }

        $request = wp_parse_args($url_params, $request);

        if (isset($request['nonce']) && salesloo_verify_nonce($request['nonce'])) {
            $this->data = $request;
        }
    }

    /**
     * checkout page validation
     *
     * @return void
     */
    public function checkout_page_validation()
    {
        $valid = false;

        if (isset($_COOKIE['wp_salesloo_cart'])) {
            $cart_key = sanitize_text_field($_COOKIE['wp_salesloo_cart']);
            $cookie   = json_decode(salesloo_decrypt($cart_key), true);

            if (isset($cookie[0]) && isset($cookie[1])) {
                $valid = true;
            }
        }

        if (false === $valid) {
            $this->data = [];
        }

        return $this;
    }

    /**
     * Getter
     * 
     * handle dynamic var
     */
    public function __get($name)
    {
        if (isset($this->data[$name]))
            return $this->data[$name];

        return false;
    }

    /**
     * setter
     * @param  string $name [description]
     * @return [type]      [description]
     */
    public function __set($name, $value)
    {
        $request = $this->attributes;
        $request[$name] = $value;

        return $request;
    }
}
