<?php
$title = 'Carga Masiva en Bloque';
require_once __DIR__ . '/../templates/header.php';
require_role(['superadmin', 'admin']);
csrf_check();
$error = null;
$notice = null;
$user = current_user();
$user_role = $_SESSION['user_role'] ?? '';
$user_id = $_SESSION['uid'] ?? 0;

// Obtener clientes asignados solo 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 asignadas solo a este admin (filtrado por user_id)
$platsStmt = pdo()->prepare('SELECT id, name FROM platforms WHERE user_id = 0 OR user_id = :user_id ORDER BY id ASC');
$platsStmt->execute(['user_id' => $user_id]);
$plats = $platsStmt->fetchAll();

// Función para mostrar fecha en formato día-mes-año
function formatDateForDisplay($dateString) {
    if ($dateString === null || $dateString === '') return '';
    $dateObj = DateTime::createFromFormat('Y-m-d', $dateString);
    return $dateObj ? $dateObj->format('d-m-Y') : $dateString;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $client_id = (int)($_POST['client_id'] ?? 0);
    $bulk_data = trim($_POST['bulk_data'] ?? '');
    $plat_ids = array_column($plats, 'id');

    if (!$client_id || !$bulk_data) {
        $error = "Selecciona un cliente y escribe las cuentas masivas.";
    } else {
        $lines = preg_split('/\r\n|\r|\n/', $bulk_data);
        $stmt = pdo()->prepare('INSERT IGNORE INTO assigned_accounts (client_id, platform_id, email, expiration_date, price) VALUES (?, ?, ?, ?, ?)');
        $ok = 0;
        $skipped = 0;

        foreach ($lines as $line) {
            $parts = array_map('trim', explode(',', $line));
            if (count($parts) < 3) {
                $skipped++;
                continue;
            }

            $email = $parts[0];
            $platform_id = (int)$parts[1];
            $expiration_raw = $parts[2];
            $price = $parts[3] ?? null;

            // Convertir fecha DD-MM-YYYY a YYYY-MM-DD para guardar en BD
            if ($expiration_raw !== '') {
                $expiration = date('Y-m-d', strtotime(str_replace('/', '-', $expiration_raw)));
            } else {
                $expiration = null;
            }

            if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !in_array($platform_id, $plat_ids, true) || ($price !== null && !is_numeric($price))) {
                $skipped++;
                continue;
            }

            $price = $price === '' ? null : $price;

            try {
                $stmt->execute([$client_id, $platform_id, $email, $expiration, $price]);
                if ($stmt->rowCount() > 0) $ok++;
                else $skipped++;
            } catch (PDOException $e) {
                $skipped++;
            }
        }

        $notice = "Cuentas agregadas: $ok | Omitidas: $skipped";
    }
}
?>
<div class="container my-4">
  <h3>Asignación masiva en bloque</h3>
  <?php if ($error): ?>
    <div class="alert alert-danger"><?= e($error) ?></div>
  <?php endif; ?>
  <?php if ($notice): ?>
    <div class="alert alert-info"><?= e($notice) ?></div>
  <?php endif; ?>
  <form method="post" autocomplete="off">
    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
    <div class="mb-3">
      <label for="client-select" class="form-label">Cliente</label>
      <select name="client_id" id="client-select" class="form-select" required>
        <option value="">-- Selecciona un cliente --</option>
        <?php foreach ($clients as $client): ?>
          <option value="<?= e($client['id']) ?>"><?= e($client['name']) ?> (<?= e($client['email']) ?>)</option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="mb-3">
      <label for="bulk-data" class="form-label">Ingresa este formato (correo, id plataforma, fecha caducidad, precio opcional) -> usuario@mail.com,1,31-12-2025,19.99</label>
      <textarea id="bulk-data" name="bulk_data" rows="10" class="form-control" placeholder="usuario@mail.com,1,31-12-2025,19.99"></textarea>
      <small class="form-text text-muted">Una cuenta por línea, separados por comas. La fecha caducidad y el precio son opcionales.</small>
    </div>
    <div class="mb-3 mt-4">
      <strong>Plataformas disponibles:</strong>
      <table class="table table-bordered table-sm mt-2" style="max-width:400px;">
        <thead>
          <tr>
            <th>ID</th><th>Plataforma</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($plats as $plat): ?>
            <tr>
              <td><?= e($plat['id']) ?></td>
              <td><?= e($plat['name']) ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <button type="submit" class="btn btn-primary">Asignar cuentas masivamente</button>
  </form>
</div>
<?php require_once __DIR__ . '/../templates/footer.php'; ?>
