<?php

namespace App\Http\Controllers;

use App\Repos\ColoredRepo;
use App\Repos\PageRepo;
use App\Repos\SubscriptionRepo;
use App\Repos\UserRepo;
use App\Services\ResponseService;
use App\Utils\DateUtil;
use Throwable;

class AnalyticController extends Controller
{
    public function counters()
    {
        try {
            $startOfWeek = now()->subWeek();
            $now = now();
            $counters = [
                'week' => [
                    'users' => UserRepo::countUsersBetweenDate($startOfWeek, $now),
                    'pages' => PageRepo::countBetweenDate($startOfWeek, $now),
                    'coloreds' => ColoredRepo::countBetweenDate($startOfWeek, $now),
                    'subscriptions' => SubscriptionRepo::countActiveBetweenDate($startOfWeek, $now),
                ],
                'total' => [
                    'users' => UserRepo::countUsers(),
                    'pages' => PageRepo::count(),
                    'coloreds' => ColoredRepo::count(),
                    'subscriptions' => SubscriptionRepo::countActive(),
                ]
            ];
            return ResponseService::ok($counters);
        } catch (Throwable $error) {
            return ResponseService::handleError($error);
        }
    }

    public function charts()
    {
        try {
            $startOfMonth = now()->subMonth();
            $now = now();
            $dates = DateUtil::shortDatesBetweenDate($startOfMonth, $now);
            $transformer = function ($items, $name) use ($dates) {
                return $dates->map(function ($date) use ($items, $name) {
                    $item = $items->first(function ($item) use ($date) {
                        return $item->date === $date;
                    });
                    $count = $item ? $item->count : 0;
                    return ['name' => $date, $name => $count];
                });
            };
            $users = UserRepo::dailyUsersCountBetweenDate($startOfMonth, $now);
            $pages = PageRepo::dailyCountBetweenDate($startOfMonth, $now);
            $coloreds = ColoredRepo::dailyCountBetweenDate($startOfMonth, $now);
            $subscriptions = SubscriptionRepo::dailyCountBetweenDate($startOfMonth, $now);
            $charts = [
                'users' => $transformer($users, 'users'),
                'pages' => $transformer($pages, 'pages'),
                'coloreds' => $transformer($coloreds, 'coloreds'),
                'subscriptions' => $transformer($subscriptions, 'subscriptions'),
            ];
            return ResponseService::ok($charts);
        } catch (Throwable $error) {
            return ResponseService::handleError($error);
        }
    }
}
