<?php
include '../auth.php';
include '../../koneksi.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $user_id = $_SESSION['user_id'];
    $nama_konsumen = $_POST['namakonsumen'];
    $ulasan_konsumen = $_POST['ulasan'];

    // Cek apakah user sudah punya testimoni
    $sql = "SELECT id_testimoni FROM testimoni WHERE id_user = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $testimoni = $result->fetch_assoc();

    if (!$testimoni) {
        // Jika belum ada testimoni, buat satu dulu
        $sql_insert = "INSERT INTO testimoni (id_user) VALUES (?)";
        $stmt_insert = $conn->prepare($sql_insert);
        $stmt_insert->bind_param("i", $user_id);
        $stmt_insert->execute();
        $id_testimoni = $stmt_insert->insert_id;
        $stmt_insert->close();
    } else {
        $id_testimoni = $testimoni['id_testimoni'];
    }

    // Simpan satu data detail testimoni
    $sql_detail = "INSERT INTO detail_testimoni (id_testimoni, nama_konsumen, ulasan_konsumen) VALUES (?, ?, ?)";
    $stmt_detail = $conn->prepare($sql_detail);

    if ($stmt_detail) {
        $stmt_detail->bind_param("iss", $id_testimoni, $nama_konsumen, $ulasan_konsumen);
        $stmt_detail->execute();
        $stmt_detail->close();
    }

    $_SESSION['success'] = "Data Testimoni berhasil ditambahkan!";
    header("Location: ../testimoni");
    exit();
}
?>
