<?php
// create_subcategory.php

// Include the database connection
require 'db_connection.php'; // Assuming this file sets up the MySQLi connection

// Fetch all categories for the dropdown
$categories_query = "SELECT * FROM categories";
$categories_result = mysqli_query($conn, $categories_query);
$categories = mysqli_fetch_all($categories_result, MYSQLI_ASSOC); // Fetch categories as an associative array

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $category_id = $_POST['category_id'];
    $subcategory_name = $_POST['subcategory_name'];
    
    // Prepare the SQL statement
    $stmt = "INSERT INTO subcategories (category_id, subcategory_name) VALUES ('$category_id', '$subcategory_name')";

    // Execute the statement
    if (mysqli_query($conn, $stmt)) {
        echo "Subcategory created successfully.";
    } else {
        echo "Error: " . mysqli_error($conn); // Display error if any
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Create Subcategory</title>
</head>
<body>
    <form method="POST" action="">
        <select name="category_id" required>
            <option value="">Select Category</option>
            <?php foreach ($categories as $category): ?>
                <option value="<?= htmlspecialchars($category['id']) ?>"><?= htmlspecialchars($category['category_name']) ?></option>
            <?php endforeach; ?>
        </select><br>
        <input type="text" name="subcategory_name" placeholder="Subcategory Name" required><br>
        <button type="submit">Create Subcategory</button>
    </form>
</body>
</html>
