<?php
include '../managers/menu.php';
if (!(UserHasPerm("god_profile") && $userID == 1)) {
  StopAndDie();
}

$jsonFile = __DIR__ . '/../managers/version.json';
if (isset($_POST['build'], $_POST['idx']) && file_exists($jsonFile)) {
	$build = $_POST['build'];
	$idx = (int)$_POST['idx'];
	$versionData = json_decode(file_get_contents($jsonFile), true);
	foreach ($versionData['updates'] as $uKey => &$update) {
		if ($update['build'] === $build) {
			if (isset($update['changes'][$idx])) {
				array_splice($update['changes'], $idx, 1);
				if (count($update['changes']) === 0) {
					array_splice($versionData['updates'], $uKey, 1);
				}
				file_put_contents($jsonFile, json_encode($versionData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
			}
			break;
		}
	}

}
if (isset($_POST['build'])) {
  http_response_code(204);
  exit();
}

$versionData = [];
if (file_exists($jsonFile)) {
  $jsonContent = file_get_contents($jsonFile);
  $versionData = json_decode($jsonContent, true);
  if (!is_array($versionData)) {
    $versionData = ['updates' => []];
  }
} else {
  $versionData = ['updates' => []];
}

// Alapértelmezett értékek a legutóbbi build alapján
$defaultEnv = 'l'; // Éles
$defaultStatus = 'a'; // Aktív
$defaultDateTime = date('Y-m-d\TH:i');

if (!empty($versionData['updates'])) {
  $lastBuild = $versionData['updates'][0]['build'];
  if (strlen($lastBuild) >= 2) {
    $defaultEnv = substr($lastBuild, 0, 1);
    $defaultStatus = substr($lastBuild, 1, 1);
    $timestamp = (int) substr($lastBuild, 2);
    $defaultDateTime = date('Y-m-d\TH:i', $timestamp);
  }
}

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['env']) && isset($_POST['status']) && isset($_POST['datetime']) && isset($_POST['change']) && isset($_POST['anticsrfid']) && $_POST['anticsrfid'] == $_SESSION["anticsrfid"]) {
  $env = trim($_POST['env']);
  $status = trim($_POST['status']);
  $datetime = trim($_POST['datetime']);
  $change = trim($_POST['change']);

  if ($env !== '' && $status !== '' && $datetime !== '' && $change !== '') {
    // Build szám generálása
    $timestamp = strtotime($datetime);
    $build = $env . $status . $timestamp;

    $found = false;
    foreach ($versionData['updates'] as &$update) {
      if ($update['build'] === $build) {
        if (!in_array($change, $update['changes'], true)) {
          array_unshift($update['changes'], $change);
        }
        $found = true;
        break;
      }
    }
    unset($update);
    if (!$found) {
      array_unshift($versionData['updates'], [
        'build' => $build,
        'changes' => [$change]
      ]);
    }
    if (file_put_contents($jsonFile, json_encode($versionData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) === false) {
      $message = 'Mentés sikertelen: nem lehet írni a fájlt. Útvonal: ' . htmlspecialchars($jsonFile);
    } else {
      $message = 'A változtatás mentve lett. Build szám: ' . htmlspecialchars($build);
    }
  } else {
    $message = 'Minden mező kitöltése kötelező.';
  }
}

$anticsrfid = bin2hex(random_bytes(24));
$_SESSION["anticsrfid"] = $anticsrfid;
?>
<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Verzió szerkesztő</title>
    <style>
      body {
        font-family: 'Poppins', sans-serif;
        font-size: 14px;
        line-height: 1.7;
        color: #333333;
        background: #eef2f7;
        display: flex;
        justify-content: center;
        align-items: flex-start;
        min-height: 100vh;
        padding: 2rem;
      }
      form {
        background: white;
        padding: 1.5rem 2rem;
        border-radius: 10px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        width: 100%;
        max-width: 400px;
      }
      h2 {
        margin-bottom: 1rem;
      }
      label {
        display: block;
        margin-bottom: 0.25rem;
        font-weight: 600;
        color: #555;
      }
      input[type="text"], input[type="datetime-local"], select {
        width: 100%;
        padding: 0.5rem 0.75rem;
        margin-bottom: 1rem;
        border: 1px solid #ccc;
        border-radius: 6px;
        font-size: 1rem;
        box-sizing: border-box;
        transition: border-color 0.2s ease;
      }
      input[type="text"]:focus, input[type="datetime-local"]:focus, select:focus {
        border-color: #667eea;
        outline: none;
      }
      select {
        cursor: pointer;
      }
      button {
        background: #48a14d;
        color: white;
        border: none;
        border-radius: 6px;
        padding: 0.6rem 1.2rem;
        font-size: 1rem;
        cursor: pointer;
        font-weight: 600;
        transition: 0.2s ease;
      }
      button:hover {
        opacity: 0.8;
      }
      .message {
        margin-top: 1rem;
        padding: 0.75rem;
        border-radius: 6px;
        font-weight: 600;
        color: #2a662a;
        background-color: #d3f9d8;
      }
      .form-row {
        display: flex;
        gap: 1rem;
      }
      .form-row > div {
        flex: 1;
      }
      .form-row label {
        margin-bottom: 0.25rem;
      }
      li {
        cursor: pointer;
        transition: 0.2s ease;
      }
      li:hover {
        color: #48a14d;
      }
    </style>
</head>
<body>
  <div style="display: block;">
    <form method="POST" novalidate>
      <h2>Új frissítés hozzáadása</h2>

      <label for="change">Frissítés leírása</label>
      <input type="text" id="change" name="change" autocomplete="off" spellcheck="false" autocapitalize="off" autocorrect="off" required />
      <input type="hidden" name="anticsrfid" value="<?php echo $anticsrfid;?>">

      <div class="form-row">
        <div>
          <label for="env">Verzió környezete</label>
          <select id="env" name="env" required>
            <option value="l" <?= $defaultEnv === 'l' ? 'selected' : '' ?>>Éles</option>
            <option value="t" <?= $defaultEnv === 't' ? 'selected' : '' ?>>Teszt</option>
          </select>
        </div>
        <div>
          <label for="status">Verzió státusza</label>
          <select id="status" name="status" required>
            <option value="a" <?= $defaultStatus === 'a' ? 'selected' : '' ?>>Aktív</option>
            <option value="d" <?= $defaultStatus === 'd' ? 'selected' : '' ?>>Demó</option>
            <option value="b" <?= $defaultStatus === 'b' ? 'selected' : '' ?>>Béta</option>
          </select>
        </div>
      </div>

      <label for="datetime">Dátum és idő</label>
      <input type="datetime-local" id="datetime" name="datetime" value="<?= $defaultDateTime ?>" required />

      <button type="submit">Mentés</button>
      <?php if ($message !== ''): ?>
        <div class="message"><?=htmlspecialchars($message)?></div>
      <?php endif; ?>
    </form>
    <br clear="all"><br>
    <?php
      $jsonPath = __DIR__ . '/../managers/version.json';
      $jsonData = file_get_contents($jsonPath);
      $versionData = json_decode($jsonData, true);
      if (!empty($versionData['updates'])) {
          $updates = array_slice($versionData['updates'], 0, 5);
          echo '<div style="background: white; padding: 1.5rem 2rem; border-radius: 10px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); width: 100%; max-width: 400px; overflow-y: auto; ">';
          foreach ($updates as $update) {
              echo '<div style="margin-bottom: 1rem;">';
              $buildNumber = htmlspecialchars($update['build']);

              // Build szám dekódolása
              $envChar = substr($buildNumber, 0, 1);
              $statusChar = substr($buildNumber, 1, 1);
              $timestampPart = substr($buildNumber, 2);

              $envLabel = ($envChar === 'l') ? 'Éles' : 'Teszt';
              $statusLabel = ($statusChar === 'a') ? 'Aktív' : (($statusChar === 'd') ? 'Demó' : 'Béta');

              echo '<strong>Build szám: #' . $buildNumber . '</strong>';
              echo '<small style="opacity: 0.8;"> (' . $envLabel . ' / ' . $statusLabel . ' - ' . date('Y.m.d. H:i', intval($timestampPart)) . ')</small><br>';
              echo '<ul style="margin: 0 0 0 1rem; padding: 0;">';
              foreach ($update['changes'] as $idx => $change) {
              	echo '<li class="deletable" data-build="'.htmlspecialchars($buildNumber).'" data-idx="'.$idx.'">'
              		.htmlspecialchars($change).'</li>';
              }
              echo '</ul></div>';
          }
          echo '</div>';
      }
    ?>
  </div>
  <script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function() {
    	document.querySelectorAll('.deletable').forEach(function(el) {
    		el.addEventListener('click', function() {
    			const build = this.dataset.build;
    			const idx = this.dataset.idx;
    			const text = this.textContent;
    			if (confirm(`Biztos törölni akarod a(z) ${build} buildszámú "${text}" bejegyzést?`)) {
    				fetch('version_controll.php', {
    					method: 'POST',
    					headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    					body: `build=${encodeURIComponent(build)}&idx=${encodeURIComponent(idx)}`
    				})
    				.then(response => location.reload());
    			}
    		});
    	});
    });
  </script>

</body>
</html>
