<?php

namespace App\Http\Controllers;

use App\Models\Blog;
use App\Models\City;
use App\Models\HyperLink;
use App\Models\Profile;
use App\Models\Region;
use App\Models\Tag;
use App\Models\Website;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class StatistiquesController extends Controller
{
    public function CardsStats(Request $request)
    {
        $userId = $request->user()->id;
        $userRole = $request->user()->role->name;

        $websiteId = $request->website_id;

        $today = Carbon::today();
        $yesterday = Carbon::yesterday();

        $todayData = $this->getDailyData($today, $websiteId, $userId, $userRole);
        $yesterdayData = $this->getDailyData($yesterday, $websiteId, $userId, $userRole);

        return [
            'hyperLinks' => $this->calculateStats(
                $todayData['hyperLinks'],
                $yesterdayData['hyperLinks'],
                HyperLink::whereNull('deleted_at')
                    ->when($websiteId, function ($query) use ($websiteId) {
                        return $query->where('website_id', $websiteId);
                    })
                    ->when($userRole && $userRole !== 'SuperAdmin', function ($query) use ($userId) {
                        return $query->where('user_id', $userId);
                    })
                    ->count()
            ),

            'blogs' => $this->calculateStats(
                $todayData['blogs'],
                $yesterdayData['blogs'],
                Blog::whereNull('deleted_at')
                    ->when($websiteId, function ($query) use ($websiteId) {
                        return $query->where('website_id', $websiteId);
                    })
                    ->when($userRole && $userRole !== 'SuperAdmin', function ($query) use ($userId) {
                        return $query->where('user_id', $userId);
                    })
                    ->count()
            ),

            // No user filter for websites
            'websites' => $this->calculateStats(
                $todayData['websites'],
                $yesterdayData['websites'],
                Website::whereNull('deleted_at')
                    ->count()
            )
        ];
    }

    private function getDailyData($date, $websiteId = null, $userId, $userRole)
    {
        return [
            'hyperLinks' => HyperLink::whereNull('deleted_at')
                ->whereDate('created_at', $date)
                ->when($websiteId, function ($query) use ($websiteId) {
                    return $query->where('website_id', $websiteId);
                })
                ->when($userRole && $userRole !== 'SuperAdmin', function ($query) use ($userId) {
                    return $query->where('user_id', $userId);
                })
                ->count(),

            'blogs' => Blog::whereNull('deleted_at')
                ->whereDate('created_at', $date)
                ->when($websiteId, function ($query) use ($websiteId) {
                    return $query->where('website_id', $websiteId);
                })
                ->when($userRole && $userRole !== 'SuperAdmin', function ($query) use ($userId) {
                    return $query->where('user_id', $userId);
                })
                ->count(),

            // No user filter for websites
            'websites' => Website::whereNull('deleted_at')
                ->whereDate('created_at', $date)
                ->count(),
        ];
    }


    private function calculateStats($todayCount, $yesterdayCount, $allTimeCount)
    {
        $difference = $todayCount - $yesterdayCount;
        $percentage = $yesterdayCount ? (($difference / $yesterdayCount) * 100) : ($todayCount ? 100 : 0);

        return [
            'allTimeCount' => $allTimeCount,
            'difference' => $difference,
            'percentage' => $percentage
        ];
    }



    public function GraphsStats(Request $request)
    {
        $website = $request->website_id;
        $userId = $request->user()->id;
        $userRole = $request->user()->role->name;

        // Define the start and end dates for the year up to the current month
        $startDate = Carbon::now()->startOfYear(); // Start of the year
        $endDate = Carbon::now()->endOfMonth();   // End of the current month

        // Get a list of all months within the range
        $months = [];
        $currentMonth = $startDate->copy();

        while ($currentMonth->lte($endDate)) {
            $months[] = $currentMonth->format('F Y'); // Format as 'Month Year'
            $currentMonth->addMonth();
        }

        // Query to get the count of blogs per month
        $monthlyBlogCountsQuery = Blog::selectRaw(
            "DATE_FORMAT(created_at, '%M %Y') as month, COUNT(*) as count"
        )
            ->whereBetween('created_at', [$startDate, $endDate])
            ->when($website, function ($query, $website) {
                return $query->where('website_id', $website);
            })
            ->groupBy('month')
            ->orderBy('created_at', 'asc');
        if ($userRole && $userRole !== 'SuperAdmin') {
            $monthlyBlogCountsQuery->where('user_id', $userId);
        }

        $monthlyBlogCountsResults = $monthlyBlogCountsQuery->pluck('count', 'month');

        $monthlyHyperLinkCountsQuery = HyperLink::selectRaw(
            "DATE_FORMAT(created_at, '%M %Y') as month, COUNT(*) as count"
        )
            ->whereBetween('created_at', [$startDate, $endDate])
            ->when($website, function ($query, $website) {
                return $query->where('website_id', $website);
            })
            ->groupBy('month')
            ->orderBy('created_at', 'asc');
        if ($userRole && $userRole !== 'SuperAdmin') {
            $monthlyHyperLinkCountsQuery->where('user_id', $userId);
        }
        $monthlyHyperLinkCountsResults = $monthlyHyperLinkCountsQuery->pluck('count', 'month');

        $monthlyBlogCounts = [];
        $monthlyHyperLinkCounts = [];

        foreach ($months as $month) {
            $monthlyBlogCounts[] = [
                'month' => $month,
                'count' => $monthlyBlogCountsResults->get($month, 0)
            ];
            $monthlyHyperLinkCounts[] = [
                'month' => $month,
                'count' => $monthlyHyperLinkCountsResults->get($month, 0)
            ];
        }

        return [
            'monthlyBlogCounts' => $monthlyBlogCounts,
            'monthlyHyperLinkCounts' => $monthlyHyperLinkCounts
        ];
    }
}
