<?php

namespace App\Http\Controllers;

use App\Models\CommunicationLog;
use App\Models\SchoolClass;
use App\Services\CommunicationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class CommunicationController extends Controller implements HasMiddleware
{
    public function __construct(private CommunicationService $comms)
    {
    }

    public static function middleware(): array
    {
        return [
            new Middleware('can:communication.view', only: ['index', 'logs']),
            new Middleware('can:communication.send', only: ['compose', 'send', 'preview']),
        ];
    }

    public function index(Request $request): View
    {
        $logs = CommunicationLog::with('sender')
            ->when($request->input('channel'), fn ($q, $v) => $q->where('channel', $v))
            ->when($request->input('status'), fn ($q, $v) => $q->where('status', $v))
            ->latest()->paginate(25)->withQueryString();

        return view('communication.logs', [
            'logs' => $logs,
            'channel' => $request->input('channel'),
            'status' => $request->input('status'),
        ]);
    }

    public function compose(): View
    {
        return view('communication.compose', [
            'classes' => SchoolClass::active()->orderBy('level')->get(),
        ]);
    }

    public function send(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'channel' => ['required', Rule::in(['sms', 'whatsapp', 'email'])],
            'audience' => ['required', Rule::in(['all_parents', 'class_parents', 'defaulters', 'all_staff', 'custom'])],
            'class_id' => ['nullable', 'required_if:audience,class_parents', 'exists:classes,id'],
            'custom' => ['nullable', 'required_if:audience,custom', 'string'],
            'subject' => ['nullable', 'required_if:channel,email', 'string', 'max:200'],
            'body' => ['required', 'string', 'max:2000'],
        ]);

        $result = $this->comms->send(
            $data['channel'], $data['audience'], $data['subject'] ?? null, $data['body'],
            ['class_id' => $data['class_id'] ?? null, 'custom' => $data['custom'] ?? null]
        );

        if ($result['sent'] === 0) {
            return back()->with('error', 'No recipients matched (missing phone/email for the chosen channel).')->withInput();
        }

        return redirect()->route('communication.index')
            ->with('success', "Message sent to {$result['sent']} recipient(s)".($result['skipped'] ? ", {$result['skipped']} skipped" : '').'.');
    }
}
