<?php

if (isset($_POST['action'])) {
    if ($_POST['action'] == "add") {
        if (isset($_POST['name'], $_POST['category'], $_POST['description'], $_POST['image'])) {
            $sub_name = $_POST['name'];
            $sub_id_category = $_POST['category'];
            $sub_description = $_POST['description'];
            $sub_image = $_POST['image'];
            $subcategoryManager = new SubCategoryManager($database);
            $categoryManager = new CategoryManager($database);
            $category = $categoryManager->findById($sub_id_category);
            try {
                $subcategoryManager->create($sub_name, $sub_description, $sub_image, $category);
            } catch (Exception $e) {
                $errors[] = $e->getMessage();
            }
            if (count($errors) == 0) {
                $_SESSION['success'] = "La sous-categorie a bien été crée";
            } else {
                $_SESSION['errors'] = $errors;
            }
            header('Location: ?page=admin');
            exit;
        }
    }
}
            } else {
                $_SESSION['success'] = "Categorie créée avec succès";
                header('Location: ?page=category&id=' . $category->getId());
                exit;
            }
        }
    }
    if ($_GET['page'] == 'create_sub_category') {
        $subCategory_name = $subCategory_banner = $subCategory_description = "";
        if (isset($_POST['subCategory_name'], $_POST['subCategory_banner'], $_POST['subCategory_description'], $_POST['subCategory_category'])) {
            $subCategoryManager = new SubCategoryManager($db);
            $categoryManager = new CategoryManager($db);
            try {
                $category = $categoryManager->findById($_POST['subCategory_category']);
            } catch (Exception $e) {
                $errors[] = $e->getMessage();
            }
            $subCategory = $subCategoryManager->create($category, $_POST['subCategory_name'], $_POST['subCategory_description'], $_POST['subCategory_banner']);
            if (is_array($subCategory)) {
                $errors = array_merge($errors, $subCategory);
                $subCategory_name = $_POST['subCategory_name'];
                $subCategory_banner = $_POST['subCategory_banner'];
                $subCategory_description = $_POST['subCategory_description'];
            } else {
                $_SESSION['success'] = "Subcategory has been created";
                header('Location: ?page=sub_category&id=' . $subCategory->getId());
                exit;
            }
        }
    }
}