<?php
include ('includes/header.php');

$table_name = "menualuser";
$page = "adduser.php";

$res  = $db->select($table_name, '*', '', '');
$sessions = $db->select('active_sessions', '*', '', 'last_seen DESC');

// Sessões ativas = logou nos últimos 30 minutos
$active_threshold = time() - (30 * 60);
$online = array_filter($sessions, fn($s) => $s['last_seen'] >= $active_threshold);

@$resU = $db->select($table_name, '*', 'id = :id', '', [':id' => $_GET['update'] ?? 0]);

// Buscar DNS da tabela dns (SQLite - ./api/.db.db)
$dns_list = $db->select('dns', '*', '', 'title ASC');

// Criar array de DNS [url => title] para lookup rápido
$dns_names = [];
foreach($dns_list as $dns) {
    $dns_names[$dns['url']] = $dns['title'];
}

// BLOQUEIA A CRIAÇÃO DE NOVOS USUÁRIOS - redireciona se tentar acessar ?create
if(isset($_GET['create'])){
	echo "<script>window.location.href='".$page."'</script>";
	exit;
}

// BLOQUEIA O INSERT DE NOVOS USUÁRIOS
if(isset($_POST['submit'])){
	echo "<script>window.location.href='".$page."'</script>";
	exit;
}

// UPDATE - COM MENSAGEM DE SUCESSO
if(isset($_POST['submitU']) && isset($_GET['update'])){
	$userId = $_GET['update'];
	unset($_POST['submitU']);
	
	$updateData = [
		'title' => $_POST['title'] ?? '',
		'username' => $_POST['username'] ?? '',
		'password' => $_POST['password'] ?? '',
		'expire_date' => $_POST['expire_date'] ?? '',
		'server_dns' => $_POST['server_dns'] ?? ''
	];
	
	try {
		$result = $db->update($table_name, $updateData, 'id = :id', [':id' => $userId]);
		
		if($result){
			$success_msg = "Usuário atualizado com sucesso!";
		} else {
			$error_msg = "Erro ao atualizar usuário.";
		}
	} catch (Exception $e) {
		$error_msg = "Erro: " . $e->getMessage();
	}
	
	// Recarrega dados após update
	@$resU = $db->select($table_name, '*', 'id = :id', '', [':id' => $userId]);
}

// DELETE
if(isset($_GET['delete'])){
	$db->delete($table_name, 'id = :id', [':id' => $_GET['delete']]);
	echo "<script>window.location.href='".$page."?status=2'</script>";
	exit;
}

// RESET ALL
if(isset($_GET['resetall'])){
	$db->delete($table_name);
	$db->delete('active_sessions');
	echo "<script>window.location.href='".$page."?status=5'</script>";
	exit;
}

function expireClass($date) {
	if(empty($date)) return '';
	$diff = (strtotime($date) - time()) / 86400;
	if($diff < 0) return 'yt-expire-over';
	if($diff <= 7) return 'yt-expire-warn';
	return 'yt-expire-ok';
}
function expireLabel($date) {
	if(empty($date)) return '—';
	date_default_timezone_set('America/Sao_Paulo');
	return date('d/m/Y', strtotime($date));
}
function timeAgo($ts) {
	$diff = time() - $ts;
	if($diff < 60) return 'agora';
	if($diff < 3600) return floor($diff/60).'min atrás';
	if($diff < 86400) return floor($diff/3600).'h atrás';
	return date('d/m H:i', $ts);
}
?>

<!-- DELETE MODAL -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h2><i class="fas fa-trash-alt" style="color:var(--yt-red);margin-right:10px"></i>Confirmar exclusão</h2>
      </div>
      <div class="modal-body" style="color:var(--yt-text-muted);font-size:14px;padding:20px 24px">
        Tem certeza que deseja excluir este usuário? Esta ação não pode ser desfeita.
      </div>
      <div class="modal-footer">
        <button type="button" class="yt-btn-ghost" data-dismiss="modal">Cancelar</button>
        <a class="yt-btn-red btn-ok"><i class="fas fa-trash"></i> Excluir</a>
      </div>
    </div>
  </div>
</div>

<!-- RESET ALL MODAL -->
<div class="modal fade" id="confirm-reset" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h2><i class="fas fa-exclamation-triangle" style="color:#ffb400;margin-right:10px"></i>Resetar todos os usuários</h2>
      </div>
      <div class="modal-body" style="color:var(--yt-text-muted);font-size:14px;padding:20px 24px">
        Isso vai <strong style="color:var(--yt-red)">apagar TODOS os usuários</strong> da lista permanentemente. Esta ação não pode ser desfeita!
      </div>
      <div class="modal-footer">
        <button type="button" class="yt-btn-ghost" data-dismiss="modal">Cancelar</button>
        <a href="adduser.php?resetall" class="yt-btn-red"><i class="fas fa-rotate-right"></i> Confirmar Reset</a>
      </div>
    </div>
  </div>
