<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\AdminNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class PushNotificationController extends Controller
{
    public function index()
    {
        $notifications = AdminNotification::orderByDesc('created_at')->paginate(15);
        $settings = Setting::all()->pluck('value', 'key')->toArray();
        $hasConfig = !empty($settings['onesignal_app_id'] ?? null) && !empty($settings['onesignal_api_key'] ?? null);
        return view('admin.notifications.index', compact('notifications', 'hasConfig'));
    }

    public function create()
    {
        $settings = Setting::all()->pluck('value', 'key')->toArray();
        $hasConfig = !empty($settings['onesignal_app_id'] ?? null) && !empty($settings['onesignal_api_key'] ?? null);
        return view('admin.notifications.create', compact('settings', 'hasConfig'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:100',
            'message' => 'required|string|max:200',
            'url' => 'nullable|url|max:255',
            'image' => 'nullable|url|max:255',
            'image_file' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:4096',
        ]);

        $appId = Setting::where('key', 'onesignal_app_id')->value('value');
        $apiKey = Setting::where('key', 'onesignal_api_key')->value('value');

        if (!$appId || !$apiKey) {
            return back()->withErrors(['error' => 'OneSignal credentials are missing in Settings'])->withInput();
        }

        $imageUrl = null;
        $storedImagePath = null;
        if ($request->hasFile('image_file')) {
            $storedImagePath = $request->file('image_file')->store('notifications', 'public');
            $imageUrl = asset('storage/' . $storedImagePath);
        } elseif ($request->filled('image')) {
            $imageUrl = $request->image;
        }

        $payload = [
            'app_id' => $appId,
            'included_segments' => ['All'],
            'headings' => ['en' => $request->title],
            'contents' => ['en' => $request->message],
        ];

        if ($request->filled('url')) $payload['url'] = $request->url;
        if ($imageUrl) {
            $payload['big_picture'] = $imageUrl; // large image
            $payload['chrome_web_icon'] = $imageUrl;
        }

        $record = AdminNotification::create([
            'title' => $request->title,
            'message' => $request->message,
            'url' => $request->url,
            'image_path' => $storedImagePath,
            'image_url' => $imageUrl,
            'status' => 'queued',
        ]);

        try {
            $res = Http::withHeaders([
                'Authorization' => 'Basic ' . $apiKey,
                'Content-Type' => 'application/json'
            ])->post('https://onesignal.com/api/v1/notifications', $payload);

            if ($res->failed()) {
                $record->update(['status' => 'failed']);
                return back()->withErrors(['error' => 'Failed to send notification: ' . $res->body()])->withInput();
            }

            $resp = $res->json();
            $record->update([
                'status' => 'sent',
                'onesignal_id' => $resp['id'] ?? null,
            ]);

            return redirect()->route('admin.notifications.index')->with('success', 'Push notification sent successfully.');
        } catch (\Throwable $e) {
            $record->update(['status' => 'failed']);
            return back()->withErrors(['error' => 'Error sending notification: ' . $e->getMessage()])->withInput();
        }
    }
}
