<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Seller;
use App\Models\Buyer;
use App\Models\Plan;
use App\Services\NotificationService;
use Illuminate\Http\Request;

class BroadcastController extends Controller
{
    /**
     * Show broadcast message form
     */
    public function index()
    {
        $plans = Plan::where('is_active', true)->get();
        $stats = [
            'total_sellers' => Seller::count(), // Direct count from Seller model
            'total_buyers' => Buyer::count(),   // Direct count from Buyer model
        ];
        
        return view('admin.broadcast.index', compact('plans', 'stats'));
    }

    /**
     * Send broadcast message
     */
    public function send(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:100',
            'message' => 'required|string|max:500',
            'target' => 'required|in:all,sellers,buyers,plan',
            'plan_id' => 'required_if:target,plan|nullable|exists:plans,id',
            'icon' => 'nullable|string|max:50',
            'icon_color' => 'nullable|in:primary,success,warning,danger,info',
        ]);

        $userIds = [];

        switch ($request->target) {
            case 'all':
                $userIds = User::pluck('id')->toArray();
                break;
            case 'sellers':
                // Get user IDs from Seller model
                $userIds = Seller::whereNotNull('user_id')->pluck('user_id')->toArray();
                break;
            case 'buyers':
                // Get user IDs from Buyer model
                $userIds = Buyer::whereNotNull('user_id')->pluck('user_id')->toArray();
                break;
            case 'plan':
                $userIds = Seller::whereHas('subscription', function($q) use ($request) {
                    $q->where('plan_id', $request->plan_id)->where('status', 'active');
                })->pluck('user_id')->toArray();
                break;
        }

        if (empty($userIds)) {
            return redirect()->back()->with('error', 'No users found for the selected target.');
        }

        $count = NotificationService::sendToMany(
            $userIds,
            'system',
            $request->title,
            $request->message,
            null,
            $request->icon ?? 'bi-megaphone',
            $request->icon_color ?? 'primary'
        );

        return redirect()->back()->with('success', "Broadcast sent to {$count} users successfully!");
    }
}
