<?php
session_start();

$usuario_default   = 'JOSE';
$contrasena_default = 'JOSE2611';

$servername = "localhost";
$username   = "toncass_cod";
$password   = "altamar599";
$dbname     = "toncass_cod";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("❌ Error al conectar con la base de datos.");
}
$conn->set_charset('utf8mb4');

/* === Guardar desde Excel === */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['guardar_excel'])) {
    $json = json_decode(file_get_contents("php://input"), true);
    $nuevos=0; $actual=0; $skip=0;

    $sel = $conn->prepare("SELECT id FROM usuarios_disney WHERE LOWER(usuario)=LOWER(?) LIMIT 1");
    $ins = $conn->prepare("INSERT INTO usuarios_disney (usuario, contrasena) VALUES (?, ?)");
    $upd = $conn->prepare("UPDATE usuarios_disney SET contrasena=? WHERE id=?");

    foreach ($json as $fila) {
        $usuarioExacto = trim((string)($fila[0] ?? ''));
        $clave         = trim((string)($fila[1] ?? ''));
        if ($usuarioExacto === '' || $clave === '') { $skip++; continue; }

        $sel->bind_param("s", $usuarioExacto);
        $sel->execute();
        $r = $sel->get_result()->fetch_assoc();

        if (!$r) {
            $ins->bind_param("ss", $usuarioExacto, $clave);
            $ins->execute();
            $nuevos++;
        } else {
            $id = (int)$r['id'];
            $upd->bind_param("si", $clave, $id);
            $upd->execute();
            $actual++;
        }
    }
    echo json_encode(["ok"=>true,"msg"=>"Excel: $nuevos nuevos, $actual actualizados, $skip omitidos."]);
    exit;
}

/* === Guardar desde TXT === */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['guardar_txt'])) {
    $raw = trim(file_get_contents("php://input"));
    $lines = preg_split('/\r\n|\r|\n/', $raw);
    $nuevos=0; $actual=0; $skip=0;

    $sel = $conn->prepare("SELECT id FROM usuarios_disney WHERE LOWER(usuario)=LOWER(?) LIMIT 1");
    $ins = $conn->prepare("INSERT INTO usuarios_disney (usuario, contrasena) VALUES (?, ?)");
    $upd = $conn->prepare("UPDATE usuarios_disney SET contrasena=? WHERE id=?");

    foreach ($lines as $line) {
        $line = trim($line);
        if ($line==='') continue;

        if (!preg_match('/^(.+?)\s*:\s*(.+)$/', $line, $m)) { $skip++; continue; }
        $usuarioExacto = trim($m[1]);
        $clave         = trim($m[2]);

        if ($usuarioExacto==='' || $clave==='') { $skip++; continue; }

        $sel->bind_param("s", $usuarioExacto);
        $sel->execute();
        $r = $sel->get_result()->fetch_assoc();

        if (!$r) {
            $ins->bind_param("ss", $usuarioExacto, $clave);
            $ins->execute();
            $nuevos++;
        } else {
            $id = (int)$r['id'];
            $upd->bind_param("si", $clave, $id);
            $upd->execute();
            $actual++;
        }
    }
    echo json_encode(["ok"=>true,"msg"=>"TXT: $nuevos nuevos, $actual actualizados, $skip inválidos."]);
    exit;
}

