<?php
session_start();
$title = 'Cuentas asignadas';
require_once __DIR__ . '/../templates/header.php';
require_role(['admin', 'superadmin']);
csrf_check();
$error = null;
$notice = null;
$user_role = $_SESSION['user_role'] ?? '';
$user_id = $_SESSION['uid'] ?? 0;


// Procesar asignación múltiple
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'assign_multi') {
    $client_id = (int)($_POST['client_id'] ?? 0);
    $platform_ids = $_POST['platform_id'] ?? [];
    $emails = $_POST['email'] ?? [];
    $expiration_dates = $_POST['expiration_date'] ?? [];
    $prices = $_POST['price'] ?? [];
    $count = min(count($platform_ids), count($emails), count($expiration_dates), count($prices));
    if ($client_id <= 0) {
        $error = "Debes seleccionar un cliente válido para asignar cuentas.";
    } else {
        $ins = pdo()->prepare('INSERT IGNORE INTO assigned_accounts (client_id, platform_id, email, expiration_date, price, user_id) VALUES (?, ?, ?, ?, ?, ?)');
        $ok = 0; $skipped = 0;
        for ($i = 0; $i < $count; $i++) {
            $pid = (int)$platform_ids[$i];
            $email = trim($emails[$i] ?? '');
            $exp = $expiration_dates[$i] ?? null;
            $price = is_numeric($prices[$i]) ? floatval($prices[$i]) : null;
            $exp = ($exp === '') ? null : $exp;
            if ($pid > 0 && $email !== '') {
                try {
                    $ins->execute([$client_id, $pid, $email, $exp, $price, $user_id]);
                    if ($ins->rowCount() > 0) $ok++;
                    else $skipped++;
                } catch (PDOException $e) {
                    $skipped++;
                }
            }
        }
        $notice = "Agregados: $ok | Omitidos (duplicados o vacíos): $skipped";
    }
}

// Obtener clientes asignados a este admin
$clientsStmt = pdo()->prepare('SELECT id, name, email FROM users WHERE role = :role AND admin_id = :admin_id ORDER BY name');
$clientsStmt->execute(['role' => 'client', 'admin_id' => $user_id]);
$clients = $clientsStmt->fetchAll();

// Obtener plataformas
$platsStmt = pdo()->query('SELECT id, name FROM platforms ORDER BY name');
$plats = $platsStmt->fetchAll();
?>

<h3>Cuentas asignadas</h3>
<?php if ($notice): ?>
  <div class="alert alert-info"><?= e($notice) ?></div>
<?php endif; ?>
<?php if ($error): ?>
  <div class="alert alert-danger"><?= e($error) ?></div>
<?php endif; ?>

<!-- Formulario asignación múltiple -->
<div class="card card-body mb-3" style="padding: 12px;">
  <form method="post" id="assign-form">
    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
    <input type="hidden" name="action" value="assign_multi">
    <div class="row mb-3 g-2 align-items-end multi-row mb-2">
      <div class="col-md-6">
        <label for="client-select" class="form-label">Cliente</label>
        <select id="client-select" name="client_id" class="form-select" required>
          <option value="">-- Selecciona un cliente --</option>
          <?php foreach ($clients as $client): ?>
            <option value="<?= e($client['id']) ?>" data-email="<?= e($client['email']) ?>"><?= e($client['name']) ?> (<?= e($client['email']) ?>)</option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-4">
        <button type="submit" class="btn btn-primary">Asignar</button>
      </div>
    </div>
    <div id="multi-accounts">
      <div class="row g-2 align-items-end multi-row mb-2">
        <div class="col-md-3">
          <label class="form-label">Plataforma</label>
          <select class="form-select" name="platform_id[]" required>
            <option value="">-- Selecciona --</option>
            <?php foreach ($plats as $p): ?>
              <option value="<?= e($p['id']) ?>"><?= e($p['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label">Correo</label>
          <input type="email" name="email[]" class="form-control" placeholder="usuario@correo.com" required>
        </div>
        <div class="col-md-2">
          <label class="form-label">Precio</label>
          <input type="number" name="price[]" class="form-control" placeholder="$10.000" step="any" required>
        </div>
        <div class="col-md-2">
          <label class="form-label">Caducidad</label>
          <input type="date" name="expiration_date[]" class="form-control">
        </div>
        <div class="col-md-1 d-flex align-items-end">
          <button type="button" class="btn btn-success add-row" aria-label="Agregar fila">+</button>
        </div>
      </div>
    </div>
  </form>
</div>



<div class="row">
  <div class="col-md-3">
    <div class="card shadow-sm mb-4">
      <div class="card-body">
        <h5>Asignación Masiva</h5>
        <p class="text-muted small">Agregar cuentas a un cliente.</p>
        <a href="mass_accounts.php" class="btn btn-primary btn-sm">Abrir</a>
      </div>
    </div>
  </div>
  <div class="col-md-3">
    <div class="card shadow-sm mb-4">
      <div class="card-body">
        <h5>Consultar Asignaciones</h5>
        <p class="text-muted small">Consultar por cliente las cuentas.</p>
        <a href="view.php" class="btn btn-primary btn-sm">Abrir</a>
      </div>
    </div>
  </div>
</div>
<script>
document.addEventListener('click', function(e) {
  if (e.target.classList.contains('add-row')) {
    e.preventDefault();
    const container = document.getElementById('multi-accounts');
    const row = container.querySelector('.multi-row');
    const clone = row.cloneNode(true);
    // Limpiar valores de inputs y select en la fila clonada
    clone.querySelector('select[name="platform_id[]"]').value = '';
    clone.querySelector('input[name="email[]"]').value = '';
    clone.querySelector('input[name="expiration_date[]"]').value = '';

    // Cambiar el botón + a - para poder eliminar la fila clonada
    const btn = clone.querySelector('.add-row');
    btn.classList.remove('btn-success', 'add-row');
    btn.classList.add('btn-danger', 'remove-row');
    btn.textContent = '-';

    container.appendChild(clone);
  } else if (e.target.classList.contains('remove-row')) {
    e.preventDefault();
    e.target.closest('.multi-row').remove();
  }
});
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<?php require_once __DIR__ . '/../templates/footer.php'; ?>