<?php
// share_statement.php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit;
}

try {
    $db = new PDO("sqlite:database.sqlite");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Create table if not exists
    $db->exec("CREATE TABLE IF NOT EXISTS shared_statements (
        token TEXT PRIMARY KEY,
        html_content TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["error" => "Database error"]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $html = $input['html'] ?? '';
    if (empty($html)) {
        echo json_encode(['error' => 'No HTML provided']);
        exit;
    }
    
    $token = bin2hex(random_bytes(16));
    
    $stmt = $db->prepare("INSERT INTO shared_statements (token, html_content) VALUES (?, ?)");
    $stmt->execute([$token, $html]);
    
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
    $host = $_SERVER['HTTP_HOST'];
    // Get the base path
    $path = dirname($_SERVER['REQUEST_URI']);
    if ($path === '/' || $path === '\\') $path = '';
    
    $url = $protocol . $host . $path . '/view_statement.php?token=' . $token;
    
    echo json_encode(['success' => true, 'url' => $url]);
    exit;
}
?>
