<?php
include 'koneksi.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $package_id = $_POST['package_id'];
    $package_name = $_POST['package_name'];
    $description = $_POST['description'];
    $price = $_POST['price'];
    
    $duration = $_POST['durationValue'] . " " . $_POST['durationUnit'];

    // Validasi field tidak boleh kosong
    if (empty($package_id) || empty($package_name) || empty($description) || empty($price) || empty($duration)) {
        die("Semua field harus diisi!");
    }

    // Validasi nama hanya huruf dan spasi
    if (!preg_match('/^[A-Za-z\s]+$/', $package_name)) {
        die("Nama paket tidak boleh ada karakter khusus.");
    }

    // Validasi harga harus angka maksimal 6 digit
    if (!preg_match('/^\d{1,6}$/', $price)) {
        die("Harga harus angka");
    }

    // (Opsional) Validasi durasi value-nya angka dan maksimal 2 digit
    if (!preg_match('/^\d{1,3}$/', $_POST['durationValue'])) {
        die("Durasi harus angka");
    }
    $check_sql = "SELECT package_id FROM membership_packages WHERE package_id = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("i", $package_id);
    $check_stmt->execute();
    $check_stmt->store_result();

    if ($check_stmt->num_rows > 0) {
        die("Error: ID Paket sudah digunakan.");
    }
    $check_stmt->close();

    $sql = "INSERT INTO membership_packages (package_id, package_name, description, price, duration) 
            VALUES (?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);

    if ($stmt === false) {
        die("Error statement: " . $conn->error);
    }

    $stmt->bind_param("issis", $package_id, $package_name, $description, $price, $duration);

    if ($stmt->execute()) {
        header("Location: ../Paket/p_membership.php?status=sukses");
        exit();
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
} else {
    header("Location: ../Paket/p_membership.php");
    exit();
}

$conn->close();
?>
