<?php
require_once 'includes/db.php';
requireLogin();

// Handle Create
if (isset($_POST['create_seed'])) {
    $username = $_POST['username'];
    $label = $_POST['label'];
    $email = $username . '@seed.local';
    $passwordHash = password_hash('password123', PASSWORD_BCRYPT);
    
    $stmt = $pdo->prepare("INSERT INTO users (email, password_hash, username, display_name, link_slug, is_seed, seed_label, seed_owner_admin_id, status) VALUES (?, ?, ?, ?, ?, 1, ?, ?, 'online')");
    $stmt->execute([$email, $passwordHash, $username, $username, $username, $label, $_SESSION['admin_id']]);
    $userId = $pdo->lastInsertId();

    $stmt = $pdo->prepare("INSERT INTO seed_accounts (user_id, label, is_enabled) VALUES (?, ?, 1)");
    $stmt->execute([$userId, $label]);
}

// Handle Send Message
if (isset($_POST['send_message'])) {
    $seedId = $_POST['seed_id'];
    $targetUsername = $_POST['target_username'];
    $message = $_POST['message'];

    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->execute([$targetUsername]);
    $target = $stmt->fetch();

    if ($target) {
        // Logic duplicated from API for simplicity in "PHP ONLY" shared hosting env without shared lib folder setup
        // Ideally should call internal API or share classes
        $receiverId = $target['id'];
        
        // Find/Create conversation
        $stmt = $pdo->prepare("SELECT id FROM conversations WHERE (user_a_id = ? AND user_b_id = ?) OR (user_a_id = ? AND user_b_id = ?)");
        $stmt->execute([$seedId, $receiverId, $receiverId, $seedId]);
        $conv = $stmt->fetch();
        
        if ($conv) {
            $conversationId = $conv['id'];
        } else {
            $stmt = $pdo->prepare("INSERT INTO conversations (user_a_id, user_b_id, created_at, updated_at) VALUES (?, ?, NOW(), NOW())");
            $stmt->execute([min($seedId, $receiverId), max($seedId, $receiverId)]);
            $conversationId = $pdo->lastInsertId();
        }

        $stmt = $pdo->prepare("INSERT INTO messages (conversation_id, sender_id, receiver_id, body_text, sent_by_admin_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())");
        $stmt->execute([$conversationId, $seedId, $receiverId, $message, $_SESSION['admin_id']]);
        
        // Push notification logic omitted in pure PHP admin panel for brevity, or use cURL to localhost API
        // Using cURL to own API is best practice here
        $apiUrl = getenv('BASE_URL') . '/api/admin/seed-users/' . $seedId . '/message';
        // But we need admin token.
        // Simplified: Just insert into DB is enough for MVP core logic, polling picks it up.
    }
}

$stmt = $pdo->query("SELECT u.*, sa.label as seed_label_meta FROM users u JOIN seed_accounts sa ON u.id = sa.user_id");
$seeds = $stmt->fetchAll();

require_once 'includes/header.php';
?>

<h2>Seed Users</h2>

<div class="card mb-4">
    <div class="card-body">
        <h5>Create New Seed User</h5>
        <form method="post" class="row g-3">
            <div class="col-md-4">
                <input type="text" name="username" class="form-control" placeholder="Username" required>
            </div>
            <div class="col-md-4">
                <select name="label" class="form-select">
                    <option value="Bot">Bot</option>
                    <option value="Official">Official</option>
                </select>
            </div>
            <div class="col-md-4">
                <button type="submit" name="create_seed" class="btn btn-primary">Create</button>
            </div>
        </form>
    </div>
</div>

<div class="row">
    <?php foreach($seeds as $seed): ?>
    <div class="col-md-6 mb-3">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title"><?= htmlspecialchars($seed['display_name']) ?> <span class="badge bg-secondary"><?= $seed['seed_label_meta'] ?></span></h5>
                <p class="card-text">@<?= htmlspecialchars($seed['username']) ?></p>
                
                <form method="post">
                    <input type="hidden" name="seed_id" value="<?= $seed['id'] ?>">
                    <div class="input-group mb-3">
                        <input type="text" name="target_username" class="form-control" placeholder="Target Username" required>
                    </div>
                    <div class="input-group mb-3">
                        <input type="text" name="message" class="form-control" placeholder="Message body..." required>
                        <button class="btn btn-outline-secondary" name="send_message">Send</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<?php require_once 'includes/footer.php'; ?>
