<?php

namespace App\Http\Controllers;

use App\Models\SmsCampaign;
use App\Models\Subscriber;
use Illuminate\Http\Request;

class CommunicationController extends Controller
{
    public function index()
    {
        $campaigns = SmsCampaign::orderBy('created_at', 'desc')->get();
        $subscribers = Subscriber::select('id', 'name', 'phone', 'email')->get();
        return view('admin.communications.sms', compact('campaigns', 'subscribers'));
    }

    public function sendSms(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'message_body' => 'required|string',
            'recipients_count' => 'required|integer|min:1',
        ]);

        $charLength = strlen($validated['message_body']);
        $segments = max(1, ceil($charLength / 160));

        SmsCampaign::create([
            'name' => $validated['name'],
            'message_body' => $validated['message_body'],
            'recipients_count' => $validated['recipients_count'],
            'segments_count' => $segments,
            'channel' => 'SMS',
            'status' => 'Completed',
            'sent_at' => now(),
        ]);

        return redirect()->route('admin.communications.sms')->with('success', "SMS campaign '{$validated['name']}' dispatched to {$validated['recipients_count']} subscribers ({$segments} segments)!");
    }
}
