<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\DnsRecord;
use App\Models\DnsZone;
use App\Models\DnsZoneAlert;
use App\Models\NameServer;
use App\Models\Plan;
use App\Models\User;
use App\Models\CloudflareZone;
use App\Models\CloudflareCredential;
use App\Models\CloudflareRecordSetting;
use App\Models\CloudflareSyncLog;
use App\Models\DynamicDnsClient;
use Illuminate\Http\Request;

class AdminDashboardController extends Controller
{
    public function index()
    {
        // Statistici generale
        $stats = [
            'total_users' => User::count(),
            'total_plans' => Plan::count(),
            'total_dns_zones' => DnsZone::count(),
            'total_dns_records' => DnsRecord::count(),
            'active_users' => User::where('is_active', true)->count(),
            'new_users_this_month' => User::whereMonth('created_at', now()->month)->count(),
            'suspended_zones' => DnsZone::whereNotNull('suspended_at')->count(),
            'zones_with_alerts' => DnsZoneAlert::active()->distinct('dns_zone_id')->count(),
            'zones_ready_reactivation' => DnsZone::whereNotNull('suspended_at')->where('can_be_reactivated', true)->count(),
        ];

        // Comparație cu luna precedentă
        $lastMonthUsers = User::whereMonth('created_at', now()->subMonth()->month)
            ->whereYear('created_at', now()->subMonth()->year)
            ->count();
        $lastMonthZones = DnsZone::whereMonth('created_at', now()->subMonth()->month)
            ->whereYear('created_at', now()->subMonth()->year)
            ->count();
        $thisMonthZones = DnsZone::whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->count();
        $lastMonthRecords = DnsRecord::whereMonth('created_at', now()->subMonth()->month)
            ->whereYear('created_at', now()->subMonth()->year)
            ->count();
        $thisMonthRecords = DnsRecord::whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->count();

        $comparison = [
            'users_change' => $lastMonthUsers > 0
                ? round((($stats['new_users_this_month'] - $lastMonthUsers) / $lastMonthUsers) * 100)
                : ($stats['new_users_this_month'] > 0 ? 100 : 0),
            'zones_change' => $lastMonthZones > 0
                ? round((($thisMonthZones - $lastMonthZones) / $lastMonthZones) * 100)
                : ($thisMonthZones > 0 ? 100 : 0),
            'records_change' => $lastMonthRecords > 0
                ? round((($thisMonthRecords - $lastMonthRecords) / $lastMonthRecords) * 100)
                : ($thisMonthRecords > 0 ? 100 : 0),
        ];

        // Cloudflare Statistics
        $cloudflareStats = [
            'total_zones' => CloudflareZone::count(),
            'total_proxied_records' => CloudflareRecordSetting::where('proxied', true)->count(),
            'credentials_count' => CloudflareCredential::count(),
            'last_sync' => CloudflareSyncLog::latest()->first()?->created_at,
            'sync_errors' => CloudflareSyncLog::whereDate('created_at', today())
                ->where('status', 'error')->count(),
        ];

        // Statistici DynDNS
        $dyndnsStats = [
            'active_clients' => DynamicDnsClient::where('is_active', true)->count(),
            'total_clients' => DynamicDnsClient::count(),
            'total_updates_today' => DynamicDnsClient::whereDate('last_update', today())->sum('update_count'),
            'last_update' => DynamicDnsClient::whereNotNull('last_update')->latest('last_update')->first()?->last_update,
            'clients_last_month' => DynamicDnsClient::whereMonth('created_at', now()->subMonth()->month)
                ->whereYear('created_at', now()->subMonth()->year)
                ->count(),
        ];

        // Utilizatori recenți
        $recentUsers = User::with(['plan', 'resellerPlan'])
            ->latest()
            ->take(5)
            ->get();

        // zonă DNS recente
        $recentZones = DnsZone::with('user')
            ->latest()
            ->take(5)
            ->get();

        // Activități recente
        $recentActivities = ActivityLog::with('user')
            ->latest()
            ->take(10)
            ->get();

        // Statistici pe planuri
        $planStats = Plan::withCount('users')->get();

        // Statistici nume servere
        $nameServerStats = [
            'total' => NameServer::count(),
            'online' => NameServer::where('status', 'online')->count(),
            'offline' => NameServer::where('status', 'offline')->count(),
            'avg_response' => NameServer::where('status', 'online')->avg('response_time_ms') ?? 0,
            'total_zones' => NameServer::sum('current_zones'),
        ];

        return view('admin.dashboard', compact(
            'stats',
            'comparison',
            'cloudflareStats',
            'dyndnsStats',
            'recentUsers',
            'recentZones',
            'recentActivities',
            'planStats',
            'nameServerStats'
        ));
    }
}
