<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Reader;
use App\Models\NotificationTemplate;
use App\Models\NotificationHistory;
use App\Services\WhatsAppService;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function index()
    {
        $templates = NotificationTemplate::where('active', true)->get();
        $readers = Reader::where('status', 'active')->count();
        $history = NotificationHistory::orderBy('created_at', 'desc')->limit(50)->get();

        return view('admin.notifications.index', compact('templates', 'readers', 'history'));
    }

    public function send(Request $request)
    {
        $validated = $request->validate([
            'template_id' => 'required|exists:notifications_templates,id',
            'reader_ids' => 'nullable|array',
            'send_to_all' => 'boolean',
            'variables' => 'nullable|array',
        ]);

        $template = NotificationTemplate::findOrFail($validated['template_id']);
        $whatsapp = app(WhatsAppService::class);

        // Selecionar leitores
        if ($validated['send_to_all'] ?? false) {
            $readers = Reader::where('status', 'active')->get();
        } else {
            $readers = Reader::whereIn('id', $validated['reader_ids'] ?? [])->get();
        }

        $sent = 0;
        $failed = 0;

        foreach ($readers as $reader) {
            try {
                // Renderizar template
                $variables = array_merge($validated['variables'] ?? [], [
                    'nome' => $reader->name,
                ]);
                
                $message = $template->render($variables);

                // Enviar
                $result = $whatsapp->sendText($reader->whatsapp_number, $message);

                // Salvar histórico
                NotificationHistory::create([
                    'reader_id' => $reader->id,
                    'template_id' => $template->id,
                    'type' => 'whatsapp',
                    'to' => $reader->whatsapp_number,
                    'message' => $message,
                    'variables' => $variables,
                    'status' => $result['success'] ? 'sent' : 'failed',
                    'api_response' => json_encode($result),
                    'sent_at' => $result['success'] ? now() : null,
                ]);

                if ($result['success']) {
                    $sent++;
                    $reader->update(['last_notification_at' => now()]);
                } else {
                    $failed++;
                }
            } catch (\Exception $e) {
                $failed++;
                NotificationHistory::create([
                    'reader_id' => $reader->id,
                    'template_id' => $template->id,
                    'type' => 'whatsapp',
                    'to' => $reader->whatsapp_number,
                    'message' => $message ?? '',
                    'status' => 'failed',
                    'error_message' => $e->getMessage(),
                ]);
            }
        }

        return redirect()->route('admin.notifications.index')
            ->with('success', "Notificações enviadas! Sucesso: {$sent}, Falhas: {$failed}");
    }
}

