<?php
require_once '../../includes/auth.php';
require_once '../../db.php';

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    header("Location: index.php");
    exit;
}

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

$user = $conn->query("SELECT id, role FROM users WHERE id = $id")->fetch_assoc();

if (!$user) {
    header("Location: index.php");
    exit;
}

if ($user['role'] === 'admin') {
    die("Admin users cannot be deleted.");
}

if ($id === $loggedInId) {
    die("You cannot delete your own account.");
}

$conn->begin_transaction();
try {
    $conn->query("DELETE FROM user_companies WHERE user_id = $id");
    $conn->query("DELETE FROM users WHERE id = $id");
    $conn->commit();
    header("Location: index.php?deleted=1");
    exit;
} catch (Exception $e) {
    $conn->rollback();
    die("Delete failed: " . $e->getMessage());
}
