<?php

$main_class = 'userInfo';

class UserInfo extends Window
{
    protected $template = 'window/userInfo.tpl';
    protected $outgoing_data;

    public function get_vars()
    {
        $vars = parent::get_vars();
        $vars['data'] = $this->outgoing_data;

        return $vars;
    }

    public function handleGetQueueInfo()
    {
        $json_data = getVal('data');

        $data = json_decode($json_data, true);

        $outgoing_data = [];
        $outgoing_data['incoming_data'] = $data;
        if (!empty($data['caller_number'])) {
            $outgoing_data['user'] = $this->findUser($data['caller_number']);

            $outgoing_data['money'] = $this->getSpendedMoney($data['caller_number']);
        }

        $this->outgoing_data = $outgoing_data;
    }

    public function handleGetCallerInfo()
    {
        $json_data = getVal('data');

        $data = json_decode($json_data, true);

        $outgoing_data = [];
        $outgoing_data['incoming_data'] = $data;
        if (!empty($data['caller_number'])) {
            $outgoing_data['user'] = $this->findUser($data['caller_number']);

            $outgoing_data['orders'] = $this->getOrders($data['caller_number']);
            $outgoing_data['money'] = $this->getSpendedMoney($data['caller_number']);

            if (findModule(Modules::RECLAMATIONS)) {
                $outgoing_data['reclamations'] = $this->getReclamations($data['caller_number']);
            }

            if (findModule(Modules::RETURNS)) {
                $outgoing_data['returns'] = $this->getReturns($data['caller_number']);
            }
        }

        $this->outgoing_data = $outgoing_data;
    }

    public function handleCallInterrupt()
    {
        global $dbcfg;
        $call_id = getVal('call_id');

        if (empty($call_id)) {
            exit;
        }

        $item = "
          <interrupt_call>
            <id>{$call_id}</id>
            <recording_id>{$dbcfg['telfa']['status']['interrupt']}</recording_id>
          </interrupt_call>
          ";

        $url = 'https://www4.telfa.cz/calls/interrupt.xml';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_USERPWD, $dbcfg['telfa']['username'].':'.$dbcfg['telfa']['password']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/xml']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $item);
        $info = curl_getinfo($ch);
        $xml = curl_exec($ch);
        curl_close($ch);

        $this->realtimeDebug($item);
        $this->realtimeDebug($xml);
        exit;
    }

    public function realtimeDebug($data = null)
    {
        $itemjson = json_encode($data);

        $url = 'http://pardal.wpj.cz:5555/telfa/triger?channel=telfa&message=myevent';

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $itemjson);

