<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Device;
use App\Models\NotificationTemplate;
use App\Models\User;
use App\Services\FirebasePushService;
use Illuminate\Http\Request;

class NotificationTemplatesController extends Controller
{
    public function index(FirebasePushService $push)
    {
        $templates = NotificationTemplate::orderBy('event')->get()->keyBy('event');
        $devices = Device::whereNotNull('fcm_token')->with('user')->get();
        $users = User::orderBy('name')->get(['id', 'name', 'email']);
        $pushReady = $push->isConfigured();

        return view('admin.notifications.index', compact('templates', 'devices', 'users', 'pushReady'));
    }

    public function update(Request $request, NotificationTemplate $template)
    {
        $data = $request->validate([
            'title'     => ['required', 'string', 'max:255'],
            'body'      => ['required', 'string', 'max:1000'],
            'image_url' => ['nullable', 'url', 'max:500'],
        ]);

        $template->update($data);

        return back()->with('success', 'Template "' . NotificationTemplate::EVENTS[$template->event]['label'] . '" saved.');
    }

    public function toggle(NotificationTemplate $template)
    {
        $template->update(['is_enabled' => !$template->is_enabled]);

        return back()->with('success',
            NotificationTemplate::EVENTS[$template->event]['label'] .
            ' notifications ' . ($template->is_enabled ? 'enabled' : 'disabled') . '.');
    }

    public function test(Request $request, NotificationTemplate $template, FirebasePushService $push)
    {
        $data = $request->validate([
            'device_id' => ['required', 'exists:devices,id'],
        ]);

        if (!$push->isConfigured()) {
            return back()->with('error', 'Firebase is not configured. Please upload your service account JSON in Settings → Integrations.');
        }

        $device = Device::find($data['device_id']);
        if (!$device || !$device->fcm_token) {
            return back()->with('error', 'This device has no FCM token registered.');
        }

        $rendered = $template->render([
            '{name}'       => $device->user?->name ?? 'Demo User',
            '{email}'      => $device->user?->email ?? 'demo@example.com',
            '{plan}'       => 'Pro',
            '{expires_at}' => now()->addMonth()->format('Y-m-d'),
            '{days}'       => '7',
        ]);

        $result = $push->sendToToken(
            $device->fcm_token,
            $rendered['title'],
            $rendered['body'],
            ['event' => $template->event],
            $template->image_url
        );

        if ($result['ok']) {
            return back()->with('success', 'Test notification sent to ' . ($device->user?->name ?? $device->device_id) . '.');
        }

        return back()->with('error', 'FCM returned an error: ' . (is_array($result['body']) ? json_encode($result['body']) : $result['body']));
    }

    public function sendManual(Request $request, FirebasePushService $push)
    {
        $data = $request->validate([
            'title'     => ['required', 'string', 'max:255'],
            'body'      => ['required', 'string', 'max:1000'],
            'image_url' => ['nullable', 'url', 'max:500'],
            'target'    => ['required', 'in:all,selected'],
            'user_ids'  => ['required_if:target,selected', 'nullable', 'array'],
            'user_ids.*'=> ['exists:users,id'],
        ]);

        if (! $push->isConfigured()) {
            return back()->with('error', 'Firebase is not configured. Please upload your service account JSON in Settings → Integrations.');
        }

        $query = Device::whereNotNull('fcm_token');
        if ($data['target'] === 'selected' && ! empty($data['user_ids'])) {
            $query->whereIn('user_id', $data['user_ids']);
        }
        $devices = $query->get();

        if ($devices->isEmpty()) {
            return back()->with('error', 'No registered devices found for the selected target.');
        }

        $sent = 0;
        $failed = 0;
        foreach ($devices as $device) {
            $result = $push->sendToToken(
                $device->fcm_token,
                $data['title'],
                $data['body'],
                ['event' => 'manual_broadcast'],
                $data['image_url'] ?? null
            );
            $result['ok'] ? $sent++ : $failed++;
        }

        $msg = "Sent to {$sent} device(s).";
        if ($failed > 0) {
            $msg .= " {$failed} failed.";
        }

        return back()->with('success', $msg);
    }
}
