<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace ModulesGarden\HostingQuotaNotifications\App\Helper\SmartyHelper;

use ModulesGarden\HostingQuotaNotifications\Core\Models\Whmcs\Client as ClientWHMCS;
use \Illuminate\Database\Capsule\Manager as DB;
use ModulesGarden\HostingQuotaNotifications\Core\Models\Whmcs\CustomField;
use ModulesGarden\HostingQuotaNotifications\Core\Helper;
use ModulesGarden\HostingQuotaNotifications\App\Helper\DBModelsHelper;
use ModulesGarden\HostingQuotaNotifications\App\Helper\CountriesHelper;

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

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

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

        //$db = new MG_SMS_DBWorld();

        $client = ClientWHMCS::where('id', $id)->get()->first();

        $this->data = $client->toArray();

        $this->data['group_name'] = $client->groupid->groupname;

        $model = DB::table('tblinvoices')
                ->select(DB::raw('SUM(total)-COALESCE((SELECT SUM(amountin-amountout) FROM tblaccounts WHERE tblaccounts.invoiceid=tblinvoices.id),0)', "transid"))
                ->where('userid', $this->data['id'])
                ->where('status', 'Unpaid')
                ->first();

        $this->data['balance'] = reset($model);

        $this->data = array_merge($this->data, $this->getCCDetails());

        $model = CustomField::join('tblcustomfieldsvalues', 'tblcustomfieldsvalues.fieldid', '=', 'tblcustomfields.id')
                ->select("tblcustomfields.fieldname AS name", "tblcustomfieldsvalues.value")
                ->where('tblcustomfields.type', 'client')
                ->where('tblcustomfieldsvalues.relid', $this->data['id'])
                ->get()
                ->toArray();

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

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

    private function getCCDetails()
    {
        global $cc_encryption_hash;
        $cchash = md5($cc_encryption_hash . $this->data['id']);

        $model = DB::table('tblclients')
                ->select(
                        "cardtype", "cardlastfour", DB::raw("AES_DECRYPT(cardnum,'{$cchash}') as cardnum"), DB::raw("AES_DECRYPT(expdate, '{$cchash}' ) as expdate"), DB::raw("AES_DECRYPT(issuenumber, '{$cchash}') as issuenumber", DB::raw("AES_DECRYPT(startdate, '{$cchash}') as startdate"), "gatewayid")
                )
                ->where('id', $this->data['id'])
                ->first();
        $data  = (array) $model;

        $data['fullcardnum'] = $data['cardnum'];
        $data['cardnum']     = ($data['cardlastfour'] ? "************" . $data['cardlastfour'] : Helper\sl('lang')->T('nocarddetails'));

        $data['expdate']   = ($data['expdate'] ? substr($data['expdate'], 0, 2) . "/" . substr($data['expdate'], 2, 2) : "");
        $data['startdate'] = ($data['startdate'] ? substr($data['startdate'], 0, 2) . "/" . substr($data['startdate'], 2, 2) : "");
        return $data;
    }

    public function getFormatedData()
    {
        global $currency;

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

        $this->output                 = $this->data;
        $this->output['datecreated']  = fromMySQLDate($this->output['datecreated'], 0, 1);
        $this->output['country_full'] = CountriesHelper::getFullCountryName($this->output['country']);

        //$this->output['password'] = "**********";
        if (DBModelsHelper::getWHMCSConfigValue('NOMD5'))
        {
            $this->output['password'] = decrypt($this->output['password']);
        }
        else
        {
            $this->output['password'] = "**********";
        }

        $this->output['balance']   = formatCurrency($this->output['balance']);
        $this->output['credit']    = formatCurrency($this->output['creadit']);
        $this->output['expdate']   = fromMySQLDate($this->output['expdate'], 0, 1);
        $this->output['startdate'] = fromMySQLDate($this->output['startdate'], 0, 1);

        $this->output['full_name'] = trim($this->output['firstname'] . " " . $this->output['lastname']);
        if ($this->output['companyname'])
        {
            $this->output['full_name'] .= " (" . $this->output['companyname'] . ")";
        }
        return $this->output;
    }

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

//        $formated = reset($formated);
        $fields   = array();

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

        return $fields;
    }

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

    private static function getMergeFieldsMap()
    {
        return array('client_id'                   => 'id',
            'client_name'                 => 'full_name',
            'client_first_name'           => 'firstname',
            'client_last_name'            => 'lastname',
            'client_company_name'         => 'companyname',
            'client_email'                => 'email',
            'client_address1'             => 'address1',
            'client_address2'             => 'address2',
            'client_city'                 => 'city',
            'client_state'                => 'state',
            'client_postcode'             => 'postcode',
            'client_country'              => 'country_full',
            'client_phonenumber'          => 'phonenumber',
            'client_password'             => 'password',
            'client_signup_date'          => 'datecreated',
            'client_credit'               => 'credit',
            'client_cc_type'              => 'cardtype',
            'client_cc_number'            => 'cardnum',
            'client_cc_expiry'            => 'expdate',
            'client_language'             => 'language',
            'client_status'               => 'status',
//            'client_group_id'             => 'groupid',
//            'client_group_name'           => 'group_name',
            'client_gateway_id'           => 'gatewayid',
//            'unsubscribe_url'             => '',
            'client_due_invoices_balance' => 'balance',
//            'client_custom_fields'        => 'customfields',
//            'client_custom_field_name'    => '',
            'client_country_code'         => 'country',
            'clientname'                  => 'full_name',
            'client_hostname'             => 'host',
            'client_ip'                   => 'ip'
        );
    }
}
