<?php
// delete-leads-api.php

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

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Connect to DB
include 'dbconnect.php'; // your DB connection file

// Get POST data
$data = json_decode(file_get_contents('php://input'), true);

// Validate input
$leadIds = isset($data['leadIds']) ? array_map('intval', $data['leadIds']) : [];
$deleteLeadIds = isset($data['deleteLeadIds']) ? array_map('intval', $data['deleteLeadIds']) : [];

if (empty($leadIds) && empty($deleteLeadIds)) {
    echo json_encode(["success" => false, "message" => "No lead IDs provided."]);
    exit;
}

$errors = [];

// Process leadIds (e.g., set a flag)
if (!empty($leadIds)) {
    $idsString = implode(',', $leadIds);
    $sql = "UPDATE tbl_lead_user SET tbl_lead_user_flag = '1' WHERE tbl_lead_user_id IN ($idsString)";
    if (!mysqli_query($conn, $sql)) {
        $errors[] = "Error updating lead flags: " . mysqli_error($conn);
    } else {
        unset($_SESSION['selecteddelStatus']); // Optional: clean session
    }
}

// Process deleteLeadIds (e.g., delete from another table or same)
if (!empty($deleteLeadIds)) {
    $deleteIdsString = implode(',', $deleteLeadIds);
    $deleteSql = "DELETE FROM tbl_lead_user WHERE tbl_lead_user_id IN ($deleteIdsString)";
    if (!mysqli_query($conn, $deleteSql)) {
        $errors[] = "Error deleting leads: " . mysqli_error($conn);
    }
}

// Respond
if (empty($errors)) {
    echo json_encode(["success" => true]);
} else {
    echo json_encode(["success" => false, "message" => implode("; ", $errors)]);
}
?>
