<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class OneSignalService
{
	protected $appId;
	protected $restApiKey;
	protected $userAuthKey;
	
	public function __construct()
	{
		$this->appId = config('services.onesignal.app_id');
		$this->restApiKey = config('services.onesignal.rest_api_key');
		$this->userAuthKey = config('services.onesignal.user_auth_key');
	}
	
	/**
	 * Send notification to specific user by OneSignal player ID
	 */
	public function sendNotificationToUser($playerId, $title, $body, $data = [])
	{
		return $this->sendNotification([
			'include_player_ids' => [$playerId],
			'headings'           => ['ja' => $title, 'en' => $title],
			'contents'           => ['ja' => $body, 'en' => $body],
			'data'               => $data,
			'web_url'            => url('/'),
			'chrome_web_icon'    => url('/images/logo.png'),
			'firefox_icon'       => url('/images/logo.png'),
			'chrome_icon'        => url('/images/logo.png'),
			'large_icon'         => url('/images/logo.png'),
			'ios_sound'          => 'default',
			'android_sound'      => 'default',
			'web_push_topic'     => 'nakai-chat'
		]);
	}
	
	/**
	 * Send notification to multiple users by OneSignal player IDs
	 */
	public function sendNotificationToUsers($playerIds, $title, $body, $data = [])
	{
		if (empty($playerIds)) {
			return false;
		}
		
		return $this->sendNotification([
			'include_player_ids' => $playerIds,
			'headings'           => ['ja' => $title, 'en' => $title],
			'contents'           => ['ja' => $body, 'en' => $body],
			'data'               => $data,
			'web_url'            => url('/'),
			'chrome_web_icon'    => url('/images/logo.png'),
			'firefox_icon'       => url('/images/logo.png'),
			'chrome_icon'        => url('/images/logo.png'),
			'large_icon'         => url('/images/logo.png'),
			'ios_sound'          => 'default',
			'android_sound'      => 'default',
			'web_push_topic'     => 'nakai-chat'
		]);
	}
	
	/**
	 * Send notification to users by external user IDs (your user IDs)
	 */
	public function sendNotificationToExternalUsers($externalUserIds, $title, $body, $data = [])
	{
		if (empty($externalUserIds)) {
			return false;
		}
		
		return $this->sendNotification([
			'include_external_user_ids' => $externalUserIds,
			'headings'                  => ['ja' => $title, 'en' => $title],
			'contents'                  => ['ja' => $body, 'en' => $body],
			'data'                      => $data,
			'web_url'                   => url('/'),
			'chrome_web_icon'           => url('/images/logo.png'),
			'firefox_icon'              => url('/images/logo.png'),
			'chrome_icon'               => url('/images/logo.png'),
			'large_icon'                => url('/images/logo.png'),
			'ios_sound'                 => 'default',
			'android_sound'             => 'default',
			'web_push_topic'            => 'nakai-chat'
		]);
	}
	
	/**
	 * Base method to send notification via OneSignal API
	 */
	protected function sendNotification($payload)
	{
		try {
			$payload['app_id'] = $this->appId;
			
			$response = Http::withHeaders([
				'Authorization' => 'Basic ' . $this->restApiKey,
				'Content-Type'  => 'application/json'
			])->post('https://onesignal.com/api/v1/notifications', $payload);
			
			if ($response->successful()) {
				$result = $response->json();
				Log::info('OneSignal notification sent successfully', [
					'id'         => $result['id'] ?? null,
					'recipients' => $result['recipients'] ?? 0
				]);
				return $result;
			} else {
				Log::error('OneSignal notification failed', [
					'status'   => $response->status(),
					'response' => $response->body()
				]);
				return false;
			}
		} catch (\Exception $e) {
			Log::error('OneSignal notification exception: ' . $e->getMessage());
			return false;
		}
	}
	
	/**
	 * Get device info by player ID
	 */
	public function getDevice($playerId)
	{
		try {
			$response = Http::withHeaders([
				'Authorization' => 'Basic ' . $this->restApiKey
			])->get("https://onesignal.com/api/v1/players/{$playerId}?app_id={$this->appId}");
			
			if ($response->successful()) {
				return $response->json();
			}
			
			return false;
		} catch (\Exception $e) {
			Log::error('OneSignal get device failed: ' . $e->getMessage());
			return false;
		}
	}
	
	/**
	 * Get all devices for the app
	 */
	public function getDevices($limit = 300, $offset = 0)
	{
		try {
			$response = Http::withHeaders([
				'Authorization' => 'Basic ' . $this->restApiKey
			])->get("https://onesignal.com/api/v1/players?app_id={$this->appId}&limit={$limit}&offset={$offset}");
			
			if ($response->successful()) {
				return $response->json();
			}
			
			return false;
		} catch (\Exception $e) {
			Log::error('OneSignal get devices failed: ' . $e->getMessage());
			return false;
		}
	}
}