<?php

// get the posted data
$PlayerID = 0;
$PlayerFName = "";
$PlayerSName ="";
$PlayerGamerTag ="";
$PlayerDiscord ="";
$TeamID = 0;

if(isset($_POST['PlayerID']))
    $PlayerID = $_POST['PlayerID'];

if(isset($_POST['pFName']))
    $PlayerFName = $_POST['pFName'];

if(isset($_POST['pSName']))
    $PlayerSName = $_POST['pSName'];

if(isset($_POST['pGTag']))
    $PlayerGamerTag = $_POST['pGTag']; 

if(isset($_POST['pDisc']))
    $PlayerDiscord = $_POST['pDisc'];

if(isset($_POST['teamSelect']))
    $TeamID = (int)$_POST['teamSelect'];

// check and see if this is a new player with no description - if so return to list or give error ???
if ($PlayerID == 0 && empty($PlayerFName) && empty($PlayerSName) && empty($PlayerGamerTag) && empty($PlayerDiscord) && $TeamID == 0  )
{
    $redirect = "location: index.php";
    header($redirect);
    exit();
    
}

// attempt to connect to the DB
$dbconn = mysqli_connect("localhost", "root", "", "gcsowls");
if ($dbconn->connect_error > 0) {
    die('Could not connect: ' . $dbconn->connect_error);
    exit(); // you should redirect to some form of error page !!!!
}

// lets determine if this is a new player or existing
if ($PlayerID == 0)
{
    // new game - create the query (prepared statement
    $sql = $dbconn->prepare("INSERT INTO player (PlayerFName, PlayerSName, PlayerGamerTag, PlayerDiscord, TeamID) values (?, ?, ?, ?, ?)");
    $sql->bind_param('ssssi', $PlayerFName, $PlayerSName, $PlayerGamerTag, $PlayerDiscord, $TeamID);	
    // execute the query 
    $sql->execute();    
}
else
{
   // existing player
    $sql = $dbconn->prepare("update player 
                                    set PlayerFName = ?, PlayerSName = ?, PlayerGamerTag = ?, PlayerDiscord = ?, TeamID = ?
                                    where PlayerID = ?");
    $sql->bind_param('ssssii', $PlayerFName, $PlayerSName, $PlayerGamerTag, $PlayerDiscord, $TeamID, $PlayerID);	
    // execute the query 
    $sql->execute();      
}


// close the DB and connection
$sql->close();
$dbconn->close(); 

header('Location: index.php');
 ?>


