<?php

include 'includes/config.php';

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and validate input
    $name = trim($_POST['name']);
    $short_code = trim($_POST['short_code']);
    $description = trim($_POST['description']);
    $isSubTaxonomy = isset($_POST['isSubTaxonomy']) ? 1 : 0;
    $parent_id = $isSubTaxonomy ? trim($_POST['parent_id']) : null;

    // Fixed values
    $business_id = 3;
    $category_type = 'product';

    // Check if parent_id is provided if 'isSubTaxonomy' is checked
    if ($isSubTaxonomy && empty($parent_id)) {
        echo "<script>alert('Parent category is required when adding as a sub taxonomy.');</script>";
        echo "<script>window.location.href='your_form_page.php'</script>";
        exit;
    }

    // Prepare SQL statement
    $sql = "INSERT INTO categories (name, business_id, short_code, parent_id, category_type, description)
            VALUES (:name, :business_id, :short_code, :parent_id, :category_type, :description)";

    try {
        $stmt = $conn->prepare($sql);
        $stmt->execute([
            ':name' => $name,
            ':business_id' => $business_id,
            ':short_code' => $short_code,
            ':parent_id' => $parent_id ? $parent_id : 0,  // Default to 0 if not provided
            ':category_type' => $category_type,
            ':description' => $description
        ]);
        echo "<script>alert('Category successfully added!');</script>";
        echo "<script>window.location.href='categories.php'</script>";

    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
} else {
    echo "Invalid request method.";
}
?>