</div>

<?php if (isset($_GET['update'])): ?>

<div class="yt-page-header">
  <div class="yt-page-title">
    <h1><i class="fas fa-user-edit" style="color:var(--yt-red);margin-right:8px"></i>Editar Usuário</h1>
  </div>
  <a href="<?= $page ?>" class="yt-btn-ghost"><i class="fas fa-arrow-left"></i> Voltar</a>
</div>

<?php if(isset($success_msg)): ?>
<div class="yt-card" style="max-width:600px; margin-bottom:20px; border-left:4px solid var(--yt-green);">
  <div class="yt-card-body" style="display:flex;align-items:center;gap:10px;color:var(--yt-green);">
    <i class="fas fa-check-circle" style="font-size:20px;"></i>
    <span style="font-weight:500;"><?= $success_msg ?></span>
  </div>
</div>
<?php endif; ?>

<?php if(isset($error_msg)): ?>
<div class="yt-card" style="max-width:600px; margin-bottom:20px; border-left:4px solid var(--yt-red);">
  <div class="yt-card-body" style="display:flex;align-items:center;gap:10px;color:var(--yt-red);">
    <i class="fas fa-times-circle" style="font-size:20px;"></i>
    <span style="font-weight:500;"><?= $error_msg ?></span>
  </div>
</div>
<?php endif; ?>

