<?php

namespace AutoAdmin\Bundle\Admin\Controller\Admin;

use AutoAdmin\Bundle\Admin\Configuration\ConfigManager;
use AutoAdmin\Bundle\Admin\Factory\BuilderFactory;
use AutoAdmin\Bundle\Admin\Factory\ContentFactory;
use AutoAdmin\Bundle\Admin\Finder\EntityFinder;
use AutoAdmin\Bundle\Admin\Helper\AccessHelper;
use AutoAdmin\Bundle\Admin\Helper\EntityHelper;
use AutoAdmin\Bundle\Admin\Router\AdminRouter;
use AutoAdmin\Bundle\Content\Routing\ContentRouter;
use AutoAdmin\Bundle\Content\Service\GoogleAnalyticsServiceApi;
use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use AutoAdmin\Bundle\Seo\Generator\GeneratorManager;
use Doctrine\DBAL\Exception;
use Doctrine\ORM\EntityManagerInterface;
use ReflectionClass;
use ReflectionException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ChartController extends AbstractAdminController
{
    protected EntityHelper $entityHelper;
    protected BuilderFactory $builderFactory;
    protected AdminRouter $adminRouter;
    protected ContentFactory $contentFactory;
    protected AccessHelper $accessHelper;
    protected ConfigManager $configManager;
    protected ContentRouter $contentRouter;
    protected SiteContextHelper $siteContextHelper;
    protected EntityFinder $entityFinder;
    protected GeneratorManager $seoGenerator;
    private GoogleAnalyticsServiceApi $googleAnalyticsServiceApi;

    public function __construct(
        EntityHelper              $entityHelper,
        BuilderFactory            $builderFactory,
        AdminRouter               $adminRouter,
        ContentFactory            $contentFactory,
        AccessHelper              $accessHelper,
        ConfigManager             $configManager,
        ContentRouter             $contentRouter,
        SiteContextHelper         $siteContextHelper,
        EntityFinder              $entityFinder,
        GeneratorManager          $seoGenerator,
        GoogleAnalyticsServiceApi $googleAnalyticsServiceApi
    )
    {
        parent::__construct($entityHelper, $builderFactory, $adminRouter, $contentFactory, $accessHelper, $configManager, $contentRouter, $siteContextHelper, $entityFinder, $seoGenerator);

        $this->googleAnalyticsServiceApi = $googleAnalyticsServiceApi;
    }

    /**
     * @throws ReflectionException
     * @throws Exception
     */
    public function init(
        Request $request,
        EntityManagerInterface $em
    ): Response
    {
        $body = $request->getContent();
        $body = json_decode($body, true);

        // check if class implement interface with reflection
        $reflection = new ReflectionClass($body['entity']);
        if ($reflection->implementsInterface('AutoAdmin\Bundle\Content\Model\CreatedAtInterface') || $reflection->hasProperty('createdAt')) {

            $entityName = strtolower($reflection->getShortName());
            $spamFilter = $entityName === "contact" ? " WHERE is_spam = 0 " : "";

            $conn = $em->getConnection();

            // sql query to use DATE function ( deactivated by doctrine query builder )

            $sql = "
                SELECT stats.* FROM (
                   SELECT COUNT(id) as number , CONCAT(YEAR(created_at), '/', WEEK(created_at)) AS week
                   FROM " . $entityName . $spamFilter . "
                   GROUP BY week
                   ORDER BY YEAR(created_at) ASC, WEEK(created_at) ASC
                ) stats
                WHERE week < DATE_SUB(NOW(),INTERVAL 1 YEAR)
            ";

            $stmt = $conn->prepare($sql);
            $result = $stmt->executeQuery()->fetchAllAssociative();
            $data = [];

            foreach ($result as $week) {
                $data['x'][] = $week['week'];
                $data['y'][] = intval($week['number']);
            }

            return new JsonResponse($data);
        }

        return new JsonResponse(
            json_encode([
                'error' => 'Entity does not implement CreatedAtInterface'
            ]), Response::HTTP_BAD_REQUEST
        );
    }

    public function gaStats(string $type, Request $request): JsonResponse
    {
        $domain = $request->getHost();
        $body = $request->toArray();
        $stats = $this->googleAnalyticsServiceApi->getStats($type, $domain, $body);

        return new JsonResponse([
            'x' => $stats['labels'],
            'y' => $stats['datasets']
        ]);
    }
}
