<?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 {
    require_once 'db_config.php';
    
    // Create table if not exists (VARCHAR for MySQL compatibility)
    // Drop old broken table if it exists with TEXT PRIMARY KEY
    try {
        $checkStmt = $db->query("SELECT 1 FROM shared_statements LIMIT 1");
    } catch (Exception $checkEx) {
        // Table doesn't exist or is broken, drop and recreate
        try { $db->exec("DROP TABLE IF EXISTS shared_statements"); } catch(Exception $e2) {}
    }
    $db->exec("CREATE TABLE IF NOT EXISTS shared_statements (
        token VARCHAR(64) PRIMARY KEY,
        html_content LONGTEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["error" => "Database error: " . $e->getMessage()]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $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]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to save: ' . $e->getMessage()]);
    }
    exit;
}
?>
