<?php 
include('auth.php'); 
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// --- DATABASE CONFIGURATION ---
$host = "localhost";
$db_user = "root"; 
$db_pass = ""; 

$conn = new mysqli($host, $db_user, $db_pass);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// 1. HANDLE SINGLE DELETE
if (isset($_GET['delete_user']) && isset($_GET['host'])) {
    $u = $conn->real_escape_string($_GET['delete_user']);
    $h = $conn->real_escape_string($_GET['host']);
    $dbName = $u . "db";
    
    if ($conn->query("DROP USER '$u'@'$h'")) {
        $conn->query("DROP DATABASE IF EXISTS `$dbName` ");
        $_SESSION['status'] = "User '$u' and database '$dbName' removed.";
    }
    header("Location: dashboard.php"); // REDIRECT TO PREVENT REFRESH ISSUES
    exit();
}

// 2. HANDLE BULK DELETE
if (isset($_POST['bulk_delete']) && !empty($_POST['selected_users'])) {
    $count = 0;
    foreach ($_POST['selected_users'] as $user_host) {
        list($u, $h) = explode('|', $user_host);
        $u = $conn->real_escape_string($u);
        $h = $conn->real_escape_string($h);
        $dbName = $u . "db";
        if ($conn->query("DROP USER '$u'@'$h'")) {
            $conn->query("DROP DATABASE IF EXISTS `$dbName` ");
            $count++;
        }
    }
    $_SESSION['status'] = "Bulk action: $count accounts removed.";
    header("Location: dashboard.php");
    exit();
}

// 3. HANDLE TEXTAREA BULK PROCESS
if (isset($_POST['bulk_text_import']) && !empty($_POST['usn_list'])) {
    $input = $_POST['usn_list'];
    $raw_usns = preg_split('/[,\n\r]+/', $input);
    $created = 0; $skipped = 0;

    foreach ($raw_usns as $usn) {
        $usn = strtolower(trim(preg_replace("/[^a-zA-Z0-9]/", "", $usn)));
        if (empty($usn)) continue;

        $dbName = $usn . "db";
        $check = $conn->query("SELECT User FROM mysql.user WHERE User = '$usn'");
        
        if ($check && $check->num_rows > 0) {
            $skipped++;
            continue;
        }

        $conn->query("CREATE DATABASE IF NOT EXISTS `$dbName` ");
        if ($conn->query("CREATE USER '$usn'@'%' IDENTIFIED BY '$usn'")) {
            $conn->query("GRANT ALL PRIVILEGES ON `$dbName`.* TO '$usn'@'%'");
            $created++;
        }
    }
    $conn->query("FLUSH PRIVILEGES");
    $_SESSION['status'] = "Import complete: $created created, $skipped skipped.";
    header("Location: dashboard.php");
    exit();
}

// Fetch Users for display
$system_users = "'root', 'mariadb.sys', 'mysql', 'debian-sys-maint', 'phpmyadmin', 'pma'";
$users_result = $conn->query("SELECT User, Host FROM mysql.user WHERE User NOT IN ($system_users) ORDER BY User ASC");

// Get message from session and then clear it
$status_msg = $_SESSION['status'] ?? "";
unset($_SESSION['status']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MariaDB Lab Manager</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f4f7f6; color: #333; margin: 0; padding: 20px; }
        .container { max-width: 1100px; margin: 0 auto; }
        header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; border-bottom: 2px solid #ddd; padding-bottom: 10px;}
        h1 { margin: 0; color: #2c3e50; font-size: 24px; }
        .status { background: #d1ecf1; color: #0c5460; padding: 12px; border-radius: 6px; border: 1px solid #bee5eb; margin-bottom: 20px; font-weight: bold; animation: fadeOut 5s forwards; }
        @keyframes fadeOut { 0% {opacity: 1;} 70% {opacity: 1;} 100% {opacity: 0.3;} }
        .grid { display: grid; grid-template-columns: 1fr 2fr; gap: 20px; }
        .card { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        textarea { width: 100%; box-sizing: border-box; padding: 10px; border: 1px solid #ddd; border-radius: 5px; resize: vertical; font-family: monospace; margin-top: 10px;}
        .btn { display: inline-block; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; font-weight: bold; text-decoration: none; text-align: center; }
        .btn-primary { background: #3498db; color: white; width: 100%; margin-top: 10px; }
        .btn-outline-danger { background: transparent; border: 1px solid #e74c3c; color: #e74c3c; cursor:pointer; padding: 5px 10px; font-size: 12px;}
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th { text-align: left; background: #f8f9fa; padding: 12px; border-bottom: 2px solid #eee; font-size: 12px; color: #777; text-transform: uppercase; }
        td { padding: 12px; border-bottom: 1px solid #eee; font-size: 14px; }
        .usn-badge { font-family: monospace; font-weight: bold; color: #2c3e50; background: #e3f2fd; padding: 3px 8px; border-radius: 4px; border: 1px solid #bbdefb; }
        .action-bar { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid #eee; margin-bottom: 10px;}
    </style>
</head>
<body>

<div class="container">
    <header>
        <h1>MariaDB Lab Dashboard</h1>
        <div style="font-size: 13px;">
            <strong>IP:</strong> <?php echo $_SERVER['SERVER_ADDR'] ?? '127.0.0.1'; ?>
        </div>
    </header>

    <?php if ($status_msg): ?>
        <div class="status"><?php echo $status_msg; ?></div>
    <?php endif; ?>

    <div class="grid">
        <div class="card">
            <h2 style="font-size: 16px; margin:0;">Create User Accounts</h2>
            <form action="" method="post">
                <textarea name="usn_list" rows="12" placeholder="Paste USNs here..."></textarea>
                <button type="submit" name="bulk_text_import" class="btn btn-primary">Create Accounts</button>
            </form>
        </div>

        <div class="card">
            <form action="" method="post">
                <div class="action-bar">
                    <span style="font-weight:bold; font-size: 15px;">Active Student Databases</span>
                    <button type="submit" name="bulk_delete" onclick="return confirm('Delete selected student data?')" class="btn btn-outline-danger">Delete Selected</button>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th width="30"><input type="checkbox" onclick="toggleChecks(this)"></th>
                            <th>USN / Database</th>
                            <th style="text-align:right;">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($users_result->num_rows > 0): ?>
                            <?php while($row = $users_result->fetch_assoc()): ?>
                            <tr>
                                <td><input type="checkbox" name="selected_users[]" value="<?php echo $row['User'].'|'.$row['Host']; ?>" class="chk"></td>
                                <td>
                                    <span class="usn-badge"><?php echo $row['User']; ?></span>
                                    <small style="color:#999; margin-left:5px;">&rarr; <?php echo $row['User'].'db'; ?></small>
                                </td>
                                <td style="text-align:right;">
                                    <a href="?delete_user=<?php echo $row['User']; ?>&host=<?php echo $row['Host']; ?>" 
                                       onclick="return confirm('Drop user and database?')" 
                                       style="color:#e74c3c; font-size:12px; text-decoration:none;">Remove</a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="3" style="text-align:center; padding:40px; color:#ccc;">No active student databases.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </form>
        </div>
    </div>
</div>

<script>
    function toggleChecks(source) {
        var checkboxes = document.querySelectorAll('.chk');
        for(var i=0; i<checkboxes.length; i++) { checkboxes[i].checked = source.checked; }
    }
</script>

</body>
</html>
