<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\User;
use App\Models\Notification;
use App\Models\NotificationDelivery;
use App\Services\FirebaseService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class PushNotificationSettingController extends Controller
{
    protected $firebaseService;

    public function __construct(FirebaseService $firebaseService)
    {
        $this->firebaseService = $firebaseService;
    }

    /**
     * Display the push notification settings.
     */
    public function index()
    {
        $settings = [
            'firebase_server_key' => Setting::where('key', 'firebase_server_key')->value('value') ?? config('services.firebase.server_key'),
            'firebase_sender_id' => Setting::where('key', 'firebase_sender_id')->value('value'),
            'firebase_project_id' => Setting::where('key', 'firebase_project_id')->value('value'),
            'firebase_api_url' => Setting::where('key', 'firebase_api_url')->value('value') ?? 'https://fcm.googleapis.com/fcm/send',
        ];

        return view('admin.settings.notifications', [
            'settings' => $settings,
            'configured' => $this->firebaseService->validateConfiguration(),
            'status' => $this->firebaseService->getConfigurationStatus()
        ]);
    }

    /**
     * Update the push notification settings.
     */
    public function update(Request $request)
    {
        $validated = $request->validate([
            'firebase_server_key' => 'nullable|string',
            'firebase_sender_id' => 'nullable|string',
            'firebase_project_id' => 'nullable|string',
            'firebase_api_url' => 'nullable|url',
        ]);

        foreach ($validated as $key => $value) {
            Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $value]
            );
        }

        return redirect()->back()->with('success', 'Push notification settings updated successfully!');
    }

    /**
     * Send a test push notification.
     */
    public function test(Request $request)
    {
        $user = User::whereNotNull('device_token')->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'No user found with a device token to test with.'
            ], 422);
        }

        $notification = new Notification([
            'title' => 'Test Notification',
            'message' => 'This is a test notification from the admin panel.',
            'status' => 'testing',
        ]);

        $delivery = new NotificationDelivery([
            'user_id' => $user->id,
            'status' => 'pending'
        ]);

        $success = $this->firebaseService->sendPushNotification($user, $notification, $delivery);

        if ($success) {
            return response()->json([
                'success' => true,
                'message' => 'Test notification sent successfully to ' . $user->name
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Failed to send test notification. Check logs for details.'
        ], 500);
    }
}
