<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $text = trim($_POST['input_text']);

    // Pastikan folder uploads ada
    if (!is_dir('uploads')) {
        mkdir('uploads', 0777, true);
    }

    // Simpan teks ke file sementara
    $text_file = 'uploads/input_text.txt';
    file_put_contents($text_file, $text);

    // Nama file hasil
    $output_img = 'wordcloud_' . time() . '.png';

    // Path Python 
    $pythonPath = "C:\\laragon\\bin\\python\\python-3.10\\python.exe";

    // Tentukan perintah Python lengkap
    $cmd = "\"$pythonPath\" generate_wordcloud.py \"$text_file\" \"uploads\\$output_img\"";

    // Jalankan perintah Python dan tangkap output
    $output = shell_exec($cmd . " 2>&1");

    // Cek hasil
    if (file_exists("uploads/$output_img")) {
        // Redirect ke index dengan hasil gambar
        header("Location: index.php?img=$output_img&msg=success");
        exit;
    } else {
        // Jika gagal, tampilkan pesan error dari Python
        echo "<h3 style='color:red;'>❌ Gagal membuat Word Cloud.</h3>";
        echo "<pre>$output</pre>";
    }
}
?>
