<?php

namespace KupShop\MarketingBundle\SupportBox;

use Query\Operator;

class InfoProvider
{
    public function getAdditionalData(?string $email, ?string $phone): array
    {
        $data = [];

        if ($email) {
            $data['user'] = (new \User())->createFromLogin($email);
        } elseif ($phone) {
            $phone = str_replace(' ', '', $phone);
            $data['user'] = \User::createFromSpec(Operator::like(['phone' => '%'.$phone.'%']));
        }

        $data = array_merge($data, $this->provideOrdersData($email, $phone));
        $data = array_merge($data, $this->provideSalesData($email, $phone));

        $smarty = createSmarty(true, true);
        $smarty->assign($data);

        $result['html'] = $smarty->fetch('supportBox/userInfo.tpl');

        return $result;
    }

    public function getName($phone)
    {
        $phone = str_replace(' ', '', $phone);
        $name = sqlQueryBuilder()
            ->select('CONCAT_WS(" ", name, surname)')
            ->from('users')
            ->where(Operator::like(['phone' => '%'.$phone.'%']))
            ->orderBy('id', 'DESC')
            ->setMaxResults(1)
            ->execute()->fetchColumn();

        if (!$name) {
            $name = sqlQueryBuilder()
            ->select('CONCAT_WS(" ", invoice_name, invoice_surname)')
            ->from('orders')
            ->where(Operator::like(['invoice_phone' => '%'.$phone.'%']))
            ->orderBy('id', 'DESC')
            ->setMaxResults(1)
            ->execute()->fetchColumn();
        }

        if (!$name) {
            return [];
        }

        return [
            'name' => $name,
        ];
    }

    protected function provideOrdersData(?string $email, ?string $phone): array
    {
        $result = [];

        $orX = [];

        if ($email) {
            $orX[] = Operator::like(['invoice_email' => $email]);
        }

        if ($phone) {
            $orX[] = Operator::like(['invoice_phone' => $phone]);
        }

        $result['total_orders_price'] = sqlQueryBuilder()->select('SUM(total_price*currency_rate)')
            ->from('orders')
            ->where(Operator::orX($orX))
            ->andWhere('status_storno!=1')
            ->execute()->fetchOne();

        $ordersQb = sqlQueryBuilder()
            ->select('*')
            ->from('orders', 'o')
            ->orderBy('o.id', 'DESC')
            ->setMaxResults(2)
            ->where(Operator::orX($orX));

        foreach ($ordersQb->execute() as $order) {
            $order['order_status'] = getOrderStatus($order['status'])['name'];
            $order['items'] = sqlQueryBuilder()
                ->select('*')
                ->from('order_items')
                ->where(Operator::equals(['id_order' => $order['id']]))
                ->execute()->fetchAllAssociative();

            $result['orders'][] = $order;
        }

        return $result;
    }

    protected function provideSalesData(?string $email, ?string $phone): array
    {
        if (!findModule(\Modules::SALES)) {
            return [];
        }

        $result = [];

        $orX = [];

        if ($email) {
            $orX[] = Operator::like(['u.email' => $email]);
        }

        if ($phone) {
            $orX[] = Operator::like(['u.phone' => $phone]);
        }

        $baseQb = sqlQueryBuilder()
            ->select('s.*, sell.title as seller_name')
            ->from('sales', 's')
            ->leftJoin('s', 'users', 'u', 'u.id = s.id_user')
            ->leftJoin('s', 'sellers', 'sell', 'sell.id = s.id_seller');

        $result['total_sales_price'] = (clone $baseQb)
            ->select('SUM(total_price)')
            ->where(Operator::orX($orX))
            ->execute()->fetchOne();

        $salesQb = (clone $baseQb)
            ->where(Operator::orX($orX));

        foreach ($salesQb->execute() as $sale) {
            $sale['items'] = sqlQueryBuilder()
                ->select('*')
                ->from('sales_items')
                ->where(Operator::equals(['id_sale' => $sale['id']]))
                ->execute()->fetchAllAssociative();

            $result['sales'][] = $sale;
        }

        return $result;
    }
}
