<?php
use Illuminate\Database\Capsule\Manager as Capsule;

require_once 'modules/billing/models/Currency.php';

/**
 * Clients in Credit Report
 *
 * @category Report
 * @package  ClientExec
 * @author   Juan D. Bolivar <juan@clientexec.com>
 * @license  ClientExec License
 * @version  1.0
 * @link     http://www.clientexec.com
 *
 *************************************************
 *   1.0 Initial Report Released.  - Juan D. Bolivar
 ************************************************
 */

/**
 * Clients_In_Credit Report Class
 *
 * @category Report
 * @package  ClientExec
 * @author   Juan D. Bolivar <juan@clientexec.com>
 * @license  ClientExec License
 * @version  1.0
 * @link     http://www.clientexec.com
 */
class Clients_In_Credit extends Report
{
    private $lang;

    protected $featureSet = 'accounts';

    function __construct($user = null, $customer = null)
    {
        $this->lang = lang('Clients in Credit');
        parent::__construct($user, $customer);
    }

    /**
     * Report Process Method
     *
     * @return null - direct output
     */
    function process()
    {
        $this->SetDescription($this->user->lang('Displays a list of clients with the amount of credit balance they have.'));

        // Load the currency information
        $currency = new Currency($this->user);

        $currencyCode = ((isset($_REQUEST['currencycode']))? $_REQUEST['currencycode'] : $this->settings->get('Default Currency'));
        $currencyName = $currency->getName($currencyCode);

        $filter = '<form id="report" method="GET">'
            .'    <div style="text-align:center">'
            .'        '.$this->user->lang('Currency').': '
            .'        <select name="currencycode" class="normalSelect2 w-20" id="currencycode" value="'.CE_Lib::viewEscape($currencyCode).'" onChange="ChangeTable(this.value);"> ';

        $isSelectedCurrencyInTheList = false;

        //Get all currencies of all clients with positive balance
        $result = Capsule::table('users as u')
            ->join('currency as c', 'c.abrv', '=', 'u.currency')
            ->select('c.abrv', 'c.name')
            ->where('u.balance', '>', 0)
            ->distinct()
            ->orderBy('c.name', 'ASC')
            ->get();

        foreach ($result as $row) {
            if (!$isSelectedCurrencyInTheList && $currencyName < $row->name) {
                $filter .= '<option value="'.$currencyCode.'" selected>'.$currencyName.'</option>';
                $isSelectedCurrencyInTheList = true;
            } elseif ($currencyCode == $row->abrv) {
                $isSelectedCurrencyInTheList = true;
            }

            $filter .= '<option value="'.$row->abrv.'" '.(($currencyCode == $row->abrv)? 'selected' : '').'>'.$row->name.'</option>';
        }

        if (!$isSelectedCurrencyInTheList) {
            $filter .= '<option value="'.$currencyCode.'" selected>'.$currencyName.'</option>';
            $isSelectedCurrencyInTheList = true;
        }

        $filter .= '</select>';
        $filter .= '    </div>'
            .'</form>'
            .'</br>'
            .'<script type="text/javascript">'
            .'    function ChangeTable(currencycode){'
            .'        location.href="index.php?fuse=reports&view=viewreport&controller=index&report=Clients+In+Credit&type=Accounts&currencycode="+currencycode;'
            .'    }'
            .'</script>';
        echo $filter;

        $totalCredit = 0;

        //SQL to generate the the result set of the report
        $result = Capsule::table('users as u')
            ->select('u.id')
            ->where('u.balance', '>', 0)
            ->where('u.currency', $currencyCode)
            ->orderBy('u.balance', 'DESC')
            ->get();

        foreach ($result as $row) {
            $user = new User($row->id);
            $CustomerLink = "<a href=\"index.php?fuse=clients&controller=userprofile&frmClientID=" . $row->id . "&view=credithistoryview\" target=blank>" . CE_Lib::viewEscape($user->getFullName()) . "</a>";
            $aGroup[] = array($CustomerLink, $user->getFormatedCreditBalance());
            $totalCredit += $user->getCreditBalance();
        }

        $currency = new Currency($this->user);
        $aGroup[] = array('<b>'.$this->user->lang('Total').'</b>', '<b>'.$currency->format($currencyCode, $totalCredit, true, 'NONE', true).'</b>');

        if (isset($aGroup)) {
            $this->reportData[] = array(
                "group"     => $aGroup,
                "groupname" => $this->user->lang('Clients in Credit').' ('.$currencyCode.')',
                "label"     => array($this->user->lang('Client'), $this->user->lang('Credit')),
                "groupId"   => "",
                "isHidden"  => false
            );

            unset($aGroup);
        }
    }
}
