<?php
// Set response type to standard JSON format
header('Content-Type: application/json');

// Capture incoming raw JSON request data from fetch channel
$rawInput = file_get_contents('php://input');
$data = json_decode($rawInput, true);

// Fallback error response if payload structure is unreadable
if (!$data || !isset($data['txt']) || trim($data['txt']) === '') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid data payload submitted.']);
    exit();
}

try {
    // Establish a zero-dependency local SQLite file instance
    $db = new PDO('sqlite:app_feed.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Dynamic initial table creation schema interceptor
    $db->exec("CREATE TABLE IF NOT EXISTS application_comments (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        flag TEXT,
        tier TEXT,
        txt TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    // Clean, binded transaction architecture preventing execution exploits
    $stmt = $db->prepare("INSERT INTO application_comments (name, flag, tier, txt) VALUES (:name, :flag, :tier, :txt)");
    
    // Quick sanitization fallbacks for standard variables
    $name = !empty($data['name']) ? strip_tags($data['name']) : 'Anonymous User';
    $flag = !empty($data['flag']) ? strip_tags($data['flag']) : '📱';
    $tier = !empty($data['tier']) ? strip_tags($data['tier']) : 'Bronze Active';
    $txt  = strip_tags($data['txt']);

    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':flag', $flag);
    $stmt->bindParam(':tier', $tier);
    $stmt->bindParam(':txt', $txt);
    
    $stmt->execute();

    echo json_encode(['status' => 'success', 'message' => 'Record successfully committed to feed log.']);

} catch (PDOException $e) {
    // Standard secure execution response wrapper
    echo json_encode(['status' => 'error', 'message' => 'Database operation error sequence encountered.']);
}
?>