<?php

  include("html_functions.php");



  ################## PAGE INITIALIZATION #########################

  $lgid=$_SESSION['lgid'];

  $lgpath=$_SESSION['lgpath'];

  $date=new Date($_SESSION['lgdate']);

  $lgyear=$_SESSION['lgyear'];



  $team_no = $_POST['team'];

  $debug=$_POST['debug'];



  # Title Bar

  $title='Team Trade Block Admin - Forum Updater';



  page_head($title,$_SESSION['lgpath'],"","","./text_functions.js");

  echo " <div id='topbar'>\n";

  main_titlebar($lgid,$_SESSION['lgpath'],$title,$team_id);

  nav_toolbar('front_office',"Front Office");

  echo " </div>   <!-- END topbar DIV -->\n";

  echo " <div id='contentpane'>\n";



  //StatsLabPath

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

  $query="SELECT setting,value FROM ootp_sql_admin WHERE module='admin' AND (setting IN ('StatsLabPath') OR setting LIKE '%slack%')";

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

  if (mysqli_num_rows($result))

  {

	  while ($row=mysqli_fetch_array($result))

	  {

		  $field=$row['setting'];

		  $val=$row['value'];

		  switch ($field)

		  {

		  case 'StatsLabPath' : $_SESSION['StatsLabPath']=$val; break;

		  case 'ServerURL': $_SESSION['serverurl']=$val;break;

		  default:

			$settings[$field]=$val;

		  }

		  $StatsLabPath=$_SESSION['StatsLabPath'];

		  if (strtolower(substr($_SESSION['StatsLabPath'],0,4))!="http") {$StatsLabPath=$_SESSION['serverurl'].$_SESSION['StatsLabPath'];}

	  }

  }



  //Get GM

  $query="SELECT human_manager_id,team_id,organization_id,if(team_id=organization_id,1,0) as sortCol FROM human_managers WHERE team_id=$team_no OR organization_id=$team_no ORDER BY sortCol DESC LIMIT 1";

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

  if (mysqli_num_rows($result))

  {

	  $row=mysqli_fetch_array($result);

	  $hmid=$row['human_manager_id'];

  } 



  //Get GM user info

  $query="SELECT setting,value FROM ootp_sql_admin WHERE module='users' AND identifier=$hmid AND setting IN ('flink','email')";

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

  if (mysqli_num_rows($result))

  {

	  while ($row=mysqli_fetch_array($result))

	  {

		  $setting=$row['setting'];

		  $users[$setting]=$row['value'];

	  }

  } 



$debug_string = '';

$timestamp = time();

$error_count = 0;



##

## Check for positional needs

##

$c=$_POST['c'];

$fb=$_POST['fb'];

$sb=$_POST['sb'];

$tb=$_POST['tb'];

$ss=$_POST['ss'];

$lf=$_POST['lf'];

$cf=$_POST['cf'];

$rf=$_POST['rf'];

$sp=$_POST['sp'];

$rp=$_POST['rp'];

if ($c!=1) {$c=0;}

if ($fb!=1) {$fb=0;}

if ($sb!=1) {$sb=0;}

if ($tb!=1) {$tb=0;}

if ($ss!=1) {$ss=0;}

if ($lf!=1) {$lf=0;}

if ($cf!=1) {$cf=0;}

if ($rf!=1) {$rf=0;}

if ($sp!=1) {$sp=0;}

if ($rp!=1) {$rp=0;}

$sum_pos = $c + $fb + $sb + $ss + $tb + $lf + $cf + $rf + $sp + $rp;

$sum_pos--;



##

## Listing of associated "post_id" values

##

$teams[1]['post_id'] = 36533; /* Arlington Bureaucrats    */

$teams[2]['post_id'] = 36528; /* Connecticut Nutmeggers   */

$teams[3]['post_id'] = 36520; /* London Underground       */

$teams[4]['post_id'] = 36519; /* Manchester Maulers       */

$teams[5]['post_id'] = 36518; /* New Jersey Hitmen        */

$teams[6]['post_id'] = 36523; /* Gloucester Fishermen     */

$teams[7]['post_id'] = 36529; /* Charleston Statesmen     */

