<?php

class Am_Report_Selfservice extends Am_Report_Date
{

    public function __construct()
    {
        $this->title = ___('Credits spent by products breakdown');
    }

    public function getPointField()
    {
        return 'h.dattm';
    }

    public function _initConfigForm(Am_Form $form)
    {
        parent::_initConfigForm($form);
        $sel = $form->addMagicSelect('products')->setLabel(___("Products\nkeep empty to report all products"));
        $sel->loadOptions($this->getAllProducts());
    }

    /** @return Am_Query */
    public function getQuery()
    {
        $q = new Am_Query($this->getDi()->selfserviceHistoryTable, 'h');
        $q->clearFields();
        foreach ($this->getProducts() as $id => $title) {
            $q->addField("-1 * SUM(IF(record_id=$id, value, 0))", 'sum_' . $id);
        }
        $q->addWhere('record_type=?', 'debit');
        $q->addWhere('?#=?', 'table', 'product');
        return $q;
    }

    function getAllProducts()
    {
        return $this->getDi()->db->selectCol("SELECT p.product_id as ARRAY_KEY, CONCAT('(', p.product_id, ') ', p.title)
            FROM ?_product p LEFT JOIN ?_selfservice_type_product tp
            USING (product_id)
            WHERE tp.relation = ? AND tp.value>0
            ORDER BY p.sort_order, p.title", 'out');
    }

    function getProducts()
    {
        $vars = $this->form->getValue();
        $cache = $this->getDi()->db->selectCol("SELECT
                DISTINCT product_id as ARRAY_KEY, title
                FROM ?_product
                {WHERE product_id IN (?a)}
                ORDER BY sort_order, title", !empty($vars['products']) ? (array) $vars['products'] : array_keys($this->getAllProducts()));
        return $cache;
    }

    function getLines()
    {
        $ret = [];
        foreach ($this->getProducts() as $id => $title) {
            $ret[] = new Am_Report_Line('sum_' . $id, ucfirst($title));
        }
        return $ret;
    }

}