<?php

namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Controller;
use App\Services\Api\API;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class BroadcastController extends Controller
{
    protected API $api;

    protected array $channels = [
        0 => 'General',
        1 => 'Global',
        2 => 'Group',
        3 => 'Clan',
        4 => 'Unknown',
        5 => 'Notice',
        6 => 'Orange Notice',
        7 => 'Trade',
        8 => 'Unknown',
        9 => 'Broadcast',
        10 => 'Blue Notice',
        11 => 'Pink',
        12 => 'Messenger',
        13 => 'White',
        14 => 'White Notice',
        15 => 'Cross-Server',
    ];

    public function __construct(API $api)
    {
        $this->api = $api;
    }

    /**
     * Display broadcast page
     */
    public function index(): Response
    {
        // Get recent broadcasts from history
        $history = DB::table('broadcast_history')
            ->orderBy('created_at', 'desc')
            ->limit(20)
            ->get();

        $serverOnline = $this->api->serverOnline();

        return Inertia::render('admin/system/broadcast/index', [
            'channels' => $this->channels,
            'history' => $history,
            'serverOnline' => $serverOnline,
        ]);
    }

    /**
     * Send broadcast message to game
     */
    public function send(Request $request)
    {
        $request->validate([
            'message' => 'required|string|max:500',
            'channel' => 'required|integer|min:0|max:15',
            'sender_role_id' => 'nullable|integer',
        ]);

        if (! $this->api->serverOnline()) {
            return redirect()->back()->with('error', 'Game server is offline!');
        }

        $message = $request->input('message');
        $channel = $request->input('channel');
        $senderRoleId = $request->input('sender_role_id', 0);

        try {
            // Send broadcast using WorldChat API
            $result = $this->api->WorldChat($senderRoleId, $message, $channel);

            // Save to history
            DB::table('broadcast_history')->insert([
                'user_id' => Auth::id(),
                'sender_role_id' => $senderRoleId,
                'channel' => $channel,
                'channel_name' => $this->channels[$channel] ?? 'Unknown',
                'message' => $message,
                'status' => $result ? 'sent' : 'failed',
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            if ($result) {
                return redirect()->back()->with('success', 'Broadcast message sent successfully!');
            } else {
                return redirect()->back()->with('error', 'Failed to send broadcast message!');
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Error: '.$e->getMessage());
        }
    }

    /**
     * Get broadcast history
     */
    public function history(Request $request)
    {
        $perPage = $request->input('per_page', 20);

        $history = DB::table('broadcast_history')
            ->leftJoin('users', 'broadcast_history.user_id', '=', 'users.id')
            ->select(
                'broadcast_history.*',
                'users.name as admin_name',
                'users.email as admin_email'
            )
            ->orderBy('broadcast_history.created_at', 'desc')
            ->paginate($perPage);

        return response()->json($history);
    }

    /**
     * Delete broadcast history
     */
    public function clearHistory()
    {
        DB::table('broadcast_history')->truncate();

        return redirect()->back()->with('success', 'Broadcast history cleared successfully!');
    }
}
