<?php

namespace ModulesGarden\HostingQuotaNotifications\App\Helper\SmartyHelper;

use ModulesGarden\HostingQuotaNotifications\App\Helper\Lang\Lang;
use ModulesGarden\HostingQuotaNotifications\App\Helper\Models\User;
use \ModulesGarden\HostingQuotaNotifications\Core\Helper;
use \Illuminate\Database\Capsule\Manager as DB;
use ModulesGarden\HostingQuotaNotifications\Core\ModuleConstants;

/**
 * Description of Product
 *
 * @author Artur Pilch <artur.pi@modulesgarden.com>
 */
class Product
{
    private $data;
    private $output;

    public function getUserID()
    {
        return $this->data['userid'];
    }

    public function __construct($id)
    {
        
        $this->langHelper = $langHelper;

        $model      = DB::table('tblhosting')
                ->leftJoin('tblproducts', 'tblhosting.packageid', '=', 'tblproducts.id')
                ->select(
                        "tblhosting.*", "tblproducts.name", "tblproducts.description")
                ->where('tblhosting.id', '=', $id)
                ->first();
        
        $this->data = (array) $model;


        $model = DB::table('tblpaymentgateways')
                ->select("tblpaymentgateways.value")
                ->where('setting', 'name')
                ->where('gateway', $this->data['paymentmethod'])
                ->first();

        $this->data['paymentmethodname'] = $model->value;
        $this->data['recuringamount']    = $this->data['amount'];


        $model = DB::table('tblcancelrequests')
                ->select("tblcancelrequests.type", "tblcancelrequests.reason")
                ->where('relid', $id)
                ->orderBy('id', 'desc')
                ->first();
        
        $cancel_request = (array) $model;

        $this->data['canceltype']   = $cancel_request['type'];
        $this->data['cancelreason'] = $cancel_request['reason'];

        if ($this->data['server'])
        {
            $server = DB::table('tblservers')
                    ->where('id', $this->data['server'])
                    ->first();

            $this->data['server_name']     = $server->name;
            $this->data['server_ip']       = $server->ipaddress;
            $this->data['server_hostname'] = $server->hostname;
            $this->data['server_ns1']      = $server->nameserver1;
            $this->data['server_ns2']      = $server->nameserver2;
            $this->data['server_ns3']      = $server->nameserver3;
            $this->data['server_ns4']      = $server->nameserver4;
            $this->data['server_ns1ip']    = $server->nameserver1ip;
            $this->data['server_ns2ip']    = $server->nameserver2ip;
            $this->data['server_ns3ip']    = $server->nameserver3ip;
            $this->data['server_ns4ip']    = $server->nameserver4ip;
        }
        
        $cycle                        = preg_replace("/[^a-z]/i", "", strtolower($this->data['billingcycle']));
        if ($cycle == "free account")
            $cycle                        = "monthly";
        $this->data['billingcycledb'] = str_replace("lly", "l", $cycle);



        $model = DB::table('tblhostingconfigoptions')
                ->join('tblproductconfigoptions', 'tblproductconfigoptions.id', '=', 'tblhostingconfigoptions.configid')
                ->join('tblproductconfigoptionssub', 'tblproductconfigoptionssub.id', '=', 'tblhostingconfigoptions.optionid')
                ->join('tblhosting', 'tblhosting.id', '=', 'tblhostingconfigoptions.relid')
                ->join('tblproductconfiglinks', 'tblproductconfiglinks.gid', '=', 'tblproductconfigoptions.gid')
                ->select("tblproductconfigoptions.id", "tblproductconfigoptions.optionname AS confoption", "tblproductconfigoptions.optiontype AS conftype", "tblproductconfigoptionssub.optionname", "tblhostingconfigoptions.qty")
                ->where('tblhostingconfigoptions.relid', $this->data['id'])
                ->where('tblproductconfiglinks.pid', 'tblhosting.packageid')
                ->orderBy('tblproductconfigoptions.id', 'ASC')
                ->first();

        $this->data['configoptions'] = (array) $model;

        foreach ($this->data['configoptions'] as &$option)
        {
            if (strpos($option['confoption'], "|"))
            {
                $option['confoption'] = explode("|", $option['confoption']);
                $option['option']     = trim($option['confoption'][1]);
            }

            if (strpos($option['optionname'], "|"))
            {
                $option['optionname'] = explode("|", $option['optionname']);
                $option['value']      = trim($option['optionname'][1]);
            }
            $option['type']      = $option['conftype'];
            $option['setup']     = "";
            $option['recurring'] = "";
        }

        $this->data['password'] = decrypt($this->data['password']);

        $model = DB::table('tblcustomfields')
                ->join('tblcustomfieldsvalues', 'tblcustomfieldsvalues.fieldid', '=', 'tblcustomfields.id')
                ->select("tblcustomfields.fieldname AS name", "tblcustomfieldsvalues.value")
                ->where('tblcustomfields.type', 'product')
                ->where('tblcustomfields.relid', $this->data['packageid'])
                ->where('tblcustomfieldsvalues.relid', $this->data['id'])
                ->first();

        $this->data['customfields'] = (array) $model;

        foreach ($this->data['customfields'] as $field)
        {
            $name                               = preg_replace("/[^0-9a-z]/", "", strtolower($field['name']));
            $this->data['customfield_' . $name] = $field['value'];
        }

    }

