<?php
$IIDX_Location = "192.168.1.80";
$IIDX_Port = 4500;
$SDVX_Location = "192.168.1.81";
$SDVX_Port = 4500;

if (!file_exists('cards.json')) { fopen('cards.json','w'); }
// if cards.json does not exist, we create it

if (!file_exists('settings.json')) {
  // if setting.json does not exist, we create it
  fopen('settings.json','w');
  // this is settings.json default values, settings must be changed through the interface, not here !
  $settings = array (
    'rcard' => array ('PLAYER_1','PLAYER_2'),
    'card' => array (
      'background' => 'backgrounds/programmedsun.png',
      'subtitle' => '',
      'icon' => '',
      'width' => '400',
      'height' => '260'
    ),
    'sort-key' => 'name',
    'sort-order' => 'asc',
    'animations' => 'on',
    'regex' => 'cards/monopole-$0.txt'
  );
  file_put_contents('settings.json',json_encode($settings));
}
// we fetch settings.json content and put it into an array
$settings = json_decode(file_get_contents('settings.json'),true);

for ($i=0;$i<count($settings['rcard']);$i++) {
    if(!file_exists(preg_replace('#^\w*#',$settings['regex'],$settings['rcard'][$i]))) {
        fopen(preg_replace('#^\w*#',$settings['regex'],$settings['rcard'][$i]),'w');
    }
}
// if the card files do not exist, we create them, THAT'S IMPORTANT, REALLY.

$json = file_get_contents('cards.json');

$cards = json_decode($json, true);
// we get value stored into cards.json and convert it to a PHP array

$cards = $cards == NULL ? array() : $cards;
// if cards.json is empty, we say it's an array anyway. if we don't do that the next steps may fail.


