<?php

  session_start();



  if ($_SESSION['user_is_commish']!=1)

  {

	  header('Location: '.$_SERVER['HTTP_REFERER']);

  }



  $debug=$_POST['debug'];



  include($_SESSION['adminpath']."/dbopen.php");

  ## Get Slack/Discord/Email Details
  $query="SELECT setting,value,identifier FROM ootp_sql_admin WHERE setting LIKE '%slack%' OR setting LIKE '%discord%' OR setting IN ('sendUpdateEmails','ServerURL','StatsLabPath');";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);

  if (mysqli_num_rows($result)>0)
  {
	  while ($row=mysqli_fetch_array($result))
	  {
		  $setting=$row['setting'];
		  $settings[$setting]=$row['value'];
	  }

      ## Define StatsLab Link
      if (strpos($settings['StatsLabPath'],'http') !== false)
        {
            $slPath=$settings['StatsLabPath'];
        }
        else
        {
            $slPath=$settings['ServerURL'].$settings['StatsLabPath'];
        }

      ## Slack Update Message ##
	  if (($settings['slackEnable']==1)&&($settings['sendUpdateSlack']==1))
	  {
		  $serviceURL = $settings['slackServiceURL'];
		  $msg = "StatsLab updated to ".date("F j, Y",strtotime($_SESSION['lgdate']));
		  $dataArray = Array (
				"channel"    => $settings['slackDefChannel'],
				"username"   => $settings['slackUser'],
				"icon_emoji" => $settings['slackIcon'],
				"text"       => $msg
		  );

          $data = "payload=" . json_encode($dataArray);

          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) {header('Location: '.$_SERVER['HTTP_REFERER']);}
			else
			{
				echo curl_error($ch);
				echo "<br>\n";
				echo $data;
			}

			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 "<br/>\n";
		  }
	  }

      ## Discord Update Message ##
      if (($settings['discordEnable']==1)&&($settings['sendUpdateDiscord']==1))
      {
          $serviceURL = $settings['discordPrimaryURL'];
          $msg = "[StatsLab](".$slPath.") updated to ".date("F j, Y",strtotime($_SESSION['lgdate']));
          $dataArray = Array (
                "content" => $msg
          );

          $json_data = json_encode($dataArray, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

          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) {header('Location: '.$_SERVER['HTTP_REFERER']);}
            else
            {
                echo curl_error($ch);
                echo "<br>\n";
                echo $data;
            }

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

      }
  }


  ## Get From List as List of Commish Emails

  $query="SELECT value FROM ootp_sql_admin as osa,human_managers as hm WHERE hm.human_manager_id=osa.identifier AND hm.is_commish=1 AND hm.retired=0 AND setting='email'";

  if ($_GET['showq']==1) {echo "$query<br/>\n";}

  $result=mysqli_query($db,$query);

  if (mysqli_num_rows($result)>0)

  {

	  $replyList="";

	  while ($row=mysqli_fetch_array($result))

	  {

		  if (filter_var($row['value'], FILTER_VALIDATE_EMAIL)) {$replyList.=",".$row['value'];}

	  }

	  $replyList=trim($replyList,",");



	  ## Get User Defined Reply-To Addresses

	  unset($fromList);

	  $query="SELECT value FROM ootp_sql_admin WHERE setting='emailReplyTo'";

	  if ($_GET['showq']==1) {echo "$query<br/>\n";}

	  $result=mysqli_query($db,$query);

	  if (mysqli_num_rows($result)>0)

	  {

		  $row=mysqli_fetch_array($result);

		  if ($row['value']!="")

		  {

			$replyList=$row['value'];

		  }

	  }



	  ## Get From Address

	  unset($fromList);

	  $query="SELECT value FROM ootp_sql_admin WHERE setting='emailFrom'";

	  if ($_GET['showq']==1) {echo "$query<br/>\n";}

	  $result=mysqli_query($db,$query);

	  if (mysqli_num_rows($result)>0)

	  {

		  $row=mysqli_fetch_array($result);

		  $fromList=$row['value'];

	  }

	  if (!isset($fromList)||($fromList==""))

	  {

		  $fromList=$replyList;

	  }



	  ## Get To List

	  $query="SELECT value FROM (SELECT identifier FROM ootp_sql_admin WHERE setting='slUpdateSubscribe'";

	  if ($_POST['sendToAll']!=1) {$query.=" AND value=1";}

	  $query.=") as t1,(SELECT identifier,value FROM ootp_sql_admin WHERE setting='email' AND value IS NOT NULL) as t2 WHERE t1.identifier=t2.identifier GROUP BY value";

	  if ($_GET['showq']==1) {echo "$query<br/>\n";}

	  $result=mysqli_query($db,$query);

	  if (mysqli_num_rows($result)>0)

	  {

		  $toList="";

		  while ($row=mysqli_fetch_array($result))

		  {

			  if (filter_var($row['value'], FILTER_VALIDATE_EMAIL)) {$toList.=",".$row['value'];}

		  }

		  $toList=trim($toList,",");

	  }



	  ## Compose Message

	  if (($replyList!="")&&($toList!=""))

	  {

		  ## Compose Header

		  $header="From: ".$fromList."\r\n";

		  $header.="Reply-To: ".$replyList." \r\n";

		  $header.="MIME-Version: 1.0\r\n";

		  $header.="Content-type: text/html; charset=iso-8859-1\r\n";



		  # Get current date

		  if (!isset($_SESSION['lgdate']))

		  {

			  $query="SELECT leagues.current_date as lgdate FROM leagues LIMIT 1";

			  if ($_GET['showq']==1) {echo "$query<br/>\n";}

			  $result=mysqli_query($db,$query);

			  $row=mysqli_fetch_array($result);

			  $_SESSION['lgdate']=$row['lgdate'];

		  }

		  $curLgDate=$_SESSION['lgdate'];



		  ## Compose Subject Line

		  $subject="StatsLab Updated";



		  $lgAbbrList="";

		  $query="SELECT abbr FROM leagues as lg,human_managers as hm WHERE lg.league_id=hm.league_id AND hm.league_id>0 GROUP BY abbr ORDER BY lg.league_id";

		  if ($_GET['showq']==1) {echo "$query<br/>\n";}

		  $result=mysqli_query($db,$query);

		  if (mysqli_num_rows($result)>0)

		  {

			  $lgList="";

			  while ($row=mysqli_fetch_array($result))

			  {

				  $lgList.="/".$row['abbr'];

			  }

			  $lgList=trim($lgList,"/");



			  $subject=$lgList." ".$subject;

		  }

		  $subject.=" to $curLgDate";

		  ## Generate Message Text
		  $message="StatsLab has been updated for $lgList, and the new league date is $curLgDate<br/>\n";
		  $message.="<br/>\n";
		  $message.="Click <a href=\"";
		  $message.=$slPath;
		  $message.="\">here</a> to view the latest!<br/>\n";

          ## Unsubscribe information
		  $message.="<br/>\n";
		  $message.="To unsubscribe from these emails, you can log in to StatsLab at the above link and disable email notifications in your user profile.  Alternately, reply to this message with an unsubscribe request and a league administrator will disable them for you.<br/>\n";

          if (($debug!=1)&&($_GET['showq']!=1)&&($settings['sendUpdateEmails']==1)) {mail($toList,$subject,$message,$header);}

	  }

	  else {echo "Insufficient emails to send mail<br/>\nReply To: $replyList<br/>\nSend To: $toList";$debug=1;}

  }

  else {echo "No commishes with emails configured for reply address";$debug=1;}

  

  mysqli_close($db);



  if (($debug!=1)&&($_GET['showq']!=1)) {header('Location: '.$_SERVER['HTTP_REFERER']);}

  else

  {

	  echo "<b>Email Test:</b><br/>\n";

	  echo "Reply To: $replyList<br/>\nSend To: $toList";

	  echo "<br/>\n";

	  echo "Header:<br/>\n$header<br/>\n";

	  echo "<br/>\n";

	  echo "Message:<br/>\n$message<br/>\n";

  }



?>

