<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use App\Models\DnsZone;
use App\Models\DnsQueryUsage;
use App\Models\DnsZoneStatistic;
use Illuminate\Support\Facades\DB;

class SyncDnsQueryUsage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dns:sync-query-usage
        {--user_id= : Sync only for specific user}
        {--all : Sync for all users with zones, not just those with limits}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sincronizează query-urile DNS din statistici cu sistemul de limite';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('🔄 Sincronizare Query-uri DNS...');

        $userId = $this->option('user_id');
        $syncAll = $this->option('all');

        if ($userId) {
            $users = User::where('id', $userId)->get();
        } elseif ($syncAll) {
            // Toți utilizatorii care au zone DNS
            $users = User::whereHas('dnsZones')->get();
        } else {
            // Utilizatorii care au plan cu limită SAU au zone
            $users = User::where(function($q) {
                $q->whereHas('plan', function($query) {
                    $query->whereNotNull('dns_queries_limit')
                          ->orWhereNotNull('dns_queries_limit_daily');
                })->orWhereHas('dnsZones');
            })->get();
        }

        $this->info("📊 Procesare {$users->count()} utilizatori...\n");

        $year = (int) date('Y');
        $month = (int) date('n');
        $today = now()->format('Y-m-d');

        $totalSynced = 0;

        foreach ($users as $user) {
            $this->line("👤 User: {$user->name} ({$user->email})");

            // Obține toate zonele utilizatorului
            $zones = $user->dnsZones;

            if ($zones->isEmpty()) {
                $this->line("   ⚠️  Nu are zone DNS");
                continue;
            }

            $monthlyQueries = 0;
            $dailyQueries = 0;

            foreach ($zones as $zone) {
                // Obține statistici din dns_zone_statistics pentru luna curentă
                $monthlyStats = DnsZoneStatistic::where('domain', $zone->domain)
                    ->whereYear('statistic_date', $year)
                    ->whereMonth('statistic_date', $month)
                    ->sum('total_queries');

                $monthlyQueries += $monthlyStats;

                // Obține statistici pentru azi
                $dailyStats = DnsZoneStatistic::where('domain', $zone->domain)
                    ->whereDate('statistic_date', $today)
                    ->sum('total_queries');

                $dailyQueries += $dailyStats;
            }

            // Actualizează sau creează înregistrarea de usage
            $usage = DnsQueryUsage::updateOrCreate(
                [
                    'user_id' => $user->id,
                    'year' => $year,
                    'month' => $month,
                ],
                [
                    'query_count' => $monthlyQueries,
                    'daily_query_count' => $dailyQueries,
                    'last_daily_reset' => now()->startOfDay(),
                ]
            );

            if ($monthlyQueries > 0 || $dailyQueries > 0) {
                $this->info("   ✅ Lunar: " . number_format($monthlyQueries) . " | Zilnic: " . number_format($dailyQueries));
                $totalSynced++;

                // Verifică și trimite alerte dacă e necesar
                $usage->checkAndSendAlerts();
            } else {
                $this->line("   ℹ️  0 query-uri în perioada curentă");
            }
        }

        $this->newLine();
        $this->info("✅ Sincronizare completă! ({$totalSynced} utilizatori actualizați)");

        return 0;
    }
}