if (isset($_POST['delete'])) {
  for($i=0;($cards[$i]['id'] != $_POST['delete']) && $i <= count($cards);$i++) {}
  unset($cards[$i]);
}
if (isset($_POST['edit'])) {
$cards[$_POST['edit']]['name'] = $_POST['name'];
$cards[$_POST['edit']]['id'] = $_POST['id'];
$cards[$_POST['edit']]['background'] = $_POST['background'];
$cards[$_POST['edit']]['subtitle'] = $_POST['subtitle'];
}
if (isset($_POST['cardgen']) && isset($_POST['cardid']) && isset($_POST['cardname'])) {
  array_push(
    $cards,
    array(
      'name' => $_POST['cardname'],
      'id' => $_POST['cardid'],
      'subtitle' => $settings['card']['subtitle'],
      'background' => $settings['card']['background'],
      'icon' => $settings['card']['icon'],
      'regdate' => date('U')
    )
  );
}
if (isset($_POST['rcard'])) { $settings['rcard'] = explode(',',str_replace(' ','_',$_POST['rcard']));}
if (isset($_POST['sort-key'])) { $settings['sort-key'] = $_POST['sort-key'];}
if (isset($_POST['sort-order'])) { $settings['sort-order'] = $_POST['sort-order'];}
if (isset($_POST['animations'])) { $settings['animations'] = $_POST['animations'];}
if (isset($_POST['background'])) { $settings['card']['background'] = $_POST['background'];}
if (isset($_POST['csubtitle'])) { $settings['card']['subtitle'] = $_POST['csubtitle'];}
if (isset($_POST['width'])) { $settings['card']['width'] = $_POST['width'];}
if (isset($_POST['height'])) { $settings['card']['height'] = $_POST['height'];}
foreach (glob('import/*.txt') as $file) {
// if there are files into import/ folder, we check them, the following code will store their data into cards.json
// assuming the file content = the card ID and the file name = account name
// you can change those informations later.
  $content = file_get_contents($file);
  $content = trim($content);
  $filename = basename($file,'.txt');
  if (!preg_match('#"id":"'.$content.'"#',$json) && $content != '') {
    array_push(
      $cards,
      array(
        'name' => $filename,
        'id' => $content,
        'subtitle' => $settings['card']['subtitle'],
        'background' => $settings['card']['background'],
        'icon' => $settings['card']['icon'],
        'regdate' => date('U')
      )
    );
  }
}
function sortBy($field, &$array, $direction = 'asc')
{
    usort($array, create_function('$a, $b', '
        $a = $a["' . $field . '"];
        $b = $b["' . $field . '"];

        if ($a == $b)
        {
            return 0;
        }

        return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
    '));

    return $array;
}
file_put_contents('cards.json',json_encode(sortBy($settings['sort-key'],$cards,$settings['sort-order'])));
// after reading import/ folder, we write the new data into cards.json
file_put_contents('settings.json',json_encode($settings));
// we update settings too

?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <link href='https://fonts.googleapis.com/css?family=Didact+Gothic' rel='stylesheet' type='text/css'>
  <title>"Monopole." Project</title>
  <style>
    html,body {margin:0;border:0;padding:0;width:100%;}
    body {
      font-family:'Didact Gothic';
      background: url(img/background.gif);
    }
    a,a:visited {
      color: #be9634;
      text-decoration: none;
    }
    a:hover,a:active {
      color: #8e6500;
      text-decoration: underline;
    }
    button, select {
    }
    #top h1 {
      text-align: center;
      font-size: 3em;
      color: #E7B63F;
      text-shadow: 2px 0 0 black, 0 2px 0 black, 0 0 4px black;
    }
    #top p {
      text-align: center;
      width: 90%;
      margin: auto;
    }
    .trigger {
      display: block;
      margin: auto;
      min-width: 200px
      min-height: 20px;
      margin-top: 10px;
      background-color: black;
      color: white;
      font-size: 20px;
      box-shadow: inset 0 0 5px 2px white;
      padding: 2px;
      border-radius: 15px;
      transition: .6s;
    }
    .trigger:hover {
      background-color: #ff8c00;
    }
    #cards button {
      background: none repeat scroll 0 0 transparent;
      border: medium none;
      border-spacing: 0;
      margin: 0;
      padding: 0;
      text-indent: 0;
      font-family: inherit;
      width: <?=$settings['card']['width']?>px;
      height: <?=$settings['card']['height']?>px;
      border-radius: 15px;
      box-shadow: 0 0 8px 2px black;
      margin: 15px;
      position: relative;
      background-color: #FFF;
      background-size: 100% 100%;
      vertical-align: top;
    }
    #cards button:hover {
      cursor: pointer;
    }
    #cards button .konmai {
      position: absolute;
      top: 10px;
      left: 10px;
      width: 110px;
      height: 25px;
      background: url(img/konmai.png);
      background-size: 100% 100%;
    }
    #cards .name {
      font-size: 3em;
      position: absolute;
      top: 10px;
      right: 10px;
      width: 280px;
      text-align: right;
      color: white;
      text-shadow: 2px 0 0 black, 0 2px 0 black, 0 -2px 0 black, -2px 0 0 black;
    }
    #cards .subtitle {
      font-size: 1.5em;
      position: absolute;
      bottom: 30px;
      text-align: center;
      width: 100%;
      color: white;
      text-shadow: 2px 0 0 black, 0 2px 0 black, 0 -2px 0 black, -2px 0 0 black;
    }
    #cards .id {
      position: absolute;
      bottom: 10px; left: 10px;
      font-size: 1em;
      text-shadow: 1px 0 0 white, 0 1px 0 white, 0 0 2px white;
    }
    <?=$settings['animations']=='on'?'
    -webkit-@keyframes pop-in{from{opacity:0;top:130px}to{opacity: 1; top: 0px}}
    @keyframes pop-in {
      from {opacity: 0; top: 130px}
      to {opacity: 1; top: 0px}
    }
    #cards button {
      transition: .5s;
      -webkit-animation: pop-in .5s ease-out;
      animation: pop-in .5s ease-out;
      -webkit-animation-fill-mode: forwards;
      animation-fill-mode: forwards;
      opacity: 0;
    }':''?>
    .page {
      background: white;
      border:radius: 5px;
      width: 90%;
      min-height: 350px;
      box-shadow: 0 0 4px 1px black;
      margin: 20px 0;
      margin-left: 4%;
      display: inline-block;
      padding: 20px;
      font-size: 140%;
    }
    .page small {
      color: dimgray;
    }
    .page #delcheck input, .page #delcheck button {
      width: 40%;
      min-height: 100px;
      font-size: 30px;
      margin: 5%;
    }
    .page #cardeditor input {
      min-width: 200px;
      min-height: 20px;
      font-size: 18px;
    }
    .page .sblock {
      display: inline-block;
      width: 33%;
      text-align: center;
      vertical-align: top;
    }
    .page .sblock textarea {
      width: 95%;
      min-height: 100px;
    }
    #cardeditor input {
      width: 100%;
    }
  </style>
</head>
<body>
  <div id="top">
    <a href="."><h1>Monopole. &infin; Project</h1></a>
    <p>Virtual eAMUSEMENT PASS changer made for #bemaniso tracker users. Made with &hearts; by @<a href="https://twitter.com/skielred">skielred</a>.<br /> You are using 05/08/2016 version. Love.</p>
  </div>
