<?php

namespace Bastion\Handlers;

use Openguru\OpenCartFramework\Http\JsonResponse;
use Openguru\OpenCartFramework\QueryBuilder\Builder;
use Openguru\OpenCartFramework\QueryBuilder\JoinClause;
use Openguru\OpenCartFramework\QueryBuilder\RawExpression;
use Openguru\OpenCartFramework\QueryBuilder\Table;

class StatsHandler
{
    private Builder $builder;

    public function __construct(Builder $builder)
    {
        $this->builder = $builder;
    }

    public function getDashboardStats(): JsonResponse
    {
        $ordersTotalAmount = $this->builder->newQuery()
            ->select([
                new RawExpression('COUNT(DISTINCT orders.order_id) AS orders_count'),
                new RawExpression('SUM(orders.total) AS orders_total_amount'),
                new RawExpression('COUNT(DISTINCT order_product.product_id) AS order_products_count'),
            ])
            ->from(db_table('order'), 'orders')
            ->join(new Table(db_table('order_history'), 'order_history'), function (JoinClause $join) {
                $join->on('orders.order_id', '=', 'order_history.order_id')
                    ->where('order_history.comment', '=', 'Заказ оформлен через Telegram Mini App');
            })
            ->join(new Table(db_table('order_product'), 'order_product'), function (JoinClause $join) {
                $join->on('orders.order_id', '=', 'order_product.order_id');
            })
            ->firstOrNull();

        if ($ordersTotalAmount) {
            $data = [
                'orders_count' => (int) $ordersTotalAmount['orders_count'],
                'orders_total_amount' => (int) $ordersTotalAmount['orders_total_amount'],
                'order_products_count' => (int) $ordersTotalAmount['order_products_count'],
            ];
        }

        return new JsonResponse(compact('data'));
    }
}
