<?php

use WHMCS\Application;
use WHMCS\Billing\Currency;
use WHMCS\Config\Setting;
use WHMCS\Exception\ProgramExit;
use WHMCS\Product\Product;
use WHMCS\Session;
use WHMCS\User\Client;
use WHMCS\Database\Capsule;

require("../init.php");

/*
*** USAGE SAMPLES ***

<script language="javascript" src="feeds/productsinfo.php?pid=1&get=name"></script>

<script language="javascript" src="feeds/productsinfo.php?pid=1&get=description"></script>

<script language="javascript" src="feeds/productsinfo.php?pid=1&get=price&billingcycle=monthly&currency=1"></script>

<script language="javascript" src="feeds/productsinfo.php?pid=1&get=orderurl&carttpl=web20cart"></script>

*/

$whmcs = App::self();
$pid = (int) $whmcs->get_req_var('pid');
$get = $whmcs->get_req_var('get');
$language = $whmcs->get_req_var('language') ?: null;
$data = array();
$name = $description = '';

// Verify user input for pid exists, is greater than 0, and as is a valid id
if ($pid > 0) {
    $data = Capsule::table('tblproducts')
        ->where('id', '=', $pid)
        ->first();
    $pid = null;
    if (is_object($data)) {
        $pid = (int) $data->id;
        // If there is a user logged in, we will use the client language
        $userId = (int) Session::get('userid');
        if (!empty($userId)) {
            $language = Client::find($userId, array('language'))->language ?: null;
        }
        unset($userId);
        $name = Product::getProductName($pid, $data->name, $language);
        $description = Product::getProductDescription($pid, $data->description, $language);
    }
}

if (empty($pid)) {
    widgetOutput('Product ID Not Found');
}

if ($get=="name") {
    widgetOutput($name);
} elseif ($get=="description") {
    $description = str_replace(array("\r", "\n", "\r\n"), "", nl2br($description));
    widgetOutput($description);
} elseif ($get=="configoption") {
    $configOptionNum = $whmcs->get_req_var('configoptionnum');
    if (!$configOptionNum) {
        widgetOutput('The variable configoptionnum is required when get is configoption.');
    }
    widgetoutput($data['configoption' . (int) $configOptionNum]);
} elseif ($get=="orderurl") {
    $cartTemplate = $whmcs->get_req_var('carttpl');
    if ($cartTemplate == "ajax") {
        $cartTemplate = "ajaxcart";
    }
    $systemUrl = App::getSystemUrl();
    if (!$cartTemplate) {
        $cartTemplate = Setting::getValue('OrderFormTemplate ');
    }
    widgetOutput("{$systemUrl}cart.php?a=add&pid={$pid}&carttpl={$cartTemplate}");
} elseif ($get=="price") {
    // Verify user input for currency exists, is numeric, and as is a valid id
    $billingCycle = $whmcs->get_req_var('billingcycle');
    $currencyID = $whmcs->get_req_var('currency');
    if (!is_numeric($currencyID)) {
        $currency = array();
    } else {
        $currency = getCurrency(null, $currencyID);
    }

    if (!$currency || !is_array($currency) || !isset($currency['id'])) {
        $currency = Currency::factoryForClientArea();
    }
    $currencyID = $currency['id'];

    $data = Capsule::table('tblpricing')
        ->where('type', '=', 'product')
        ->where('currency', '=', $currencyID)
        ->where('relid', '=', $pid)
        ->first();
    $price = $data->$billingCycle;
    $price = formatCurrency($price);
    widgetOutput($price);
} else {
    widgetOutput('Invalid get option. Valid options are "name", "description", "configoption", "orderurl" or "price"');
}

/**
 * The function to output the widget data to the browser in a javascript format.
 *
 * @throws WHMCS\Exception\ProgramExit
 * @param string $value the data to output
 */
function widgetOutput($value) {
    echo "document.write('".addslashes($value)."');";
    throw new ProgramExit();
}