<?php
if (isset($_POST['trigger']) && ($_POST['trigger'] == 'edit' || $_POST['trigger'] == 'delete')) {
  if ($_POST['trigger'] == 'edit') {
    for($i=0;($cards[$i]['id'] != $_POST['id']) && $i <= count($cards);$i++) {
    }
    $card = $cards[$i];
?>
  <div class="page">
    <div style="display:inline-block;vertical-align:top;margin:0 20px">
      <form method="post" id="cardeditor">
        Name :<br />
        <input type="text" name="name" value="<?=$card['name']?>" /><br />
        ID :<br />
        <input type="text" name="id" value="<?=$card['id']?>" /><br />
        Background <small>(you can use an external file like http://i.imgur.com/something.jpg)</small> :<br />
        <input type="text" name="background" id="cardbg" value="<?=$card['background']?>" /><br />
        Subtitle :<br />
        <input type="text" name="subtitle" value="<?=$card['subtitle']?>" /><br />
        <br />
        <input type="hidden" name="edit" value="<?=$i?>" />
        <input class="trigger" type="submit" value="Update card" />
      </form>
      <a href="."><button class="trigger" style="margin:inherit">Back</button></a>
    </div>
    <div style="display:inline-block;vertical-align:top;margin:0 20px">
      <p>Sample backgrounds <small>(click to select)</small> :</p>
      <ul>
<?php
  foreach(glob('backgrounds/*') as $file) {
    echo '<li style="display:inline-block;margin:20px;"><img style="width:200px;height:130px;box-shadow:0 0 3px 1px black"    onclick="cardbg(this)" src="'.$file.'"/></li>';
  }    
?>
      </ul>
      <script type="text/javascript">
        function cardbg(test) {
          document.getElementById("cardbg").value=test.getAttribute("src");
        }
      </script>
      <p>Leave empty for default background. Default background can be modified into settings.</p>
    </div>
  </div>
<?php
  } elseif ($_POST['trigger'] == 'delete') {
?>
  <div class="page">
    <h1>Are you sure you ?</h1>
    <p>You are going to delete <?=$_POST['id']?>. This card will disapear forever ! <small>(A very long time)</small></p>
    <span style="color:red">Warning : If you haven't deleted this card from the "import/" folder yet, if you delete it here the card will be added to the "cards.json" file again on the next page load.</span>
    <form method="post" id="delcheck">
      <button name="delete" value="<?=$_POST['id']?>">OF COURSE YES</button><input type="submit" value="NO !!"/>
    </form>
  </div>
<?php
  }
} elseif (isset($_POST['settings'])) {
?>
  <div class="page">
    <h1>Settings <small style="font-size:30%;font-weight:300">Because customizing your pass isn't enough, you have to customize your pass customizer too.</small></h1>
    <hr />
    <form method="post" action="">
      <h2>Add a Virtual Card <small>because using text files is so 2015</small></h2>
      <div class="sblock">
        <p>Card ID (<a href="#" onclick="generate()">generate random</a>)</p>
        <textarea name="cardid" id="cardid" style="min-height:inherit" rows="1">E004</textarea>
        <script type="text/javascript">
          function generate() {
            var possible = "ABCDEF0123456789";
            document.getElementById("cardid").value = '';
            for( var i=0; i < 12; i++ ) {
              document.getElementById("cardid").value += possible.charAt(Math.floor(Math.random() * possible.length));
            }
            document.getElementById("cardid").value = 'E004'+document.getElementById("cardid").value;
          }
        </script>
      </div>
      <div class="sblock">
        <p>DJ NAME</p>
        <textarea name="cardname" style="min-height:inherit" rows="1" placeholder="searching for you souuuul..."></textarea>
      </div>
      <div class="sblock">
        <button name="cardgen" class="trigger">Generate card</button>
      </div>
      <hr />
      <h2>Default setings</h2>
      <div class="sblock">
        <p>Sorting key :</p>
        <select name="sort-key" class="trigger">
          <option value="name" <?=$settings['sort-key']=='name'?'selected':''?>>Name</option>
          <option value="id" <?=$settings['sort-key']=='id'?'selected':''?>>ID</option>
          <option value="regdate" <?=$settings['sort-key']=='regdate'?'selected':''?>>Date</option>
        </select>
      </div>
      <div class="sblock">
        <p>Sorting order :</p>
        <select name="sort-order" class="trigger">
          <option value="asc" <?=$settings['sort-order']=='asc'?'selected':''?>>Ascend</option>
          <option value="desc" <?=$settings['sort-order']=='desc'?'selected':''?>>Descend</option>
        </select>
      </div>
      <div class="sblock">
        <p>Animations :</p>
        <select name="animations" class="trigger">
          <option value="on" <?=$settings['animations']=='on'?'selected':''?>>On</option>
          <option value="off" <?=$settings['animations']=='off'?'selected':''?>>Off</option>
        </select>
      </div>
      <hr />
      <h2>Cards</h2>
      <div class="sblock">
        <p>Default subtitle</p>
        <textarea name="csubtitle"><?=$settings['card']['subtitle']?></textarea>
      </div>
      <div class="sblock">
        <p>Default background</p>
        <select class="trigger">
<?php
  foreach(glob('backgrounds/*') as $file) {
    echo preg_replace('#/#','\\/',$file) == $settings['card']['background'] ? '<option name="'.$file.'" selected>'.$file.'</option>' : '<option name="'.$file.'">'.$file.'</option>';
  } 
?>
          <option value="none" <?=$settings['card']['background']=='none'?'selected':''?>>none</option>
        </select>
      </div>
      <div class="sblock">
        <p>Card files <small>(avoid special characters such as ' or ", seperate each different file with a comma ,)</small></p>
        <textarea name="rcard"><?=implode(',',$settings['rcard'])?></textarea>
      </div>
      <hr />
      <input type="submit" class="trigger" value="Update settings" />
  </div>
<?php
}
  else {
  if (isset($_POST['trigger']) && preg_match('#^rcard-#',$_POST['trigger'])) {
    $slot = preg_replace('#^rcard-#','',$_POST['trigger']);
    $rcard = preg_replace('#^\w*#',$settings['regex'],$slot);
    file_put_contents($rcard,$_POST['id']);
	
	// dt edit
	if($slot == 'IIDX_P1') // edit p1
	{
		$fp = fsockopen($IIDX_Location, $IIDX_Port, $errno, $errstr, 5);
		if (!$fp) 
		{
			echo "$errstr ($errno)<br />\n";
		} 
		else 
		{
			fwrite($fp, "1:" . $_POST['id']);
			while (!feof($fp)) 
			{
				echo fgets($fp, 128);
			}
        fclose($fp);
		}
	}
	elseif($slot == 'IIDX_P2') // edit p1
	{
		$fp = fsockopen($IIDX_Location, $IIDX_Port, $errno, $errstr, 5);
		if (!$fp) 
		{
			echo "$errstr ($errno)<br />\n";
		} 
		else 
		{
			fwrite($fp, "2:" . $_POST['id']);
			while (!feof($fp)) 
			{
				echo fgets($fp, 128);
			}
        fclose($fp);
		}
	}
	if($slot == 'SDVX') // edit p1
	{
		$fp = fsockopen($SDVX_Location, $SDVX_Port, $errno, $errstr, 5);
		if (!$fp) 
		{
			echo "$errstr ($errno)<br />\n";
		} 
		else 
		{
			fwrite($fp, "1:" . $_POST['id']);
			while (!feof($fp)) 
			{
				echo fgets($fp, 128);
			}
        fclose($fp);
		}
	}
  }
?>
  <form id="cards" method="post" action="">
    <select class="trigger" name="trigger">
      <?php
      for ($i=0;$i<count($settings['rcard']);$i++) {
      ?>
      <option value="rcard-<?=$settings['rcard'][$i]?>"><?=str_replace('_',' ',$settings['rcard'][$i])?></option>
      <?php
      }
      ?>
      <option value="edit">EDIT</option>
      <option value="delete">DELETE</option>
    </select>
<?php
  $i=0;
  foreach ($cards as $card) {
?>
    <button name="id" value="<?=$card['id']?>" style="background-image:url(<?=$card['background']?>); animation-delay: <?=$i*0.25?>s; <?=file_get_contents($settings['rcard'][1]) == $card['id'] ? 'box-shadow: 0 0 8px 2px #F00':''?> <?=file_get_contents($settings['rcard'][2]) == $card['id'] ? 'box-shadow: 0 0 8px 2px #00F':''?>">
      <div class="konmai"></div>
      <div class="name"><?=$card['name']?></div>
      <div class="subtitle"><?=$card['subtitle']?></div>
      <div class="id">E004-XXXX-XXXX-<?=substr($card['id'],-4)?></div>
    </button>
<?php
  $i++;
  }
?>
    <button name="settings" value="settings" style="background-image:url(img/titanium_gears.jpg);color:white;font-size:75px;text-shadow:2px 2px 5px black; animation-delay: <?=($i+1)*0.25?>s;">Settings</button>
  </form>
<?php
}
?>
</body>
</html>
