<?php

function send_discord($adminpath,$lgid,$srcModule,$dataArray="",$debug=0)
{
    if (
        ($lgid=="") ||
        ($srcModule=="") ||
        ($dataArray=="")
        ) {return false;}
    
	include($adminpath."/dbopen.php");
	
    ## Get Discord Settings
    $query="SELECT * FROM ootp_sql_admin WHERE setting LIKE 'discord%'";
    $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 Discord integration is on
	if ($settings['ALL']['admin'][-1]['discordEnable']!=1) {return false;}

	## Compose Slack JSON
    $serviceURL = $settings['ALL']['admin'][-1]['discordPrimaryURL'];
	switch ($srcModule)
	{
		case 'draft':
		case 'Draft':
            if ($settings[$lgid]['Draft'][-1]['discordDraftURL']!="")
                {$serviceURL = $settings[$lgid]['Draft'][-1]['discordDraftURL'];}
            break;
		case 'trade':
            if ($settings['ALL']['admin'][-1]['discordTradeURL']!="")
                {$serviceURL = $settings['ALL']['admin'][-1]['discordTradeURL'];}
            break;
		default     :
            // Use default defined before switch statement
            break;
	}
	
	$json_data = json_encode($dataArray);
		
	## Send Discord message
	if (($debug!=1)&&($_GET['showq']!=1))
	{
		$ch = curl_init($serviceURL);
        
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
        curl_setopt( $ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_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)||($retcode==204))
        {
            $retVal=true;
        }
        else
        {
            echo "Discord return code: $retcode</br>";
            echo "Curl error: ".curl_error($ch);
            echo "<br>\n";
            echo $json_data;
        }

        curl_close($ch);
      }
      else
      {
          echo "<b>Discord Test:</b><br/>\n";
          echo "Service URL: $serviceURL<br/>\n";
          echo "<br/>\n";
          echo $json_data;
          echo "<br/>\n";
          echo "<br/>\n";
          $retVal=false;
      }

	return $retVal;
}

?>