/* === Guardar desde Pegar Manual === */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['guardar_pegar'])) {
    $raw = trim($_POST['lista'] ?? '');
    $lines = preg_split('/\r\n|\r|\n/', $raw);
    $nuevos=0; $actual=0; $skip=0;

    $sel = $conn->prepare("SELECT id FROM usuarios_disney WHERE LOWER(usuario)=LOWER(?) LIMIT 1");
    $ins = $conn->prepare("INSERT INTO usuarios_disney (usuario, contrasena) VALUES (?, ?)");
    $upd = $conn->prepare("UPDATE usuarios_disney SET contrasena=? WHERE id=?");

    foreach ($lines as $line) {
        $line = trim($line);
        if ($line==='') continue;

        if (!preg_match('/^(.+?)\s*:\s*(.+)$/', $line, $m)) { $skip++; continue; }
        $usuarioExacto = trim($m[1]);
        $clave         = trim($m[2]);

        if ($usuarioExacto==='' || $clave==='') { $skip++; continue; }

        $sel->bind_param("s", $usuarioExacto);
        $sel->execute();
        $r = $sel->get_result()->fetch_assoc();

        if (!$r) {
            $ins->bind_param("ss", $usuarioExacto, $clave);
            $ins->execute();
            $nuevos++;
        } else {
            $id = (int)$r['id'];
            $upd->bind_param("si", $clave, $id);
            $upd->execute();
            $actual++;
        }
    }
    echo json_encode(["ok"=>true,"msg"=>"Pegado: $nuevos nuevos, $actual actualizados, $skip inválidos."]);
    exit;
}

/* === Eliminar usuario === */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['eliminar_usuario'])) {
    $id = intval($_POST['id']);
    if ($conn->query("DELETE FROM usuarios_disney WHERE id = $id")) {
        echo "✅ Usuario eliminado.";
    } else {
        echo "❌ Error al eliminar.";
    }
    exit;
}

/* === Actualizar contraseña === */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['actualizar_contra'])) {
    $id = intval($_POST['id']);
    $clave = $conn->real_escape_string($_POST['clave']);
    if ($conn->query("UPDATE usuarios_disney SET contrasena = '$clave' WHERE id = $id")) {
        echo "✅ Contraseña actualizada.";
    } else {
        echo "❌ Error al actualizar.";
    }
    exit;
}