$teams[8]['post_id'] = 36517; /* New Orleans Trendsetters */

$teams[9]['post_id'] = 36524; /* Florida Featherheads     */

$teams[10]['post_id'] = 36521; /* Kentucky Thoroughbreds   */

$teams[11]['post_id'] = 36511; /* West Virginia Coal Sox   */

$teams[12]['post_id'] = 36513; /* San Antonio Calzones of Laredo */

$teams[13]['post_id'] = 36530; /* Canton Longshoremen      */

$teams[14]['post_id'] = 36527; /* Crystal Lake Sandgnats   */

$teams[15]['post_id'] = 36526; /* Duluth Warriors          */

$teams[16]['post_id'] = 36525; /* Fargo Dinosaurs          */

$teams[17]['post_id'] = 36522; /* Kalamazoo Badgers        */

$teams[18]['post_id'] = 36516; /* Omaha Cyclones           */

$teams[19]['post_id'] = 36532; /* Aurora Borealis          */

$teams[20]['post_id'] = 36531; /* Bakersfield Bears        */

$teams[21]['post_id'] = 36515; /* Palm Springs Codgers     */

$teams[22]['post_id'] = 36514; /* Reno Tenpinners          */

$teams[23]['post_id'] = 36512; /* Tempe Knights            */

$teams[24]['post_id'] =36510; /* Yuma Bulldozers          */



$teams[157]['post_id'] = 36543; /* Hyakujuu Shinkansen    */

$teams[158]['post_id'] = 36541; /* Kure Arsenal           */

$teams[159]['post_id'] = 36537; /* Neo-Tokyo Akira        */

$teams[160]['post_id'] = 36536; /* Niihama-shi Ghosts     */

$teams[161]['post_id'] = 36534; /* Shin Seiki Evas        */

$teams[162]['post_id'] = 36542; /* Kawaguchi Transmitters */

$teams[163]['post_id'] = 36545; /* Edo Battousai          */

$teams[164]['post_id'] = 36544; /* Fushigi Yugi Celestial Warriors */

$teams[165]['post_id'] = 36540; /* Kuwana Steel Dragons   */

$teams[166]['post_id'] = 36539; /* Lupin Cliff Hangers    */

$teams[167]['post_id'] = 36538; /* Naha Shisa             */

$teams[168]['post_id'] = 36535; /* Seoul Crushers         */



##

## Listing of associated "topic_id" values

##

$teams[1]['topic_id'] = 4700; /* Arlington Bureaucrats    */

$teams[2]['topic_id'] = 4695; /* Connecticut Nutmeggers   */

$teams[3]['topic_id'] = 4687; /* London Underground       */

$teams[4]['topic_id'] = 4686; /* Manchester Maulers       */

$teams[5]['topic_id'] = 4685; /* New Jersey Hitmen        */

$teams[6]['topic_id'] = 4690; /* Gloucester Fishermen     */

$teams[7]['topic_id'] = 4696; /* Charleston Statesmen     */

$teams[8]['topic_id'] = 4684; /* New Orleans Trendsetters */

$teams[9]['topic_id'] = 4691; /* Florida Featherheads     */

$teams[10]['topic_id'] = 4688; /* Kentucky Thoroughbreds   */

$teams[11]['topic_id'] = 4678; /* West Virginia Coal Sox   */

$teams[12]['topic_id'] = 4680; /* San Antonio Calzones of Laredo */

$teams[13]['topic_id'] = 4697; /* Canton Longshoremen      */

$teams[14]['topic_id'] = 4694; /* Crystal Lake Sandgnats   */

$teams[15]['topic_id'] = 4693; /* Duluth Warriors          */

$teams[16]['topic_id'] = 4692; /* Fargo Dinosaurs          */

$teams[17]['topic_id'] = 4689; /* Kalamazoo Badgers        */

$teams[18]['topic_id'] = 4683; /* Omaha Cyclones           */

$teams[19]['topic_id'] = 4699; /* Aurora Borealis          */

$teams[20]['topic_id'] = 4698; /* Bakersfield Bears        */

$teams[21]['topic_id'] = 4682; /* Palm Springs Codgers     */

$teams[22]['topic_id'] = 4681; /* Reno Tenpinners          */

