<?php

namespace Chat;

class Gruppe {
  
  

  
  

    // --- Statische Methoden ---
  
  public static function subscribeAction() { 
    
    
    // --- BLOCK: access ---
    if(!((!\FOP\User::getIsGuest()))) throw new \FOP\AccessDeniedException();
    // --- BLOCK: main ---
    
	error_log(json_encode($_POST));
		$itemid = $_POST['itemid'];
		$publickey = $_POST['publickey'];
		// Kombination aus Table, ItemId, PublicKey muss eindeutig sein
		$existingrows = \FOP\Database::query('SELECT '.qi('ID').' FROM '.qi('ChatgruppeSubscriptions').' WHERE '.qi('ItemId').' = ' . \FOP\Database::quote($itemid) . ' AND '.qi('PublicKey').' = ' . \FOP\Database::quote($publickey))->fetchAll();
		if (count($existingrows) == 0){
			// Check, ob angefragtes Item existiert..
			$item = \Tables\Gruppe::view(intval($itemid));

			// Check, ob eine Subscription mit dem jeweiligen PublicKey hinterlegt ist
			$keycount = \FOP\Database::query('SELECT count(*) FROM fop_pushsubscriptions WHERE userid = ' . \FOP\Database::quote(\FOP\User::getID()) )->fetchAll()[0][0];/*. ' AND '.qi('publicKey').' = ' . \FOP\Database::quote($publickey)*/
			if($keycount == 0) throw new \Exception('PublicKey not defined');

			\FOP\Database::query('INSERT INTO '.qi('ChatgruppeSubscriptions').'('.qi('ItemId').','.qi('Sender').','.qi('PublicKey').','.qi('Timestamp').') VALUES(' . \FOP\Database::quote($itemid) . ',' . \FOP\Database::quote(\FOP\User::getID()) . ',' . \FOP\Database::quote($publickey) . ', '.\FOP\Database::sessionVarSQL('time').')');
		} else {
			$existingid = $existingrows[0][0];
			\FOP\Database::query('UPDATE '.qi('ChatgruppeSubscriptions').' SET '.qi('Timestamp').' = '.\FOP\Database::sessionVarSQL('time').' WHERE '.qi('ID').' = ' . $existingid);
		}

		return self::getAction($itemid, $_POST['itemcount']);
	
    
  }

  public static function sendAction() { 
    
    
    // --- BLOCK: access ---
    if(!((!\FOP\User::getIsGuest()))) throw new \FOP\AccessDeniedException();
    // --- BLOCK: main ---
    
		// Check, ob angefragtes Item existiert..

		$itemid = intval($_POST['itemid']);
		$item = \Tables\Gruppe::view($itemid);
		$itemcount = 10;
		if(!isset($_POST['message'])) throw new \Exception('Message is undefined');

		$message = $_POST['message'];
		if(strlen($message) > 128) throw new \Exception('Message too long');

		$c = \FOP\Database::query('SELECT count(*) FROM fop_chat WHERE '.qi('table').'="gruppe" AND ItemId=' .
		\FOP\Database::quote($itemid) . ' AND '.qi('Sender').' = ' . \FOP\Database::quote(\FOP\User::getID()) .' AND '.qi('Timestamp').' >= '.\FOP\Database::sessionVarSQL('time').'-30')->fetchAll()[0][0];

		if($c >= 3) throw new \Exception('Rate limit exceeded');

		// Nachricht einfügen
		\FOP\Database::query('INSERT INTO fop_chat('.qi('ItemId').', '.qi('Sender').', '.qi('Message').', '.qi('ReportCount').', '.qi('Timestamp').', '.qi('table').') VALUES('. $itemid . ',' . \FOP\User::getID() . ',' . \FOP\Database::quote($message) . ',0,'.\FOP\Database::sessionVarSQL('time').', "gruppe")');

		// User abfragen, die im Chat sind
		$userrows = \FOP\Database::query('SELECT '.qi('PublicKey').' FROM '.qi('ChatgruppeSubscriptions').' WHERE '.qi('ItemId').' = ' . $itemid)->fetchAll();
		$users = array();
		foreach($userrows as $userrow){
			array_push($users, $userrow[0]);
		}
		if(count($users) > 0) {
			$subs = \FOP\Push::getSubscriptionsByKey($users);
			\FOP\Push::sendMessage($subs, json_encode(['action' => 'chat', 'tbl' => 'gruppe', 'itemid' => $itemid,
			'message' => $message, 'user' => \FOP\User::getID(), 'sender' => \FOP\User::getUsername(), 'timestamp' => time()]));
		}
		return self::getAction($itemid, $itemcount);
	
    
  }

  public static function clearSubscriptions() { 
    
    
    // --- BLOCK: main ---
    
		\FOP\Database::query('DELETE FROM '.qi('ChatgruppeSubscriptions').' WHERE '.qi('Timestamp').' < '.\FOP\Database::sessionVarSQL('time').'-60*60'); // Eine Stunde alte Subscriptions verfallen automatisch
	
    
  }

  public static function reportAction($messageId) { 
    
    
    // --- BLOCK: access ---
    if(!((!\FOP\User::getIsGuest()))) throw new \FOP\AccessDeniedException();
    // --- BLOCK: main ---
    
		\FOP\Database::query('UPDATE fop_chat SET '.qi('ReportCount').' = '.qi('ReportCount').' + 1 WHERE '.qi('ID').' = ' . intval($messageId));
	
    
  }

  public static function getAction($itemid, $itemcount = 10 ) { 
    
    
    // --- BLOCK: access ---
    if(!((!\FOP\User::getIsGuest()))) throw new \FOP\AccessDeniedException();
    // --- BLOCK: main ---
    
		if($itemcount < 1) $itemcount = 1;
		if($itemcount > 1000) $itemcount = 1000;

		// Chatnachrichten ausgeben
		$messagerows = \FOP\Database::query('SELECT c.'.qi('ItemId').', (SELECT u.'.qi('email').' FROM '.qi('mitglied').' u WHERE c.'.qi('Sender').' = u.'.qi('ID').') AS '.qi('Sender').', '.qi('Message').', '.qi('ReportCount').', '.qi('Timestamp').', '.qi('ID').' AS '.qi('messageID').', '.qi('Sender').' AS '.qi('User').' FROM fop_chat c WHERE '.qi('ItemId').' = ' . \FOP\Database::quote($itemid) . ' AND '.qi('table').' = "gruppe" ORDER BY '.qi('timestamp').' DESC LIMIT ' . (intval($itemcount)+1))->fetchAll();

		$messages = array();
		foreach($messagerows as $row){
			array_push($messages, ['ID' => intval($row['messageID']), 'timestamp' => intval($row['Timestamp']), 'sender' => is_null($row['Sender']) ? _('guest') : $row['Sender'], 'message' => $row['Message'], 'user' => ($row['User'])]);
		}
		return array_reverse($messages);
	
    
  }


  
  

  
  
}



