<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$db = new SQLite3('./a/.eggziedb.db');
$db->exec('CREATE TABLE IF NOT EXISTS ibo(id INTEGER PRIMARY KEY NOT NULL,mac_address VARCHAR(100),username VARCHAR(100),password VARCHAR(100),expire_date VARCHAR(100),url VARCHAR(100),title VARCHAR(100),created_at VARCHAR(100))');

$dup_id   = isset($_GET['dup']) ? (int)$_GET['dup'] : 0;
$original = null;
if ($dup_id > 0) {
    $stmt = $db->prepare('SELECT * FROM ibo WHERE id = :id');
    $stmt->bindValue(':id', $dup_id, SQLITE3_INTEGER);
    $original = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
}
if (!$original) { header('Location: users.php'); exit; }

$error = $success = '';

if (isset($_POST['submit'])) {
    $mac = strtoupper(trim($_POST['mac_address']));
    if (empty($mac)) {
        $error = 'O campo MAC Address é obrigatório.';
    } else {
        $chk = $db->prepare('SELECT id FROM ibo WHERE mac_address = :mac');
        $chk->bindValue(':mac', $mac, SQLITE3_TEXT);
        if ($chk->execute()->fetchArray()) {
            $error = 'Este MAC Address já existe no sistema.';
        } else {
            $ne   = date('Y-m-d', strtotime($_POST['expire_date']));
            $full = date('Y-m-d') . 'T' . date('h:m:s') . '.000000Z';
            $ins  = $db->prepare('INSERT INTO ibo(mac_address,username,password,expire_date,url,title,created_at) VALUES(:mac,:user,:pass,:exp,:url,:title,:created)');
            $ins->bindValue(':mac',     $mac,                               SQLITE3_TEXT);
            $ins->bindValue(':user',    trim($_POST['username']),           SQLITE3_TEXT);
            $ins->bindValue(':pass',    trim($_POST['password']),           SQLITE3_TEXT);
            $ins->bindValue(':exp',     $ne,                                SQLITE3_TEXT);
            $ins->bindValue(':url',     trim($_POST['dns']),                SQLITE3_TEXT);
            $ins->bindValue(':title',   trim($_POST['title']),              SQLITE3_TEXT);
            $ins->bindValue(':created', $full,                              SQLITE3_TEXT);
            $ins->execute();
            $db->close();
            header('Location: users.php');
            exit;
        }
    }
}

include 'includes/header.php';
?>

<div class="page-header">
  <h1><i class="fas fa-copy" style="color:var(--orange);font-size:18px"></i> Duplicar Cliente</h1>
  <p>Cria um novo cliente baseado nos dados de um existente.</p>
</div>

<?php if ($error): ?>
  <div class="u-alert u-alert-danger"><i class="fas fa-exclamation-circle"></i><?php echo htmlspecialchars($error); ?></div>
<?php endif; ?>

<!-- Source banner -->
<div class="source-banner mb-4">
  <i class="fas fa-clone"></i>
  <div class="source-banner-text">
    <strong>Copiando de: <?php echo htmlspecialchars($original['title']); ?></strong>
    <small>MAC original: <?php echo htmlspecialchars($original['mac_address']); ?> &mdash; DNS: <?php echo htmlspecialchars($original['url']); ?></small>
  </div>
</div>

<!-- M3U Extractor -->
<div class="u-card warning-left mb-4">
  <div class="u-card-header">
    <span class="u-card-title warning"><i class="fas fa-magic"></i> M3U Extractor <span style="color:var(--text-muted);font-weight:400;font-size:11px">(opcional)</span></span>
  </div>
  <div class="u-card-body">
    <div class="input-group">
      <input class="u-input" id="m3u_address" placeholder="Cole o link M3U para preencher automaticamente…" type="text">
      <button class="u-btn u-btn-warning" onclick="extract(event)">
        <i class="fas fa-expand-arrows-alt"></i> Extrair
      </button>
    </div>
  </div>
</div>

<!-- Duplicate Form -->
<div class="u-card orange-left glow">
  <div class="u-card-header">
    <span class="u-card-title"><i class="fas fa-id-card"></i> Dados do Novo Cliente</span>
  </div>
  <div class="u-card-body">
    <form method="post">

      <div class="grid-2">
        <div class="form-group">
          <label class="form-label">Novo MAC Address <span class="req">*</span></label>
          <input class="u-input" id="mac_address" name="mac_address"
                 placeholder="AA:BB:CC:DD:EE:FF" type="text" required
                 value="<?php echo isset($_POST['mac_address']) ? htmlspecialchars($_POST['mac_address']) : ''; ?>">
          <p class="form-hint">Deve ser diferente do MAC original.</p>
        </div>
        <div class="form-group">
          <label class="form-label">Server Name <span class="req">*</span></label>
          <input class="u-input" name="title" placeholder="Nome do servidor"
                 value="<?php echo htmlspecialchars(isset($_POST['title']) ? $_POST['title'] : $original['title']); ?>" required>
        </div>
        <div class="form-group">
          <label class="form-label">DNS / Servidor <span class="req">*</span></label>
          <input class="u-input" name="dns" id="server_url" placeholder="http://servidor.com"
                 value="<?php echo htmlspecialchars(isset($_POST['dns']) ? $_POST['dns'] : $original['url']); ?>" required>
        </div>
        <div class="form-group">
          <label class="form-label">Username <span class="req">*</span></label>
          <input class="u-input" name="username" id="username" placeholder="Usuário"
                 value="<?php echo htmlspecialchars(isset($_POST['username']) ? $_POST['username'] : $original['username']); ?>" required>
        </div>
        <div class="form-group">
          <label class="form-label">Password <span class="req">*</span></label>
          <input class="u-input" name="password" id="password" placeholder="Senha"
                 value="<?php echo htmlspecialchars(isset($_POST['password']) ? $_POST['password'] : $original['password']); ?>" required>
        </div>
        <div class="form-group">
          <label class="form-label">Data de Expiração</label>
          <input class="u-input" name="expire_date" id="datetimepicker" placeholder="YYYY-MM-DD" type="text"
                 value="<?php echo htmlspecialchars(isset($_POST['expire_date']) ? $_POST['expire_date'] : $original['expire_date']); ?>">
        </div>
      </div>

      <div class="flex gap-3 mt-2">
        <button class="u-btn u-btn-success u-btn-lg" name="submit" type="submit">
          <i class="fas fa-copy"></i> Duplicar Cliente
        </button>
        <a href="users.php" class="u-btn u-btn-ghost u-btn-lg">
          <i class="fas fa-arrow-left"></i> Cancelar
        </a>
      </div>

    </form>
  </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function(){
    var mac = document.getElementById("mac_address");
    if(mac){ mac.addEventListener("input", function(e){
        var v = e.target.value.replace(/[^a-fA-F0-9]/g,"").toUpperCase(), f="";
        for(var i=0;i<v.length;i++){ f+=v[i]; if((i+1)%2===0&&i<v.length-1) f+=":"; }
        e.target.value=f;
    });}
});
function extract(e){ e.preventDefault();
    var l=document.getElementById("m3u_address").value;
    document.getElementById("server_url").value=l.split("/get.php")[0];
    document.getElementById("username").value=getP("username",l);
    document.getElementById("password").value=getP("password",l);
}
function getP(n,url){ n=n.replace(/[\[\]]/g,"\\$&"); var r=new RegExp("[?&]"+n+"(=([^&#]*)|&|#|$)").exec(url); if(!r||!r[2])return""; return decodeURIComponent(r[2].replace(/\+/g," ")); }
</script>

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