<?php

function send_slack($adminpath,$lgid,$module,$msg="No message composed",$debug=0)
{
	include($adminpath."/dbopen.php");
	
	## Get Slack configuration
	$query="SELECT SQL_NO_CACHE * FROM ootp_sql_admin WHERE setting LIKE 'slack%'";
   	$result=mysqli_query($db,$query);
	if (mysqli_num_rows($result)) 
   	{
		while ($row=mysqli_fetch_array($result))
		{
			  $scope=$row['scope'];
			  $module=$row['module'];
			  $setting=$row['setting'];
			  $identifier=$row['identifier'];
			  $value=$row['value'];

			  $settings[$scope][$module][$identifier][$setting]=$value;
		}
		if ($debug==1) {print_r($settings);}
	}

	mysqli_close($db);

	## Validate Slack integration is on
	if ($settings['ALL']['admin'][-1]['slackEnable']!=1) {return false;}

	## Compose Slack JSON
	$serviceURL = $settings['ALL']['admin'][-1]['slackServiceURL'];
	switch ($module)
	{
		case 'draft':
		case 'Draft': $channel=$settings[$lgid]['Draft'][-1]['slackDraftChannel']; break;
		case 'trade': $channel=$settings['ALL']['admin'][-1]['slackTradeChannel']; break;
		default     : $channel=$settings['ALL']['admin'][-1]['slackDefChannel'];   break;
	}
	if ($channel=="") {$channel=$settings['ALL']['admin'][-1]['slackDefChannel'];}

	$dataArray = Array("channel" => $channel);
	if ($settings['ALL']['admin'][-1]['slackUser']!="") {$dataArray['username']=$settings['ALL']['admin'][-1]['slackUser'];}
	if ($settings['ALL']['admin'][-1]['slackIcon']!="") {$dataArray['icon_emoji']=$settings['ALL']['admin'][-1]['slackIcon'];}
	$dataArray['text']=$msg;
	
	$data = "payload=" . json_encode($dataArray);
		
	## Send Slack message
	if (($debug!=1)&&($_GET['showq']!=1))
	{
		$ch = curl_init($serviceURL);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
		curl_exec($ch);
		$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // $retcode > 400 -> not found, $retcode = 200, found.
		if ($retcode==200)
		{	
			$retVal=true;
		}
		else
		{
			echo curl_error($ch);
			echo "<br>\n";
			echo $data;
			$retVal=false;
		}
		curl_close($ch);
	}
	else
	{
		echo "<b>Slack Test:</b><br/>\n";
		echo "Service URL: $serviceURL<br/>\n";
		echo "<br/>\n";
		echo $data;
		echo "<br/>\n";
		echo "Lg ID: ".$lgid;
		echo "<br/>\n";
		$retVal=false;
	}

	return $retVal;
}

?>