$teams[23]['topic_id'] = 4679; /* Tempe Knights            */

$teams[24]['topic_id'] = 4677; /* Yuma Bulldozers          */



$teams[157]['topic_id'] = 4710; /* Hyakujuu Shinkansen    */

$teams[158]['topic_id'] = 4708; /* Kure Arsenal           */

$teams[159]['topic_id'] = 4704; /* Neo-Tokyo Akira        */

$teams[160]['topic_id'] = 4703; /* Niihama-shi Ghosts     */

$teams[161]['topic_id'] = 4701; /* Shin Seiki Evas        */

$teams[162]['topic_id'] = 4709; /* Kawaguchi Transmitters */

$teams[163]['topic_id'] = 4712; /* Edo Battousai          */

$teams[164]['topic_id'] = 4711; /* Fushigi Yugi Celestial Warriors */

$teams[165]['topic_id'] = 4707; /* Kuwana Steel Dragons   */

$teams[166]['topic_id'] = 4706; /* Lupin Cliff Hangers    */

$teams[167]['topic_id'] = 4705; /* Naha Shisa             */

$teams[168]['topic_id'] = 4702; /* Seoul Crushers         */



##

## Display Message:

##

$debug_string .= "   <h2>Under Construction!! <br /><span style='color:red;'>IL RULES!!!</span></h2>\n";

$debug_string .= "   <h3>Time stamp: $timestamp</h3\n";

$debug_string .= "   <h3>".$teams[$team_no]['post_id']."</h3>\n";



##

## Format the Post Text

##

if(isset($team_no) && $team_no > 0)

