<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user is admin
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Super Admin') {
    header('Location: index.php');
    exit();
}

$user_id = $_GET['id'] ?? 0;

// Prevent self-deletion
if ($user_id == $_SESSION['user_id']) {
    $_SESSION['error_message'] = "You cannot delete your own account!";
    header('Location: list_users.php');
    exit();
}

// Get user details
$sql = "SELECT CONCAT(first_name, ' ', last_name) as full_name FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "User not found!";
    header('Location: list_users.php');
    exit();
}

$user = $result->fetch_assoc();

// Handle deletion confirmation
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['confirm_delete'])) {
    // Begin transaction
    $conn->begin_transaction();
    
    try {
        // Log the deletion
        $activity_sql = "INSERT INTO activity_logs (user_id, action_type, module, reference_id, old_values) 
                       VALUES (?, 'DELETE', 'USER', ?, ?)";
        $activity_stmt = $conn->prepare($activity_sql);
        $old_values = json_encode(['deleted_user' => $user_id, 'deleted_by' => $_SESSION['user_id']]);
        $activity_stmt->bind_param("iis", $_SESSION['user_id'], $user_id, $old_values);
        $activity_stmt->execute();
        
        // Delete user (CASCADE will handle related records)
        $delete_sql = "DELETE FROM users WHERE id = ?";
        $delete_stmt = $conn->prepare($delete_sql);
        $delete_stmt->bind_param("i", $user_id);
        $delete_stmt->execute();
        
        $conn->commit();
        
        $_SESSION['success_message'] = "User '{$user['full_name']}' deleted successfully!";
        header('Location: list_users.php');
        exit();
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_message'] = "Failed to delete user: " . $e->getMessage();
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Delete User')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Users', 'title' => 'Delete User')); ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php 
                                echo $_SESSION['error_message']; 
                                unset($_SESSION['error_message']);
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row justify-content-center">
                        <div class="col-lg-6">
                            <div class="card border-danger">
                                <div class="card-header bg-danger">
                                    <h4 class="card-title mb-0 text-white">
                                        <i class="ri-error-warning-line me-2"></i>Confirm User Deletion
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <div class="text-center mb-4">
                                        <i class="ri-delete-bin-line text-danger" style="font-size: 4rem;"></i>
                                    </div>
                                    
                                    <div class="alert alert-danger" role="alert">
                                        <h5 class="alert-heading">⚠️ Warning: This action cannot be undone!</h5>
                                        <hr>
                                        <p class="mb-0">
                                            You are about to permanently delete the user:
                                            <strong><?php echo htmlspecialchars($user['full_name']); ?></strong>
                                        </p>
                                    </div>

                                    <div class="alert alert-warning" role="alert">
                                        <h6 class="mb-2">This will also delete:</h6>
                                        <ul class="mb-0">
                                            <li>All activity logs associated with this user</li>
                                            <li>Any tenant-specific data (if tenant)</li>
                                            <li>Property ownership records (if landlord)</li>
                                            <li>All related system records</li>
                                        </ul>
                                    </div>

                                    <form method="POST" id="deleteForm">
                                        <div class="form-check mb-3">
                                            <input class="form-check-input" type="checkbox" id="confirmCheck" required>
                                            <label class="form-check-label" for="confirmCheck">
                                                I understand this action is permanent and cannot be reversed
                                            </label>
                                        </div>

                                        <div class="d-grid gap-2">
                                            <button type="submit" name="confirm_delete" class="btn btn-danger btn-lg" id="deleteBtn" disabled>
                                                <i class="ri-delete-bin-line me-1"></i>Yes, Delete This User
                                            </button>
                                            <a href="list_users.php" class="btn btn-secondary btn-lg">
                                                <i class="ri-close-line me-1"></i>Cancel, Keep User
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <script>
        // Enable delete button only when checkbox is checked
        document.getElementById('confirmCheck').addEventListener('change', function() {
            document.getElementById('deleteBtn').disabled = !this.checked;
        });

        // Add confirmation dialog
        document.getElementById('deleteForm').addEventListener('submit', function(e) {
            if (!confirm('Are you absolutely sure? This user will be permanently deleted!')) {
                e.preventDefault();
                return false;
            }
        });
    </script>
</body>
</html>