<?php
/**
 * ICYLAB OS - Almacenar categoria desde el formulario completo.
 */
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/permissions.php';

require_login();
require_permission('module.products');

if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
    http_response_code(405);
    header('Allow: POST');
    exit;
}

csrf_require_valid_request();

$name = trim((string)($_POST['name'] ?? ''));
if ($name === '') {
    $_SESSION['form_errors'] = array('name' => 'El nombre de la categoria es obligatorio.');
    $_SESSION['form_old'] = array('name' => $name);
    header('Location: /modules/categories/category_create.php');
    exit;
}

try {
    $stmt = db()->prepare('INSERT INTO product_categories (name) VALUES (?)');
    $stmt->execute(array($name));
    header('Location: /modules/categories/');
    exit;
} catch (Throwable $e) {
    error_log('ICYLAB category_store failed: ' . $e->getMessage());
    $_SESSION['form_errors'] = array('name' => 'No fue posible guardar la categoria. Intenta nuevamente.');
    $_SESSION['form_old'] = array('name' => $name);
    header('Location: /modules/categories/category_create.php');
    exit;
}