{   

    //Team Info

    $query="SELECT team_id,league_id,name,nickname,abbr,parent_team_id,league_id,level,background_color_id,text_color_id,logo_file_name FROM teams WHERE (team_id=$team_no OR parent_team_id=$team_no);";

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

    while ($row=mysqli_fetch_array($result))

    {

	    $tid=$row['team_id'];

	    $league_id=$row['league_id'];

	    $name=$row['name']." ".$row['nickname'];

	    $teams[$tid]['name']=$name;

	    $teams[$tid]['abbr']=$row['abbr'];

	    $teams[$tid]['league_id']=$row['league_id'];

	    $teams[$tid]['parent_team_id']=$row['parent_team_id'];

	    $lvl=get_level($row['level']);

	    $teams[$tid]['level']=$lvl;

	    $teams[$tid]['background_color_id']=$row['background_color_id'];

	    $teams[$tid]['text_color_id']=$row['text_color_id'];

	    $teams[$tid]['logo_file']=urlencode($row['logo_file']);

	    if (!isset($leagues[$league_id]['lvl'])) {$leagues[$league_id]['lvl']=$lvl;}

	    $tList.=",$tid";

    }

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



    //Start text

    $team_text = "<b><a target='_blank' href='$StatsLabPath/tradeBlock.php?team_id=$team_no'>".$teams[$team_no]['name']." Trade Block</a></b>\n";

    if (isset($users['flink']) || isset($users['email']))

    {

	    $team_text .= "- Contact GM via: ";

	    if (isset($users['flink'])) {$team_text .= "<a href=\"".$users['flink']."\">PM</a>";}

	    if (isset($users['email']))

	    {

		    if (isset($users['flink'])) {$team_text .= ", ";}

		    $team_text .= "<a href=\"mailto:".$users['email']."?Subject=PEBA Trade Inquiry\">Email</a>";

	    }

	    $team_text .= "\n";

    }

    $team_text .= "\n";

    $team_text .= clean_bbcode($_POST['notice']);

    $team_text .= "\n\n<b>Needs:</b>\t";

    if($c==1)

	{ 

		$team_text .= "C";

		if($sum_pos > 0){ $team_text .= ", "; $sum_pos--; }

	}

	if($fb==1)

	{ 

		$team_text .= "1B";

		if($sum_pos > 0){ $team_text .= ", "; $sum_pos--; }

	}

    if($sb==1)

	{

		$team_text .= "2B";

		if($sum_pos > 0){ $team_text .= ", "; $sum_pos--; }

	}

    if($tb==1)

	{ 

		$team_text .= "3B";

		if($sum_pos > 0){ $team_text .= ", "; $sum_pos--; }

	}

    if($ss==1)

	{ 

		$team_text .= "SS";

		if($sum_pos > 0){ $team_text .= ", "; $sum_pos--; }

	}

    if($lf==1)

	{ 

		$team_text .= "LF";

		if($sum_pos > 0){ $team_text .= ", "; $sum_pos--; }

	}

    if($cf==1)

	{ 

		$team_text .= "CF";

		if($sum_pos > 0){ $team_text .= ", "; $sum_pos--; }

	}

    if($rf==1)

	{ 

		$team_text .= "RF";

		if($sum_pos > 0){ $team_text .= ", "; $sum_pos--; }

	}

    if($sp==1)

	{ 

		$team_text .= "SP";

		if($sum_pos > 0){ $team_text .= ", "; $sum_pos--; }

	}

    if($rp==1)

	{

		$team_text .= "RP";

	}



    ## Get Players on Block

    $team_text.="\n\n<b>Player List:</b>\n";



    //Players

    $pList="";

    $query="SELECT player_id FROM players_roster_status WHERE team_id IN ($tList) AND trade_status=2;";

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

    if (!mysqli_num_rows($result))

    {

	    $team_text.="\tNo players on the block\n";

    }

    else

    {

	    while ($row=mysqli_fetch_array($result))

	    {

		    $pid=$row['player_id'];

		    $pList.=",$pid";

	    }

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



	    # Get trade block information

	    $query="SELECT * FROM trade_block_players WHERE player_id IN ($pList);";

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

	    if (mysqli_num_rows($result))

	    {

		    while ($row=mysqli_fetch_array($result))

		    {

			    $pid=$row['player_id'];

			    $players[$pid]['headline']=stripslashes($row['headline']);

			    $notice=stripslashes($row['notice']);

			    $notice=clean_bbcode(htmlspecialchars($notice));

			    $notice=nl2br($notice);

			    $players[$pid]['notice']=$notice;

		    }

	    }



	    # Display Players

	    $query="SELECT player_id,first_name,last_name,team_id,position,role,age,injury_is_injured FROM players WHERE player_id IN ($pList) ORDER BY last_name,first_name;";

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

	    if (mysqli_num_rows($result))

	    {

		    while ($row=mysqli_fetch_array($result))

		    {

			    $pid=$row['player_id'];

			    $name=$row['first_name']." ".$row['last_name'];

			    if ($row['position']==1) {$pos=$row['role'];} else {$pos=$row['position'];}

			    $pos=get_pos($pos,1);

			    $tid=$row['team_id'];

			    $age=$row['age'];

			    $inj=$row['injury_is_injured'];



			    $team_text.="\t";

			    $team_text.="$pos ";

			    $team_text.="<a href='$StatsLabPath/player.php?player_id=$pid&league_id=".$teams[$tid]['league_id']."'>$name</a>";

			    $team_text.=" (<a href='$lgpath/teams/team_$tid.html'>".$teams[$tid]['level']."</a>)";

			    $team_text.=" - $age yrs old";

			    if ($inj==1) {$team_text.=", Injured";}

			    if ($players[$pid]['headline']!="") {$team_text.=" - ".$players[$pid]['headline'];}

			    $team_text.="\n";

		    }

	    }

    }



    mysqli_close($db);

	

    $debug_string .= "   <p>Team ID No: $team_no </p>\n";

    $team_text = addslashes($team_text);

    $debug_string .= "   <p>Note: <br />$team_text </p>\n"; 

	

	## Post to Slack

	if ($settings['slackEnable']==1)

	{

		$serviceURL = $settings['slackServiceURL'];

		$msg = "The ".$teams[$team_no]['name']." have updated their <$StatsLabPath/tradeBlock.php?team_id=$team_no|trade block>";

		if (isset($settings['slackTradeChannel'])&&($settings['slackTradeChannel']!="")) {$channel=$settings['slackTradeChannel'];}

		else {$channel=$settings['slackDefChannel'];}

		$dataArray = Array (

			"channel"    => $channel,

			"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_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";

		}

	}

	

}

else