        curl_exec($ch);
        curl_close($ch);
    }

    public function findUser($phone, $try_orders = false)
    {
        $SQL = sqlQuery('SELECT id, name, surname, phone, country FROM '.getTableName('users')." WHERE phone LIKE '%{$phone}' ");

        if ($try_orders && sqlNumRows($SQL) == 0) {
            $SQL = sqlQuery('SELECT invoice_name as name, invoice_surname as surname FROM  '.getTableName('users')." WHERE invoice_phone LIKE '%{$phone}' ORDER BY id DESC LIMIT 1");
        }

        if (sqlNumRows($SQL) >= 1) {
            $user = sqlFetchAssoc($SQL);
            sqlFreeResult($SQL);

            return $user;
        } else {
            return false;
        }
    }

    public function getReturns($phone)
    {
        $returns = sqlQueryBuilder()->select('r.id, o.invoice_name, o.invoice_surname')
            ->from('returns', 'r')
            ->join('r', 'orders', 'o', 'o.id = r.id_order')
            ->where('o.invoice_phone LIKE :like')
            ->setParameter('like', '%'.$phone)
            ->orderBy('r.id', 'DESC')
            ->setMaxResults(10)
            ->execute();

        if (sqlNumRows($returns) > 0) {
            $data = [];
            /** @var \KupShop\ReturnsBundle\Util\ReturnsUtil $returnUtil */
            $returnUtil = \KupShop\KupShopBundle\Util\Compat\ServiceContainer::getService(\KupShop\ReturnsBundle\Util\ReturnsUtil::class);
            foreach ($returns as $return) {
                $entity = $returnUtil->getReturn($return['id']);
                $orderNo = sqlQueryBuilder()->select('order_no')->from('orders')->where(\Query\Operator::equals(['id' => $entity->getIdOrder()]))->execute()->fetchColumn();

                $class = '';
                if (in_array($entity->getStatus(), $returnUtil->getHandleStatuses())) {
                    $class = ' row-green';
                }

                if (in_array($entity->getStatus(), $returnUtil->getAcceptedStatuses())) {
                    $class = ' row-blue';
                }

                $data[] = [
                    'id' => $entity->getId(),
                    'code' => $entity->getCode(),
                    'date_created' => $entity->getDateCreated(),
                    'name' => $return['invoice_name'],
                    'surname' => $return['invoice_surname'],
                    'status_name' => $entity->getStatusName(),
                    'id_order' => $entity->getIdOrder(),
                    'order_no' => $orderNo,
                    'class' => $class,
                ];
            }

            return $data;
        }

        return false;
    }

    public function getReclamations($phone)
    {
        $reclamations = sqlQueryBuilder()->select('id')
            ->from('reclamations')
            ->where('phone LIKE :like')
            ->setParameter('like', '%'.$phone)
            ->orderBy('id', 'DESC')
            ->setMaxResults(10)
            ->execute();

        if (sqlNumRows($reclamations) > 0) {
            $data = [];
            $reclamationUtil = \KupShop\KupShopBundle\Util\Compat\ServiceContainer::getService(\KupShop\ReclamationsBundle\Util\ReclamationsUtil::class);
            foreach ($reclamations as $reclamation) {
                /** @var \KupShop\ReclamationsBundle\Entity\ReclamationEntity $entity */
                $entity = $reclamationUtil->getReclamation($reclamation['id']);
                $orderNo = sqlQueryBuilder()->select('order_no')->from('orders')->where(\Query\Operator::equals(['id' => $entity->getIdOrder()]))->execute()->fetchColumn();

                $class = '';
                if (in_array($entity->getStatus(), $reclamationUtil->getHandleStatuses())) {
                    $class = ' row-green';
                }

                // upcoming
                if (in_array($entity->getStatus(), $reclamationUtil->getAcceptedStatuses())) {
                    $dateAccepted = DateTime::createFromFormat('Y-m-d H:i:s', $entity->getDateAccepted());
                    if ($dateAccepted) {
                        $diff = $dateAccepted->diff(new DateTime());
                        if (abs($diff->days) > 15) {
                            $class = ' row-orange';
                        }
                        if (abs($diff->days) > 30) {
                            $class = ' row-red';
                        }
                    }
                }

                $data[] = [
                    'id' => $entity->getId(),
                    'code' => $entity->getCode(),
                    'date_created' => $entity->getDateCreated(),
                    'name' => $entity->getAddress()['name'] ?? '',
                    'surname' => $entity->getAddress()['surname'] ?? '',
                    'id_item' => $entity->getIdItem(),
                    'item' => $entity->getItem(),
                    'id_order' => $entity->getIdOrder(),
                    'order_no' => $orderNo,
                    'status_name' => $entity->getStatusName(),
                    'class' => $class,
                ];
            }

            return $data;
        }

        return false;
    }

    public function getOrders($phone)
    {
        $SQL = sqlQuery('SELECT id, order_no, total_price, invoice_country, date_handle, date_created, invoice_name, invoice_surname, status, status_storno FROM '.getTableName('orders')." WHERE invoice_phone LIKE '%{$phone}' ORDER BY id DESC LIMIT 10");
        if (sqlNumRows($SQL) > 0) {
            $orders = [];
            foreach ($SQL as $order) {
                $order['status_text'] = $this->renderStatus($order['status'], $order['status_storno']);
                $orders[] = $order;
            }
            sqlFreeResult($SQL);

            return $orders;
        } else {
            return false;
        }
    }

    public function renderStatus($status, $status_storno)
    {
        global $cfg;

        if ($status_storno == 1) {
            return $cfg['Order']['Status']['storno'][$status_storno];
        }

        return $cfg['Order']['Status']['global'][$status];
    }

    public function getSpendedMoney($phone)
    {
        $SQL = sqlQuery('SELECT SUM(total_price) as spended FROM '.getTableName('orders')." WHERE invoice_phone LIKE '%{$phone}' AND status_storno=0");
        if (sqlNumRows($SQL) == 1) {
            $price = sqlFetchAssoc($SQL);
            sqlFreeResult($SQL);

            return $price;
        } else {
            return false;
        }
    }
}
