<?php
require_once 'db.php';
session_start();

// ✅ Ensure user is logged in
if (!isset($_SESSION['logged_in_user'])) {
    http_response_code(403);
    echo json_encode(["error" => "Unauthorized"]);
    exit;
}

$loggedInUser = $_SESSION['logged_in_user'];

// ✅ Read JSON Input
$data = json_decode(file_get_contents("php://input"), true);
if (!isset($data['email'])) {
    http_response_code(400);
    echo json_encode(["error" => "Missing email parameter"]);
    exit;
}

// ✅ Get the lead's email to delete
$email = trim($data['email']);

// ✅ Get the logged-in user's ID from the users table
$stmt = $pdo->prepare("SELECT id FROM users WHERE user_id = ?");
$stmt->execute([$loggedInUser]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    http_response_code(404);
    echo json_encode(["error" => "User not found"]);
    exit;
}

$user_id = $user['id']; // ✅ This matches the leads table user_id

// ✅ Debugging: Check if the user and email exist in leads
$stmt = $pdo->prepare("SELECT * FROM leads WHERE email = ? AND user_id = ?");
$stmt->execute([$email, $user_id]);
$lead = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$lead) {
    http_response_code(404);
    echo json_encode(["error" => "Lead not found"]);
    exit;
}

// ✅ Delete the lead
$stmt = $pdo->prepare("DELETE FROM leads WHERE email = ? AND user_id = ?");
$deleted = $stmt->execute([$email, $user_id]);

if ($deleted) {
    echo json_encode(["success" => "Lead deleted successfully"]);
} else {
    http_response_code(500);
    echo json_encode(["error" => "Failed to delete lead"]);
}
?>