{

    $debug_string .= "<p>No team is set!</p>\n";

    $error_count ++;

}



##

## Connect to phpBB database

##

/* Connection Variables */

$dbhost = 'localhost';

$dbuser = 'peba_pebafu';

$dbpass = 'hsjh4ynIy9';

$dbname = 'peba_pebaf';



/* Connect to MySQL and select Database */

$forum_connection = mysqli_connect($dbhost, $dbuser, $dbpass);



if (!$forum_connection) /* Display Error if the connection fails */

{

  $error_count ++;

  die('Could not connect to Forum Database: '.$php_errormsg);

}

else

{

	$debug_string .= "<p>Connection Open!</p>\n";

}



/* Select the Forum Database */

$db_selected = mysqli_select_db($forum_connection, $dbname);

if (!$db_selected) 

{

    $error_count ++;

    die ('Error selecting database!' . mysqli_error());

}



##

## Format query string to update the time stamp of the appropriate post

##

$update_string = "UPDATE phpbb_posts SET post_time = $timestamp, post_text = '$team_text' WHERE post_id=".$teams[$team_no]['post_id'];

$debug_string .= "<p>Update String: $update_string</p>\n";



##

## Execute query to update post

##

if (mysqli_query($forum_connection, $update_string))

{

	$debug_string .= "<p>Update of post Successful!</p>\n";

} 

else

{

    $error_count ++;

	$debug_string .= "<p>Error updating post!</p>\n";

}



##

## Format query string to update the time stamp of the appropriate topic

##

$update_string = "UPDATE phpbb_topics SET topic_last_post_time = $timestamp, topic_last_post_id = ".$teams[$team_no]['post_id']." WHERE topic_id=".$teams[$team_no]['topic_id'];

$debug_string .= "<p>Update String: $update_string</p>\n";



##

## Execute query to update topic

##

if (mysqli_query($forum_connection, $update_string))

{

	$debug_string .= "<p>Update of topic Successful!</p>\n";

} 

else

{

    $error_count++;

	$debug_string .= "<p>Error updating topic!</p>\n";

}



##

## Format query string to update the time stamp of the appropriate sub-forum

##

if($team_no < 101)

{

    /* Update the PEBA Trade Block Forum last post date */

    $update_string = "UPDATE phpbb_forums SET forum_last_post_time = $timestamp, forum_last_post_id = ".$teams[$team_no]['post_id']." WHERE forum_id=41";

}

else

{

    /* Update the LRS Trade Block Forum last post date */

    $update_string = "UPDATE phpbb_forums SET forum_last_post_time = $timestamp, forum_last_post_id = ".$teams[$team_no]['post_id']." WHERE forum_id=42";

}



##

## Execute query to update sub-forum post date

##

if (mysqli_query($forum_connection, $update_string))

{

	$debug_string .= "<p>Update of forum Successful!</p>\n";

} 

else

{

    $error_count++;

	$debug_string .= "<p>Error updating League Trade Block Forum!</p>\n";

}



##

## Close Database Connection

##

/* Close the connection */

$connection_test = mysqli_close($forum_connection);



/* Display Error if the disconnect fails */

if(!connection_test)

{

    $error_count++;

	die('Error Disconnecting from database: '.$php_errormsg);

}

else

{

	$debug_string .= "<p>Connection Closed!</p>\n";

}



if($error_count > 0)

{

    ##

    ## An error occurred

    ##

    echo "<h3>An error occurred while trying to update the forum. Contact <a href='http://pebabaseball.com/boards/ucp.php?i=pm&mode=compose&u=31'>Dan DiVincenzo</a> of the Arlington Bureaucrats with the following information:</h3>\n";

    echo "<p>$debug_string</p>\n";

}

else

{

    ##

    ## No errors! Write out 'success' message

    ##

    echo "<h3>Forum post updated successfully for the ".$teams[$team_no]['name'].".</h3>\n";

    echo "   <h3><a href='./tradeBlockAdmin.php'> Back to Front Office Admin Page </a></h3>\n";

}



  ################## END OF PAGE #########################

  echo " </div>   <!-- END contentpane DIV -->\n";

  page_foot($_SESSION['lgpath']);



?>

