<?php
//paneladm.jatpluss.com/admin/admin_delete_multiple.php

session_start();
header('Content-Type: application/json');

if (empty($_SESSION['admin_id'])) {
    http_response_code(403);
    echo json_encode(['error'=>'No autorizado']); exit;
}
require_once __DIR__.'/conexion.php';

/* --- CSRF --- */
if (empty($_POST['csrf_token']) || $_POST['csrf_token'] !== ($_SESSION['csrf_token'] ?? '')) {
    echo json_encode(['error'=>'CSRF inválido']); exit;
}

/* --- IDs recibidos --- */
$ids = $_POST['selected_ids'] ?? [];

$ids = array_filter($ids, function ($v) {   // ⇦ reemplazo compatible
    return is_numeric($v) && (int)$v > 0;
});
$ids = array_map('intval', $ids);

if (!$ids) {
    echo json_encode(['error' => 'No se enviaron IDs válidos']); 
    exit;
}
try {
    $place = rtrim(str_repeat('?,', count($ids)), ',');
    $stm = $pdo->prepare("DELETE FROM usuarios_correos WHERE id IN ($place)");
    $stm->execute($ids);
    $n = $stm->rowCount();
    echo json_encode(
        $n ? ['success'=>"$n registro(s) eliminado(s)"] 
           : ['error'=>'No se eliminaron registros']
    );
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error'=>'Error BD: '.$e->getMessage()]);
}