    public function getFormatedData()
    {
        global $currency;

        $lang        = Helper\sl('lang');

        $currency     = getCurrency($this->data['userid']);
        $this->output = $this->data;

        $this->output['assignedips'] = $this->output['assignedips']; //nl2br
        $this->output['regdate']     = fromMySQLDate($this->output['regdate'], 0, 1);
        if ($this->output['nextduedate'] != "-")
            $this->output['nextduedate'] = fromMySQLDate($this->output['nextduedate'], 0, 1);

        if (strtolower($this->output['domainstatus']) == "suspended" && !$this->output['suspendreason'])
            $this->output['suspendreason'] = $lang->T('suspendreasonoverdue');

        $this->output['domainstatus'] = $lang->T("clientarea" . strtolower(str_replace(" ", "", $this->output['domainstatus'])));

        $this->output['canceltype']   = $lang->T("clientareacancellation" . strtolower(str_replace(" ", "", $this->output['canceltype'])));

        $l                            = preg_replace("/[^a-z]/i", "", strtolower($this->output['billingcycle']));
        $this->output['billingcycle'] = $lang->T("orderpaymentterm" . $l);

        foreach ($this->output['configoptions'] as &$option)
        {
            if ($option['type'] == 3)
            {
                if ($option['qty'])
                    $option['value'] = $lang->T(['yes']);
                else
                    $option['value'] = $lang->T(['no']);
            } else
            {
                if ($option['type'] == 4)
                    $option['value'] = "" . $option['qty'] . " x " . $option['value'];
            }
        }

        if ($this->output['ns1'] != "")
        {
            $this->output['ns1'] = $this->output['ns1'];
            $this->output['ns2'] = $this->output['ns2'];
            $this->output['ns3'] = "";
            $this->output['ns4'] = "";
        }
        else
        {
            $this->output['ns1'] = $this->output['server_ns1'];
            $this->output['ns2'] = $this->output['server_ns2'];
            $this->output['ns3'] = $this->output['server_ns3'];
            $this->output['ns4'] = $this->output['server_ns4'];
        }

        $this->output['firstpaymentamount'] = formatCurrency($this->output['firstpaymentamount']);
        $this->output['recuringamount']     = formatCurrency($this->output['recuringamount']);
        $this->output['amount']             = formatCurrency($this->output['amount']);

        return $this->output;
    }

    public function getMergeFields()
    {
        $map      = self::getMergeFieldsMap();
        $formated = $this->getFormatedData();
        $fields   = array();

        foreach ($map as $k => $v)
            $fields[$k] = $formated[$v];

        foreach ($formated['customfields'] as $field)
        {
            $name                                    = preg_replace("/[^0-9a-z]/", "", strtolower($field['name']));
            $fields['service_custom_field_' . $name] = $field['value'];
        }

        return $fields;
    }

    public static function getMergeFieldsNames()
    {
        return array_keys(self::getMergeFieldsMap());
    }

    private static function getMergeFieldsMap()
    {
        return [
            'service_order_id'             => 'orderid',
            'service_id'                   => 'id',
            'service_reg_date'             => 'regdate',
            'service_product_name'         => 'name',
            'service_product'              => 'name',
            'service_product_description'  => 'description',
//            'service_config_options'       => 'configoptions',
//            'service_config_options_html'  => '',
            'service_domain'               => 'domain',
            'service_server_name'          => 'server_name',
            'service_server_hostname'      => 'server_hostname',
            'service_server_ip'            => 'server_ip',
            'service_dedicated_ip'         => 'dedicatedip',
            'service_assigned_ips'         => 'assignedips',
            'service_ns1'                  => 'ns1',
            'service_ns2'                  => 'ns2',
            'service_ns3'                  => 'ns3',
            'service_ns4'                  => 'ns4',
            'service_ns1_ip'               => 'server_ns1ip',
            'service_ns2_ip'               => 'server_ns2ip',
            'service_ns3_ip'               => 'server_ns3ip',
            'service_ns4_ip'               => 'server_ns4ip',
            'service_payment_method'       => 'paymentmethodname',
            'service_first_payment_amount' => 'firstpaymentamount',
            'service_recurring_amount'     => 'recuringamount',
//            'service_billing_cycle'        => 'billingcycle',
            'service_next_due_date'        => 'nextduedate',
            'service_status'               => 'domainstatus',
            'service_username'             => 'username',
            'service_password'             => 'password',
            'service_subscription_id'      => 'subscriptionid',
            'service_suspension_reason'    => 'suspendreason',
            'service_cancellation_type'    => 'canceltype',
//            'service_custom_fields'        => 'customfields',
//            'service_custom_field_xyz'     => '',
            'product_name'                 => 'name',
            'service_cancellation_reason'  => 'cancelreason'
        ];
    }
}