<div class="yt-card" style="max-width:600px">
  <div class="yt-card-header">
    <span class="yt-card-title"><i class="fas fa-edit"></i> Atualizar dados</span>
  </div>
  <div class="yt-card-body">
    <form method="post" action="<?= $page ?>?update=<?= htmlspecialchars($_GET['update']) ?>">
      <div class="yt-form-grid">
        <div class="yt-form-group">
          <label>Título</label>
          <input type="text" name="title" value="<?= htmlspecialchars($resU[0]['title'] ?? '') ?>" placeholder="Título">
        </div>
        <div class="yt-form-group">
          <label>Servidor DNS</label>
          <select name="server_dns" required style="width:100%;padding:10px 12px;border-radius:8px;border:1px solid var(--yt-border);background:var(--yt-surface);color:var(--yt-text);font-size:14px;outline:none;">
            <option value="">Selecione um servidor...</option>
            <?php foreach($dns_list as $dns): ?>
              <option value="<?= htmlspecialchars($dns['url']) ?>" <?= ($resU[0]['server_dns'] ?? '') == $dns['url'] ? 'selected' : '' ?>><?= htmlspecialchars($dns['title']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="yt-form-group">
          <label>Username</label>
          <input type="text" name="username" value="<?= htmlspecialchars($resU[0]['username'] ?? '') ?>" placeholder="Username" required>
        </div>
        <div class="yt-form-group">
          <label>Password</label>
          <input type="text" name="password" value="<?= htmlspecialchars($resU[0]['password'] ?? '') ?>" placeholder="Password" required>
        </div>
        <div class="yt-form-group">
          <label>Data de Expiração</label>
          <input type="date" name="expire_date" value="<?= htmlspecialchars($resU[0]['expire_date'] ?? '') ?>">
        </div>
      </div>
      <div class="yt-form-footer">
        <a href="<?= $page ?>" class="yt-btn-ghost">Cancelar</a>
        <button type="submit" name="submitU" class="yt-btn-red"><i class="fas fa-check"></i> Atualizar</button>
      </div>
    </form>
  </div>
</div>

<?php else: ?>

<?php
$expired = array_filter($res, fn($r) => !empty($r['expire_date']) && strtotime($r['expire_date']) < time());
$expiring = array_filter($res, fn($r) => !empty($r['expire_date']) && strtotime($r['expire_date']) >= time() && (strtotime($r['expire_date']) - time()) / 86400 <= 7);
?>

<div class="yt-page-header">
  <div class="yt-page-title">
    <h1>Panel Users</h1>
    <span class="yt-badge"><?= count($res) ?> usuários</span>
  </div>
  <div style="display:flex;gap:10px;align-items:center">
    <a href="#" class="yt-btn-ghost" data-toggle="modal" data-target="#confirm-reset"
       style="border-color:#ffb400;color:#ffb400;">
      <i class="fas fa-rotate-right"></i> Reset Clientes
    </a>
  </div>
</div>

<!-- Stats -->
<div class="yt-stats">
  <div class="yt-stat">
    <div class="yt-stat-icon blue"><i class="fas fa-users"></i></div>
    <div class="yt-stat-info"><span>Total</span><strong><?= count($res) ?></strong></div>
  </div>
  <div class="yt-stat">
    <div class="yt-stat-icon green"><i class="fas fa-check-circle"></i></div>
    <div class="yt-stat-info"><span>Ativos</span><strong><?= count($res) - count($expired) ?></strong></div>
  </div>
  <div class="yt-stat">
    <div class="yt-stat-icon yellow"><i class="fas fa-exclamation-triangle"></i></div>
    <div class="yt-stat-info"><span>Expirando</span><strong><?= count($expiring) ?></strong></div>
  </div>
  <div class="yt-stat">
    <div class="yt-stat-icon red"><i class="fas fa-times-circle"></i></div>
    <div class="yt-stat-info"><span>Expirados</span><strong><?= count($expired) ?></strong></div>
  </div>
  <div class="yt-stat">
    <div class="yt-stat-icon green" style="background:rgba(39,204,127,.2)">
      <i class="fas fa-wifi"></i>
    </div>
    <div class="yt-stat-info"><span>Online agora</span><strong><?= count($online) ?></strong></div>
  </div>
</div>

<!-- Tabela de usuários -->
<div class="yt-card">
  <div class="yt-card-header">
    <span class="yt-card-title"><i class="fas fa-list"></i> Lista de Usuários</span>
  </div>
  <div class="yt-table-wrap">
    <?php if(empty($res)): ?>
    <div class="yt-empty">
      <i class="fas fa-user-slash"></i>
      <p>Nenhum usuário cadastrado.<br>Contate o administrador.</p>
    </div>
    <?php else: ?>
    <table class="yt-table">
      <thead>
        <tr>
          <th>#</th>
          <th>Título</th>
          <th>Servidor</th>
          <th>Username</th>
          <th>Password</th>
          <th>Expiração</th>
          <th>Status</th>
          <th>Ações</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $onlineUsers = array_column(iterator_to_array(new ArrayIterator($online)), 'last_seen', 'username');
        foreach ($res as $i => $row):
          $isOnline = isset($onlineUsers[$row['username']]);
          // Pega o nome do servidor pelo URL, ou mostra o URL se não encontrar
          $serverName = $dns_names[$row['server_dns']] ?? $row['server_dns'] ?? '—';
        ?>
        <tr>
          <td style="color:var(--yt-text-muted);font-size:12px"><?= $i + 1 ?></td>
          <td>
            <div style="display:flex;align-items:center;gap:10px">
              <div style="width:34px;height:34px;border-radius:8px;background:var(--yt-surface2);display:flex;align-items:center;justify-content:center;color:<?= $isOnline ? 'var(--yt-green)' : 'var(--yt-blue)' ?>;flex-shrink:0">
                <i class="fas fa-user"></i>
              </div>
              <span style="font-weight:500"><?= htmlspecialchars($row['title']) ?></span>
            </div>
          </td>
          <td>
            <span style="font-weight:500;color:var(--yt-blue);font-size:13px;">
              <?= htmlspecialchars($serverName) ?>
            </span>
          </td>
          <td><span style="font-weight:500"><?= htmlspecialchars($row['username']) ?></span></td>
          <td><span class="yt-pass-badge"><?= htmlspecialchars($row['password']) ?></span></td>
          <td>
            <span class="yt-expire-badge <?= expireClass($row['expire_date']) ?>">
              <?= expireLabel($row['expire_date']) ?>
            </span>
          </td>
          <td>
            <?php if($isOnline): ?>
              <span style="display:inline-flex;align-items:center;gap:5px;font-size:12px;color:var(--yt-green)">
                <span style="width:7px;height:7px;border-radius:50%;background:var(--yt-green);box-shadow:0 0 5px var(--yt-green)"></span>
                Online
              </span>
            <?php else: ?>
              <span style="font-size:12px;color:var(--yt-text-muted)">Offline</span>
            <?php endif; ?>
          </td>
          <td>
            <div class="yt-act-wrap">
              <a class="yt-act-btn" href="<?= $page ?>?update=<?= $row['id'] ?>" title="Editar">
                <i class="fas fa-pencil-alt"></i>
              </a>
              <a class="yt-act-btn danger" href="#"
                data-href="<?= $page ?>?delete=<?= $row['id'] ?>"
                data-toggle="modal" data-target="#confirm-delete" title="Excluir">
                <i class="fas fa-trash"></i>
              </a>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>
</div>

<?php endif; ?>

<?php include ('includes/footer.php'); ?>

