<?php
$pageName = "Deleting User";
include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/header.php");

// Initialize message variable
$msg1 = '';

try {
    // Validate that ID parameter exists and is numeric
    if (!isset($_GET['id']) || empty($_GET['id']) || !is_numeric($_GET['id'])) {
        throw new Exception("Invalid user ID");
    }

    $id = intval($_GET['id']); // Sanitize the ID

    // Check if user exists before attempting to delete
    // Using only the columns we know exist
    $sql = "SELECT * FROM users WHERE id = :id";
    $stmt = $conn->prepare($sql);
    $stmt->execute(['id' => $id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        throw new Exception("User not found");
    }

    // Get username for display (try different possible column names)
    $username = isset($user['uname']) ? $user['uname'] : 
                (isset($user['username']) ? $user['username'] : 
                (isset($user['name']) ? $user['name'] : 'User'));

    // Prevent deletion of admin account (optional)
    if ($id == 1) {
        throw new Exception("Cannot delete the primary administrator account");
    }

    // Try to delete related records first to avoid foreign key constraints
    // These will fail silently if tables don't exist
    $relatedTables = [
        "DELETE FROM notifications WHERE user_id = :id",
        "DELETE FROM cards WHERE user_id = :id",
        "DELETE FROM loans WHERE user_id = :id",
        "DELETE FROM transactions WHERE sender_id = :id OR receiver_id = :id OR user_id = :id",
        "DELETE FROM wire_transfer WHERE user_id = :id",
        "DELETE FROM domestic_transfer WHERE user_id = :id",
        "DELETE FROM account_history WHERE user_id = :id"
    ];

    foreach ($relatedTables as $sql) {
        try {
            $stmt = $conn->prepare($sql);
            $stmt->execute(['id' => $id]);
        } catch (PDOException $e) {
            // Table might not exist or have different structure, continue anyway
        }
    }

    // Now delete the user
    $sql = "DELETE FROM users WHERE id = :id";
    $stmt = $conn->prepare($sql);
    $result = $stmt->execute(['id' => $id]);
    $rowsDeleted = $stmt->rowCount();

    if ($result && $rowsDeleted > 0) {
        $msg1 = "
        <div class='alert alert-success'>
            <script type='text/javascript'>
                function Redirect() {
                    window.location='./users.php';
                }
                setTimeout('Redirect()', 3000);
            </script>
            <center><img src='../assets/images/loading.gif' width='180px' /></center>
            <center>
                <strong style='color:black;'>
                    User '" . htmlspecialchars($username) . "' deleted successfully!<br>
                    Please wait while we redirect you...
                </strong>
            </center>
        </div>";
    } else {
        throw new Exception("Failed to delete user. User may have already been deleted.");
    }

} catch (PDOException $e) {
    // Database error
    error_log("Database error in delete user: " . $e->getMessage());
    $msg1 = "
    <div class='alert alert-danger'>
        <center>
            <h4><i class='fa fa-warning'></i> Database Error</h4>
            <strong>Unable to delete user</strong><br><br>
            <small>Error: " . htmlspecialchars($e->getMessage()) . "</small><br><br>
            <a href='./users.php' class='btn btn-primary btn-sm' style='margin-top:10px;'>
                <i class='fa fa-arrow-left'></i> Back to Users
            </a>
        </center>
    </div>";
    
} catch (Exception $e) {
    // General error
    $msg1 = "
    <div class='alert alert-danger'>
        <center>
            <h4><i class='fa fa-warning'></i> Error</h4>
            <strong>" . htmlspecialchars($e->getMessage()) . "</strong><br><br>
            <a href='./users.php' class='btn btn-primary btn-sm' style='margin-top:10px;'>
                <i class='fa fa-arrow-left'></i> Back to Users
            </a>
        </center>
    </div>";
}

?>

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>Delete User</h1>
        <ol class="breadcrumb">
            <li><a href="./dashboard.php"><i class="fa fa-dashboard"></i> Dashboard</a></li>
            <li><a href="./users.php"><i class="fa fa-users"></i> Users</a></li>
            <li class="active">Delete</li>
        </ol>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-md-12">
                <?php if (isset($msg1)) echo $msg1; ?>
            </div>
        </div>
    </section>
    <!-- /.content -->
</div>
<!-- /.content-wrapper -->

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/admin/layout/footer.php");
?>