<?php
// Endpoint: borrado masivo de leads seleccionados
session_start();
define('BASE_PATH', dirname(__DIR__, 2));
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

function isLoggedIn() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

header('Content-Type: application/json; charset=utf-8');

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'No autorizado']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Método no permitido']);
    exit;
}

$lead_ids = isset($_POST['lead_ids']) ? (array)$_POST['lead_ids'] : [];
$lead_ids = array_values(array_filter(array_map('intval', $lead_ids), function($v){ return $v > 0; }));

if (empty($lead_ids)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No se enviaron leads a eliminar']);
    exit;
}

$db = getDB();
$pdo = $db->getConnection();

if (!function_exists('userHasPermissionByName')) {
    function userHasPermissionByName($pdo, $permName, $userId) {
        if (empty($userId)) return false;
        $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
        $stmt->execute([$userId, $permName]);
        return (bool)$stmt->fetchColumn();
    }
}

$userId = (int)$_SESSION['user_id'];

// Verificar permiso para eliminar leads
if (!userHasPermissionByName($pdo, 'leads.delete', $userId)) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'No tienes permiso para eliminar leads']);
    exit;
}

try {
    $pdo->beginTransaction();

    // Si el usuario no tiene permiso de ver todos, restringimos a los que le pertenecen
    $restrictToAssigned = !userHasPermissionByName($pdo, 'leads.view_all', $userId);

    $placeholders = str_repeat('?,', count($lead_ids) - 1) . '?';
    $params = $lead_ids;

    if ($restrictToAssigned) {
        // Filtrar IDs que están asignados al usuario actual
        $paramsFilter = $lead_ids;
        array_unshift($paramsFilter, $userId); // user_id primero para la consulta
        $placeholdersFilter = str_repeat('?,', count($lead_ids) - 1) . '?';
        $rows = $db->select("SELECT id FROM leads WHERE assigned_to = ? AND id IN ($placeholdersFilter)", $paramsFilter);
        $lead_ids = array_map(function($r){ return (int)$r['id']; }, $rows);
        if (empty($lead_ids)) {
            $pdo->rollBack();
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'No puedes eliminar los leads seleccionados']);
            exit;
        }
        $placeholders = str_repeat('?,', count($lead_ids) - 1) . '?';
        $params = $lead_ids;
    }

    // Eliminar leads (historial y actividades se eliminan por ON DELETE CASCADE)
    $deleted = 0;
    if (!empty($lead_ids)) {
        $deleted = $db->execute("DELETE FROM leads WHERE id IN ($placeholders)", $params);
    }

    $pdo->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Leads eliminados correctamente',
        'data' => [
            'deleted_count' => (int)$deleted,
            'deleted_ids' => $lead_ids
        ]
    ]);
} catch (Exception $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error al eliminar leads', 'error' => $e->getMessage()]);
}
?>