<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Advertisement;
use App\Models\User;
use App\Models\Location;
use Illuminate\Support\Facades\DB;
use App\Models\Category;
use App\Models\Province;
use App\Models\City;
use App\Models\Country;
use App\Models\Village;

class ReportController extends Controller
{
    public function advertisements()
    {
        $advertisements = Advertisement::all(); // دریافت تمام تبلیغات
        return view('admin.reports.advertisements', compact('advertisements'));
    }

    public function users()
    {
        $users = User::all(); // دریافت تمام کاربران
        return view('admin.reports.users', compact('users'));
    }

    public function locations(Request $request)
    {
        $query = Location::with(['categoryRelation', 'country', 'province', 'city', 'village', 'user']);

        // Apply filters
        if ($request->has('category_id') && $request->category_id) {
            $query->where('category_id', $request->category_id);
        }

        if ($request->has('province_id') && $request->province_id) {
            $query->where('province_id', $request->province_id);
        }

        if ($request->has('city_id') && $request->city_id) {
            $query->where('city_id', $request->city_id);
        }

        if ($request->has('country_id') && $request->country_id) {
            $query->where('country_id', $request->country_id);
        }

        if ($request->has('village_id') && $request->village_id) {
            $query->where('village_id', $request->village_id);
        }

        if ($request->has('status') && $request->status !== '') {
            $query->where('is_active', $request->status);
        }

        if ($request->has('package_type') && $request->package_type) {
            $query->where('package_type', $request->package_type);
        }

        // Date filters
        if ($request->has('date_from') && $request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->has('date_to') && $request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        // Search filter
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%")
                  ->orWhere('address', 'like', "%{$search}%");
            });
        }

        // Handle AJAX requests for statistics update
        if ($request->ajax() && $request->has('ajax')) {
            $stats = $this->getLocationStatistics();
            return response()->json(['stats' => $stats]);
        }

        // Get comprehensive statistics
        $stats = [
            'total' => Location::count(),
            'active' => Location::where('is_active', true)->count(),
            'inactive' => Location::where('is_active', false)->count(),
            'premium' => Location::whereIn('package_type', ['diamond', 'gold', 'silver'])->count(),
            'today' => Location::whereDate('created_at', today())->count(),
            'with_coordinates' => Location::whereNotNull('lat')->whereNotNull('lng')->count(),
            'without_coordinates' => Location::where(function($q) {
                $q->whereNull('lat')->orWhereNull('lng');
            })->count(),
            'diamond' => Location::where('package_type', 'diamond')->count(),
            'gold' => Location::where('package_type', 'gold')->count(),
            'silver' => Location::where('package_type', 'silver')->count(),
            'bronze' => Location::where('package_type', 'bronze')->count(),
            'regular' => Location::where('package_type', 'regular')->count(),
        ];

        // Get category distribution
        $categoryStats = Location::select('category_id', DB::raw('COUNT(*) as count'))
            ->with('categoryRelation')
            ->whereNotNull('category_id')
            ->groupBy('category_id')
            ->having('count', '>', 0)
            ->get()
            ->map(function ($item) {
                return [
                    'name' => $item->categoryRelation ? $item->categoryRelation->getTranslatedName() : 'بدون دسته‌بندی',
                    'count' => $item->count
                ];
            });

        // Get geographic distribution
        $provinceStats = Location::select('province_id', DB::raw('COUNT(*) as count'))
            ->with('province')
            ->whereNotNull('province_id')
            ->groupBy('province_id')
            ->having('count', '>', 0)
            ->orderBy('count', 'desc')
            ->take(10)
            ->get()
            ->map(function ($item) {
                return [
                    'name' => $item->province ? $item->province->getTranslatedName() : 'نامشخص',
                    'count' => $item->count
                ];
            });

        // Get country distribution
        $countryStats = Location::select('country_id', DB::raw('COUNT(*) as count'))
            ->with('country')
            ->whereNotNull('country_id')
            ->groupBy('country_id')
            ->having('count', '>', 0)
            ->orderBy('count', 'desc')
            ->take(10)
            ->get()
            ->map(function ($item) {
                return [
                    'name' => $item->country ? $item->country->getTranslatedName() : 'نامشخص',
                    'count' => $item->count
                ];
            });

        // Get package distribution
        $packageStats = Location::select('package_type', DB::raw('COUNT(*) as count'))
            ->whereNotNull('package_type')
            ->groupBy('package_type')
            ->having('count', '>', 0)
            ->orderBy('count', 'desc')
            ->get()
            ->map(function ($item) {
                $packageNames = [
                    'diamond' => 'الماس',
                    'gold' => 'طلایی',
                    'silver' => 'نقره‌ای',
                    'bronze' => 'برنزی',
                    'regular' => 'عادی'
                ];
                return [
                    'name' => $packageNames[$item->package_type] ?? $item->package_type,
                    'count' => $item->count,
                    'type' => $item->package_type
                ];
            });

        // Get monthly statistics for the last 12 months
        $monthlyStats = [];
        for ($i = 11; $i >= 0; $i--) {
            $date = now()->subMonths($i);
            $count = Location::whereYear('created_at', $date->year)
                           ->whereMonth('created_at', $date->month)
                           ->count();
            $monthlyStats[] = [
                'month' => $date->format('Y-m'),
                'month_name' => $date->locale('fa')->translatedFormat('F Y'),
                'count' => $count
            ];
        }

        // Get locations with pagination and ensure relationships are loaded
        $locations = $query->with(['categoryRelation', 'country', 'province', 'city', 'village', 'user'])
                          ->orderBy('created_at', 'desc')
                          ->paginate(20);

        // Get filter options
        $categories = Category::where('is_active', true)->orderBy('category_fa')->get();
        $countries = Country::where('is_active', true)->orderBy('name')->get();
        $provinces = Province::where('is_active', true)->orderBy('name')->get();
        $cities = City::where('is_active', true)->orderBy('name')->get();
        $villages = Village::where('is_active', true)->orderBy('name')->get();

        // Breadcrumb for admin layout
        $breadcrumb = [
            ['title' => 'گزارشات', 'url' => '#'],
            ['title' => 'گزارش مکان‌ها', 'url' => route('admin.reports.locations')]
        ];

        return view('admin.reports.locations', compact(
            'locations',
            'stats',
            'categoryStats',
            'provinceStats',
            'countryStats',
            'packageStats',
            'monthlyStats',
            'categories',
            'countries',
            'provinces',
            'cities',
            'villages',
            'breadcrumb'
        ));
    }

    /**
     * Get comprehensive location statistics
     */
    private function getLocationStatistics()
    {
        return [
            'total' => Location::count(),
            'active' => Location::where('is_active', true)->count(),
            'inactive' => Location::where('is_active', false)->count(),
            'premium' => Location::whereIn('package_type', ['diamond', 'gold', 'silver'])->count(),
            'today' => Location::whereDate('created_at', today())->count(),
            'this_week' => Location::whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count(),
            'this_month' => Location::whereMonth('created_at', now()->month)->whereYear('created_at', now()->year)->count(),
            'with_coordinates' => Location::whereNotNull('lat')->whereNotNull('lng')->count(),
            'without_coordinates' => Location::where(function($q) {
                $q->whereNull('lat')->orWhereNull('lng');
            })->count(),
            'diamond' => Location::where('package_type', 'diamond')->count(),
            'gold' => Location::where('package_type', 'gold')->count(),
            'silver' => Location::where('package_type', 'silver')->count(),
            'bronze' => Location::where('package_type', 'bronze')->count(),
            'regular' => Location::where('package_type', 'regular')->count(),
        ];
    }

    /**
     * Get today's locations count for AJAX requests
     */
    public function getTodayCount()
    {
        $count = Location::whereDate('created_at', today())->count();
        return response()->json(['count' => $count]);
    }

    /**
     * Get cities by province for AJAX requests
     */
    public function getCitiesByProvince($provinceId)
    {
        $cities = City::where('province_id', $provinceId)
                     ->where('is_active', true)
                     ->orderBy('name')
                     ->get(['id', 'name']);

        return response()->json($cities);
    }
}