<?php

namespace Bastion\Handlers;

use Symfony\Component\HttpFoundation\JsonResponse;
use Openguru\OpenCartFramework\QueryBuilder\Builder;
use Openguru\OpenCartFramework\QueryBuilder\JoinClause;
use Openguru\OpenCartFramework\QueryBuilder\RawExpression;

class StatsHandler
{
    private Builder $builder;

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

    public function getDashboardStats(): JsonResponse
    {
        $data = [
            'orders_count' => 0,
            'orders_total_amount' => 0,
            'customers_count' => 0,
        ];

        $ordersTotalAmount = $this->builder->newQuery()
            ->select([
                new RawExpression('COUNT(DISTINCT orders.order_id) AS orders_total_count'),
                new RawExpression('SUM(orders.total) AS orders_total_amount'),
            ])
            ->from(db_table('order'), 'orders')
            ->join('telecart_customers', function (JoinClause $join) {
                $join->on('orders.customer_id', '=', 'telecart_customers.oc_customer_id');
            })
            ->join('telecart_order_meta', function (JoinClause $join) {
                $join->on('orders.order_id', '=', 'telecart_order_meta.oc_order_id')
                    ->whereRaw('orders.store_id = telecart_order_meta.oc_store_id');
            })
            ->firstOrNull();


        if ($ordersTotalAmount) {
            $data = [
                'orders_count' => (int) $ordersTotalAmount['orders_total_count'],
                'orders_total_amount' => (int) $ordersTotalAmount['orders_total_amount'],
                'customers_count' => $this->countCustomersCount(),
            ];
        }

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

    private function countCustomersCount(): int
    {
        return $this->builder->newQuery()
            ->from('telecart_customers')
            ->count();
    }
}
