<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use App\Models\Setting;
use Carbon\Carbon;

class CheckExpiredDomains extends Command
{
    // এই নামেই আমরা ক্রন জব রান করব
    protected $signature = 'domains:check-expiry';
    protected $description = 'Check expired domains, suspend them, remove DNS, and notify admin via Telegram.';

    public function handle()
    {
        $today = Carbon::today()->toDateString();
        
        // ডাটাবেজ থেকে টেলিগ্রামের ক্রেডেনশিয়াল নেওয়া হচ্ছে
        $botToken = Setting::val('telegram_bot_token');
        $adminId = Setting::val('telegram_admin_id');

        // মেয়াদ শেষ হওয়া একটিভ ডোমেইনগুলো খোঁজা
        $expiredDomains = DB::table('user_domains')
            ->join('users', 'user_domains.user_id', '=', 'users.id')
            ->where('user_domains.status', 'active')
            ->whereDate('user_domains.expiry_date', '<', $today)
            ->select('user_domains.*', 'users.username')
            ->get();

        $processed = [];

        if ($expiredDomains->count() > 0) {
            foreach ($expiredDomains as $domain) {
                // ১. স্ট্যাটাস expired করে দেওয়া
                DB::table('user_domains')->where('id', $domain->id)->update(['status' => 'expired']);

                // ২. ক্লাউডফ্লেয়ার থেকে DNS রেকর্ড মুছে ফেলা
                $this->removeDNSFromCloudflare($domain->domain_name);

                $processed[] = [
                    'domain' => $domain->domain_name,
                    'user' => $domain->username,
                    'expiry' => $domain->expiry_date
                ];
            }

            // ৩. টেলিগ্রামে রিপোর্ট পাঠানো (যদি টোকেন ও আইডি সেভ করা থাকে)
            if ($botToken && $adminId) {
                $msg = "🚨 *AUTO-SUSPEND ALERT* 🚨\n\n";
                $msg .= "📅 Date: `" . date('d M Y, h:i A') . "`\n";
                $msg .= "📉 Total Suspended: `" . count($processed) . "`\n\n";
                foreach ($processed as $item) {
                    $msg .= "❌ `{$item['domain']}`\n👤 {$item['user']} | 📅 {$item['expiry']}\n---\n";
                }
                $this->sendTelegram($botToken, $adminId, $msg);
            }
            
            $this->info("Suspended " . count($processed) . " domains.");
        } else {
            // যদি কোনো ডোমেইন সাসপেন্ড না হয়
            if ($botToken && $adminId) {
                $msg = "✅ *DAILY CHECK REPORT*\n\n";
                $msg .= "📅 Date: `" . date('d M Y, h:i A') . "`\n";
                $msg .= "🛡 Status: *All Good*\n";
                $msg .= "ℹ️ Message: No domains expired today. All sites are active.";
                $this->sendTelegram($botToken, $adminId, $msg);
            }
            $this->info("No expired domains found. All good.");
        }
    }

    private function removeDNSFromCloudflare($fullDomain)
    {
        $settings = DB::table('subdomain_settings')->get();
        $creds = null;
        
        foreach ($settings as $setting) {
            if (str_ends_with($fullDomain, $setting->domain_name)) {
                $creds = $setting;
                break;
            }
        }

        if ($creds) {
            $zoneId = $creds->cloudflare_zone_id;
            $email = $creds->cloudflare_email;
            $key = $creds->cloudflare_api_key;
            
            $headers = [
                'X-Auth-Email' => $email,
                'X-Auth-Key' => $key,
                'Content-Type' => 'application/json'
            ];

            foreach ([$fullDomain, "www.".$fullDomain] as $name) {
                $response = Http::withHeaders($headers)
                                ->withoutVerifying()
                                ->get("https://api.cloudflare.com/client/v4/zones/{$zoneId}/dns_records?name={$name}");
                
                if ($response->successful()) {
                    $records = $response->json()['result'] ?? [];
                    foreach ($records as $rec) {
                        Http::withHeaders($headers)
                            ->withoutVerifying()
                            ->delete("https://api.cloudflare.com/client/v4/zones/{$zoneId}/dns_records/{$rec['id']}");
                    }
                }
            }
        }
    }

    private function sendTelegram($token, $chatId, $text)
    {
        $url = "https://api.telegram.org/bot{$token}/sendMessage";
        Http::withoutVerifying()->post($url, [
            'chat_id' => $chatId,
            'text' => $text,
            'parse_mode' => 'Markdown'
        ]);
    }
}
