<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Location;
use App\Models\Visit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class StatisticsController extends Controller
{
    /**
     * نمایش صفحه اصلی آمار
     */
    public function index()
    {
        $totalUsers = User::count();
        $totalLocations = Location::count();
        $totalVisits = Visit::count();
        $recentVisits = Visit::with('user', 'location')
            ->latest()
            ->take(10)
            ->get();

        return view('admin.statistics.index', compact(
            'totalUsers',
            'totalLocations',
            'totalVisits',
            'recentVisits'
        ));
    }

    /**
     * نمایش آمار کاربران
     */
    public function users()
    {
        $usersByMonth = User::select(
            DB::raw('MONTH(created_at) as month'),
            DB::raw('COUNT(*) as count')
        )
            ->whereYear('created_at', date('Y'))
            ->groupBy('month')
            ->get();

        $activeUsers = User::whereHas('visits', function ($query) {
            $query->where('created_at', '>=', now()->subDays(30));
        })->count();

        return view('admin.statistics.users', compact('usersByMonth', 'activeUsers'));
    }

    /**
     * نمایش آمار مکان‌ها
     */
    public function locations()
    {
        // مکان‌های پربازدید
        $popularLocations = Location::withCount('visits')
            ->orderBy('visits_count', 'desc')
            ->take(10)
            ->get();

        // توزیع مکان‌ها بر اساس دسته‌بندی
        $locationsByCategory = Location::select('category_id', DB::raw('COUNT(*) as count'))
            ->with('categoryRelation')
            ->groupBy('category_id')
            ->having('count', '>', 0)
            ->get()
            ->map(function ($item) {
                return [
                    'name' => $item->categoryRelation ? $item->categoryRelation->getTranslatedName() : 'بدون دسته‌بندی',
                    'count' => $item->count
                ];
            });

        // آمار کلی مکان‌ها
        $locationStats = [
            'total' => Location::count(),
            'active' => Location::where('is_active', 1)->count(),
            'inactive' => Location::where('is_active', 0)->count(),
            'with_coordinates' => Location::whereNotNull('lat')->whereNotNull('lng')->count(),
            'without_coordinates' => Location::whereNull('lat')->orWhereNull('lng')->count(),
        ];

        // آمار مکان‌ها در 30 روز گذشته
        $recentLocations = Location::where('created_at', '>=', now()->subDays(30))
            ->select(
                DB::raw('DATE(created_at) as date'),
                DB::raw('COUNT(*) as count')
            )
            ->groupBy('date')
            ->orderBy('date', 'asc')
            ->get()
            ->map(function ($item) {
                return [
                    'date' => verta($item->date)->format('Y/m/d'),
                    'count' => $item->count
                ];
            });

        // آمار مکان‌ها بر اساس استان
        $locationsByProvince = Location::select('province_id', DB::raw('COUNT(*) as count'))
            ->with('province')
            ->groupBy('province_id')
            ->having('count', '>', 0)
            ->get()
            ->map(function ($item) {
                return [
                    'name' => $item->province ? $item->province->name : 'بدون استان',
                    'count' => $item->count
                ];
            });

        // آمار مکان‌ها بر اساس امتیاز
        $locationsByRating = DB::table('ratings')
            ->select(
                DB::raw('ROUND(rating, 1) as rating_value'),
                DB::raw('COUNT(*) as count')
            )
            ->where('status', 'approved')
            ->groupBy('rating_value')
            ->orderBy('rating_value', 'desc')
            ->get()
            ->map(function ($item) {
                return [
                    'rating' => $item->rating_value . ' ستاره',
                    'count' => $item->count
                ];
            });

        return view('admin.statistics.locations', compact(
            'popularLocations',
            'locationsByCategory',
            'locationStats',
            'recentLocations',
            'locationsByProvince',
            'locationsByRating'
        ));
    }

    /**
     * نمایش آمار بازدیدها
     */
    public function visits()
    {
        $visitsByDay = Visit::select(
            DB::raw('DATE(created_at) as date'),
            DB::raw('COUNT(*) as count')
        )
            ->where('created_at', '>=', now()->subDays(30))
            ->groupBy('date')
            ->get();

        $visitsByHour = Visit::select(
            DB::raw('HOUR(created_at) as hour'),
            DB::raw('COUNT(*) as count')
        )
            ->groupBy('hour')
            ->get();

        return view('admin.statistics.visits', compact('visitsByDay', 'visitsByHour'));
    }
}