/* === LOGIN === */
if (!isset($_SESSION['admin'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user'])) {
        if ($_POST['user'] === $usuario_default && $_POST['pass'] === $contrasena_default) {
            $_SESSION['admin'] = true;
            header("Location: admin.php");
            exit;
        } else {
            $error_login = "❌ Credenciales incorrectas.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Panel Admin - Usuarios</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
</head>
<body class="bg-gradient-to-r from-indigo-900 via-purple-900 to-blue-900 min-h-screen text-white flex items-center justify-center p-4">

<?php if (!isset($_SESSION['admin'])): ?>
  <form method="POST" class="bg-gray-900/80 p-8 rounded-xl shadow-xl w-full max-w-sm">
    <h2 class="text-2xl font-bold mb-6 text-center text-purple-300">🔐 Iniciar sesión</h2>
    <?php if (isset($error_login)): ?>
      <p class="text-red-400 mb-4 text-center"><?= $error_login ?></p>
    <?php endif; ?>
    <input name="user" type="text" placeholder="Usuario" required class="w-full mb-4 px-4 py-2 bg-gray-800 border border-purple-600 rounded">
    <input name="pass" type="password" placeholder="Contraseña" required class="w-full mb-6 px-4 py-2 bg-gray-800 border border-purple-600 rounded">
    <button type="submit" class="w-full bg-purple-700 hover:bg-purple-800 py-2 rounded font-semibold">Entrar</button>
  </form>
<?php else: ?>
<?php
$usuarios = [];
$result = $conn->query("SELECT id, usuario, contrasena FROM usuarios_disney ORDER BY id DESC");
while ($row = $result->fetch_assoc()) {
    $usuarios[] = $row;
}
?>
<div class="max-w-6xl w-full bg-gray-900 p-8 rounded-xl shadow-xl">
  <div class="flex justify-between items-center mb-6">
    <h1 class="text-2xl font-bold text-purple-300">📥 Subir Usuarios</h1>
    <form method="POST"><button name="logout" class="bg-red-500 hover:bg-red-600 px-4 py-1 rounded">Cerrar sesión</button></form>
  </div>

  <!-- Excel -->
  <input type="file" id="excelFile" accept=".xlsx" class="mb-2 text-white" />
  <button onclick="procesarExcel()" class="bg-purple-700 hover:bg-purple-800 px-6 py-2 rounded-lg font-semibold mb-6">Procesar Excel</button>

  <!-- TXT -->
  <input type="file" id="txtFile" accept=".txt" class="mb-2 text-white" />
  <button onclick="procesarTxt()" class="bg-purple-700 hover:bg-purple-800 px-6 py-2 rounded-lg font-semibold mb-6">Procesar TXT</button>

  <!-- Pegar manual -->
  <textarea id="pegarLista" rows="6" class="w-full text-black p-2 mb-2 rounded" placeholder="correo@dominio.com:clave123"></textarea>
  <button onclick="procesarPegado()" class="bg-purple-700 hover:bg-purple-800 px-6 py-2 rounded-lg font-semibold mb-6">Procesar Pegado</button>

  <!-- Resumen -->
  <div id="resultado" class="p-4 text-center font-bold"></div>

  <table id="tabla" class="display w-full text-sm">
    <thead><tr><th>Usuario</th><th>Contraseña</th><th>Acciones</th></tr></thead>
    <tbody>
      <?php foreach ($usuarios as $u): ?>
        <tr id="fila-<?= $u['id'] ?>">
          <td><?= htmlspecialchars($u['usuario']) ?></td>
          <td><input type="text" id="clave-<?= $u['id'] ?>" value="<?= htmlspecialchars($u['contrasena']) ?>" class="px-2 py-1 bg-gray-700 border rounded w-full"></td>
          <td class="text-center space-x-2">
            <button onclick="guardarClave(<?= $u['id'] ?>)" class="bg-green-600 hover:bg-green-700 px-3 py-1 rounded">Guardar</button>
            <button onclick="eliminarUsuario(<?= $u['id'] ?>)" class="bg-red-600 hover:bg-red-700 px-3 py-1 rounded">Eliminar</button>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script>
function mostrarResumen(msg){ document.getElementById("resultado").innerHTML=msg; }

function procesarExcel() {
  const file=document.getElementById('excelFile').files[0];
  if(!file) return alert("Selecciona un archivo Excel");
  const reader=new FileReader();
  reader.onload=e=>{
    const data=new Uint8Array(e.target.result);
    const wb=XLSX.read(data,{type:'array'});
    const sheet=wb.Sheets[wb.SheetNames[0]];
    const rows=XLSX.utils.sheet_to_json(sheet,{header:1});
    fetch('admin.php?guardar_excel=1',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(rows.slice(1))})
    .then(r=>r.json()).then(d=>{mostrarResumen(d.msg); location.reload();});
  };
  reader.readAsArrayBuffer(file);
}

function procesarTxt() {
  const file=document.getElementById('txtFile').files[0];
  if(!file) return alert("Selecciona un archivo TXT");
  const reader=new FileReader();
  reader.onload=e=>{
    fetch('admin.php?guardar_txt=1',{method:'POST',body:e.target.result})
    .then(r=>r.json()).then(d=>{mostrarResumen(d.msg); location.reload();});
  };
  reader.readAsText(file);
}

function procesarPegado() {
  const data=document.getElementById('pegarLista').value;
  if(!data.trim()) return alert("No hay datos");
  fetch('admin.php?guardar_pegar=1',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'lista='+encodeURIComponent(data)})
  .then(r=>r.json()).then(d=>{mostrarResumen(d.msg); location.reload();});
}

function eliminarUsuario(id){
  if(!confirm("¿Eliminar?"))return;
  fetch('admin.php?eliminar_usuario=1',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id})
  .then(r=>r.text()).then(m=>{mostrarResumen(m);document.getElementById("fila-"+id).remove();});
}
function guardarClave(id){
  const nueva=document.getElementById("clave-"+id).value;
  fetch('admin.php?actualizar_contra=1',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id+'&clave='+encodeURIComponent(nueva)})
  .then(r=>r.text()).then(m=>mostrarResumen(m));
}
document.addEventListener("DOMContentLoaded",()=>{$('#tabla').DataTable();});
</script>
<?php endif; ?>

<?php
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['logout'])){
  session_destroy();
  echo "<script>location.href='admin.php';</script>"; exit;
}
?>
</body>
</html>