<?php

namespace App\Events;

use App\User;
use App\UserConversation;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Message;
use App\Services\PWAPushService;

class NewMessage implements ShouldBroadcast
{
	use Dispatchable, InteractsWithSockets, SerializesModels;
	
	public $message;
	
	public function __construct(Message $message)
	{
		$this->message = $message;
		
		// Set new message badge for other participants (excluding sender)
		$this->setNewMessageBadge();
		
		// Send PWA notifications to conversation participants (excluding sender)
		$this->sendPWANotifications();
	}
	
	public function broadcastWith()
	{
		return [
			'id'                   => $this->message->id,
			'conversation_id'      => $this->message->conversation_id,
			'sender_id'            => $this->message->sender_id,
			'sender_name'          => $this->message->sender ? $this->message->sender->name : 'Worker',
			'sender_furigana_name' => $this->message->sender ? $this->message->sender->furigana_name : null,
			'sender_avatar'        => $this->message->sender ? $this->message->sender->avatar : 'avatar.png',
			'type'                 => $this->message->type,
			'content'              => $this->message->content,
			'content_type'         => $this->message->content_type,
			'file_path'            => $this->message->file_path,
			'is_read'              => $this->message->is_read,
			'read_at'              => $this->message->read_at,
			'created_at'           => $this->message->created_at,
		];
	}
	
	public function broadcastOn()
	{
		$channels = [];
		
		// Broadcast to conversation channel (existing functionality)
		$channels[] = new PrivateChannel('chat.conversion.' . $this->message->conversation->id);
		
		// Broadcast to all users in conversation (for global notifications)
		$userConversations = UserConversation::where('conversation_id', $this->message->conversation->id)
			->where('user_id', '!=', $this->message->sender_id) // Exclude sender
			->get();
		
		foreach ($userConversations as $userConversation) {
			$channels[] = new PrivateChannel('user.' . $userConversation->user_id);
		}
		
		return $channels;
	}
	
	/**
	 * Set new message badge for conversation participants (excluding sender)
	 */
	private function setNewMessageBadge()
	{
		try {
			// Only set badge if sender is not the current user viewing the conversation
			$conversation = $this->message->conversation;
			if ($conversation) {
				// Set badge for the conversation
				$conversation->update(['has_new_message_badge' => true]);
			}
		} catch (\Exception $e) {
			\Log::error('Failed to set new message badge: ' . $e->getMessage(), [
				'message_id'      => $this->message->id,
				'conversation_id' => $this->message->conversation->id
			]);
		}
	}
	
	/**
	 * Send PWA notifications to conversation participants
	 */
	private function sendPWANotifications()
	{
		try {
			// Get all users in the conversation except the sender
			$listUsers = UserConversation::where('user_id', '!=', $this->message->sender_id)
				->where('conversation_id', $this->message->conversation->id)
				->get();
			
			if ($listUsers->isEmpty()) {
				return;
			}
			
			// Get sender information
			$sender = User::find($this->message->sender_id);
			$senderName = $sender ? $sender->name : '不明なユーザー';
			
			// Prepare notification content
			$title = '中井保温工業 - 新着メッセージ';
			$body = $senderName . ': ' . mb_substr($this->message->content, 0, 50);
			if (mb_strlen($this->message->content) > 50) {
				$body .= '...';
			}
			
			// Prepare notification data
			$notificationData = [
				'conversation_id' => $this->message->conversation->id,
				'message_id'      => $this->message->id,
				'sender_id'       => $this->message->sender_id,
				'url'             => '/conversation/' . $this->message->conversation->id
			];
			
			// Get user IDs for batch notification
			$userIds = $listUsers->pluck('user_id')->toArray();
			
			// Send PWA notifications
			$pwaService = app(PWAPushService::class);
			$pwaService->sendNotificationToUsers($userIds, $title, $body, $notificationData);
			
			\Log::info('PWA notifications sent for message', [
				'message_id'      => $this->message->id,
				'conversation_id' => $this->message->conversation->id,
				'recipient_count' => count($userIds)
			]);
			
		} catch (\Exception $e) {
			\Log::error('Failed to send PWA notifications: ' . $e->getMessage(), [
				'message_id'      => $this->message->id,
				'conversation_id' => $this->message->conversation->id
			]);
		}
	}
}
