<?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;
        }

        $rooms = Room::where('type', '!=', 'svr')
            ->where('is_online', 1)
            ->get(['id', 'name', 'internal_ip', 'port']);

        foreach ($rooms as $room) {
            $nextTimeKey = "text_ad_next_time_{$room->id}";
            $indexKey = "text_ad_index_{$room->id}";

            $nextTime = Cache::get($nextTimeKey);

            // 還沒到時間，就跳過這個房間
            if ($nextTime && now()->lt($nextTime)) {
                $this->info("⏳ 房間 {$room->id} 尚未到下一次播放時間（下次播放：{$nextTime}）");
                continue;
            }

            $index = Cache::get($indexKey, 0) % $ads->count();
            $ad = $ads[$index];
            $roomCode = str_pad($room->name, 4, '0', STR_PAD_LEFT);
            $content = "{$roomCode}({$ad->color->labels()})-" . $ad->content;

            try {
                $client = new TcpSocketClient($room->internal_ip, $room->port);
                $response = $client->send($content);

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

            // 更新此房間的播放狀態
            Cache::put($nextTimeKey, now()->addMinutes($ad->duration));
            Cache::put($indexKey, ($index + 1) % $ads->count());
        }
    }
}
