<?php

namespace WHMCS\Module\Addon\ProxyCheap\Commands;

use WHMCS\Module\Addon\ProxyCheap\AbstractCommand;
use WHMCS\Database\Capsule as DB;

class AddToWHMCSCart extends AbstractCommand
{
    public function post()
    {
        if (!function_exists("getCustomFields")) {
            require ROOTDIR . "/includes/customfieldfunctions.php";
        }
        if (!function_exists("getCartConfigOptions")) {
            require ROOTDIR . "/includes/configoptionsfunctions.php";
        }

        $pid = $this->input['config']['pid'];

        $customfields = \WHMCS\CustomField::where("type", 'product')->where("relid", $pid)->get()->toArray();

        $co = DB::table('tblproductconfigoptions AS pc')
            ->join('tblproductconfiglinks AS cl', 'cl.gid', '=', 'pc.gid')
            ->where('cl.pid', $pid)
            ->orderBy('pc.order', 'ASC')->orderBy('pc.id', 'ASC')->get(['pc.*'])->toArray();

        $urlparams = ['a=add', 'pid=' . $pid, 'skipconfig=1'];
        foreach ($this->input['api'] as $optionKey => $apiOption) {

            foreach ($customfields as $customfield) {
                if (strpos($customfield['fieldname'], "|")) {
                    $optionname = explode("|", $customfield['fieldname']);
                    $optionname = trim($optionname[0]);
                } else {
                    $optionname = trim($customfield['fieldname']);
                }

                if (strtolower($optionKey) === strtolower($optionname)) {
                    $optionvalue = is_array($apiOption) ? implode('|', $apiOption) : $apiOption;
                    $urlparams[] = 'customfield[' . $customfield['id'] . ']=' . $optionvalue;
                    $breakOuter = true;
                    break;
                }
            }

            if ($breakOuter === true) {
                $breakOuter = false;
                continue;
            }

            foreach ($co as $configurableOption) {
                if (strpos($configurableOption->optionname, "|")) {
                    $optionname = explode("|", $configurableOption->optionname);
                    $optionname = trim($optionname[0]);
                } else {
                    $optionname = trim($configurableOption->optionname);
                }

                if (strtolower($optionKey) === strtolower($optionname)) {
                    $urlparams[] = 'configoption[' . $configurableOption->id . ']=' . $apiOption;
                }
            }
        }

        if ($this->input['config']['billing']) {
            $urlparams[] = 'billingcycle=' . str_replace(["-", " "], "", strtolower($this->input['config']['billing']));
        }

        return ['url' => $urlparams];
    }
}
