<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use App\Models\TextAd;
use App\Models\Room;
use App\Services\TcpSocketClient;

class RotateTextAd extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ads:rotate';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '輪播下一則啟用中的文字廣告';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $ads = TextAd::where('is_active', true)->orderBy('id')->get();

        if ($ads->isEmpty()) {
            $this->info('❌ 沒有啟用中的廣告。');
            return;
        }

        $nextTime = Cache::get('text_ad_next_time');

        // 還沒到下一次播放時間就跳出
        if ($nextTime && now()->lt($nextTime)) {
            $this->info("⏳ 尚未到下一次播放時間（下次播放：{$nextTime}）");
            return;
        }

        $index = Cache::get('text_ad_current_index', 0) % $ads->count();
        $ad = $ads[$index];

        $rooms = Room::where('type', '!=', 'svr')
            ->where('is_online', 1)
            ->get(['internal_ip', 'port']);
        // 📨 發送 TCP 廣告
        try {
            $prefix = "全部({$ad->color->labels()})-";
            $content = $prefix . $ad->content;
            foreach ($rooms as $room) {
                $client = new TcpSocketClient($room->internal_ip, $room->port);
                $response = $client->send($content);

                $this->info("✅ 已推送廣告 #{$ad->id} 至 {$room->internal_ip}:{$room->port}");
            }
        } catch (\Throwable $e) {
            $this->error("❌ 發送失敗：{$room->internal_ip}:{$room->port} - " . $e->getMessage());
        }

        // 🕒 更新下次播放時間
        Cache::put('text_ad_next_time', now()->addMinutes($ad->duration));

        // 📌 更新下次播放 index
        Cache::put('text_ad_current_index', ($index + 1) % $ads->count());
    }
}
