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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $user_id = $_SESSION['user_id'];
    $nama_keunggulan = $_POST['namakeunggulan'];

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

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

    // Simpan satu data detail  keunggulan
    $sql_detail = "INSERT INTO detail_keunggulan (id_keunggulan, deskripsi_keunggulan) VALUES (?, ?)";
    $stmt_detail = $conn->prepare($sql_detail);

    if ($stmt_detail) {
        $stmt_detail->bind_param("is", $id_keunggulan, $nama_keunggulan);
        $stmt_detail->execute();
        $stmt_detail->close();
    }

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