<?php
session_start();
require_once "config.php";

// Only admin can delete users
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    die("Unauthorized access.");
}

// Get the user ID to delete
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid user ID.");
}

$user_id = (int)$_GET['id'];
$admin_id = $_SESSION['user_id'];

// Prevent deleting self
if ($user_id === $admin_id) {
    die("You cannot delete your own account.");
}

// Begin transaction
$conn->begin_transaction();

try {
    // Delete related property visits
    $stmt = $conn->prepare("DELETE FROM property_visits WHERE visitor_id = ? OR property_id IN (SELECT id FROM properties WHERE user_id = ?)");
    $stmt->bind_param("ii", $user_id, $user_id);
    $stmt->execute();
    $stmt->close();

    // Delete related profile visits
    $stmt = $conn->prepare("DELETE FROM profile_visits WHERE visitor_id = ? OR visited_user_id = ?");
    $stmt->bind_param("ii", $user_id, $user_id);
    $stmt->execute();
    $stmt->close();

    // Delete user transactions
    $stmt = $conn->prepare("DELETE FROM transactions WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->close();

    // Delete adverts associated with user's properties
    $stmt = $conn->prepare("DELETE a FROM adverts a INNER JOIN properties p ON a.property_id = p.id WHERE p.user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->close();

    // Delete property images & videos
    $stmt = $conn->prepare("DELETE pi, pv FROM property_images pi LEFT JOIN property_videos pv ON pi.property_id = pv.property_id LEFT JOIN properties p ON pi.property_id = p.id WHERE p.user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->close();

    // Delete properties
    $stmt = $conn->prepare("DELETE FROM properties WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->close();

    // Finally, delete the user
    $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->close();

    // Commit transaction
    $conn->commit();

    echo "User deleted successfully.";
} catch (Exception $e) {
    $conn->rollback();
    echo "Failed to delete user: " . $e->getMessage();
}
?>
