<?php
session_start();
define('ADMIN_PASSWORD', 'admin');

// --- AUTHENTICATION ---
if (isset($_POST['admin_login']) && $_POST['password'] === ADMIN_PASSWORD) {
    $_SESSION['admin_logged_in'] = true;
}
if (isset($_GET['logout'])) { session_destroy(); header("Location: dashboard.php"); exit; }

$db = new PDO('sqlite:' . __DIR__ . '/app_feed.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// --- ADMIN ACTIONS ---
if (isset($_SESSION['admin_logged_in'])) {
    // Toggles access rights and updates settings table safely
    if (isset($_POST['toggle_access'])) {
        $stmt = $db->prepare("INSERT INTO user_settings (user_id, withdrawal_locked, login_locked) VALUES (?, ?, ?) 
                              ON CONFLICT(user_id) DO UPDATE SET withdrawal_locked = excluded.withdrawal_locked, login_locked = excluded.login_locked");
        
        // Execute the update
        $stmt->execute([$_POST['target_uid'], $_POST['w_lock'], $_POST['l_lock']]);
        
        // Redirect with debug message to confirm the action triggered for the specific user
        header("Location: dashboard.php?msg=updated_uid_" . $_POST['target_uid']); 
        exit;
    }
    
    // Cascading delete to keep database clean
    if (isset($_POST['delete_user'])) {
        $db->prepare("DELETE FROM users WHERE id = ?")->execute([$_POST['target_uid']]);
        $db->prepare("DELETE FROM user_registrations WHERE id = ?")->execute([$_POST['target_uid']]);
        $db->prepare("DELETE FROM user_settings WHERE user_id = ?")->execute([$_POST['target_uid']]);
        header("Location: dashboard.php"); exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Access Control Panel</title>
    <style>
        body { font-family: sans-serif; background: #0f172a; color: white; padding: 20px; }
        .card { background: #1e293b; padding: 20px; border-radius: 12px; margin-bottom: 20px; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 12px; border-bottom: 1px solid #334155; }
        button { cursor: pointer; padding: 6px 12px; border-radius: 4px; border: none; background: #6366f1; color: white; }
        .alert { background: #10b981; color: white; padding: 10px; border-radius: 6px; margin-bottom: 20px; text-align: center; }
    </style>
</head>
<body>

<?php if (!isset($_SESSION['admin_logged_in'])): ?>
    <div class="card" style="max-width: 300px; margin: 100px auto;">
        <h2>Admin Login</h2>
        <form method="POST"><input type="password" name="password" required><button type="submit" name="admin_login">Enter</button></form>
    </div>
<?php else: ?>
    <h1>Access Control Panel</h1>
    
    <?php if (isset($_GET['msg'])): ?>
        <div class="alert">Action completed for User ID: <?php echo htmlspecialchars(str_replace('updated_uid_', '', $_GET['msg'])); ?></div>
    <?php endif; ?>

    <div class="card">
        <table>
            <thead><tr><th>User</th><th>Withdrawal Access</th><th>Login Access</th><th>Actions</th></tr></thead>
            <tbody>
                <?php 
                // UNIFIED QUERY: Fetches the name from the 'users' table
                $users = $db->query("
                    SELECT 
                        u.id, 
                        COALESCE(u.name, 'Unknown User') AS username, 
                        s.withdrawal_locked, 
                        s.login_locked 
                    FROM users u 
                    LEFT JOIN user_settings s ON u.id = s.user_id
                    ORDER BY u.name ASC
                ");
                foreach ($users as $u): ?>
                <tr>
                    <form method="POST">
                        <input type="hidden" name="target_uid" value="<?php echo htmlspecialchars($u['id'] ?? ''); ?>">
                        <td>
                            <strong><?php echo htmlspecialchars($u['username'] ?? 'Unknown'); ?></strong>
                            <br>
                            <small style="color:#64748b; cursor: help;" title="<?php echo htmlspecialchars($u['id']); ?>">
                                ID: <?php echo substr(htmlspecialchars($u['id']), 0, 8) . '...'; ?>
                            </small>
                        </td>
                        <td>
                            <select name="w_lock">
                                <option value="0">Active</option>
                                <option value="1" <?php if(isset($u['withdrawal_locked']) && $u['withdrawal_locked'] == 1) echo 'selected';?>>Locked</option>
                            </select>
                        </td>
                        <td>
                            <select name="l_lock">
                                <option value="0">Active</option>
                                <option value="1" <?php if(isset($u['login_locked']) && $u['login_locked'] == 1) echo 'selected';?>>Locked</option>
                            </select>
                        </td>
                        <td>
                            <button type="submit" name="toggle_access">Update Status</button>
                            <button type="submit" name="delete_user" style="background:#ef4444;" onclick="return confirm('Are you sure?')">Delete</button>
                        </td>
                    </form>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

</body>
</html>