<?php
/**
 * ICYLAB OS - Guardar Nuevo Producto
 */
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php'; // 1. Motor de permisos
require_once '../../core/database.php';

require_login();
require_permission('module.products'); // 2. Bloqueo de seguridad

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die('Método no permitido.');
}

$pdo = db();

function product_clean_unit($unit)
{
    $allowed = array('unidad', 'mL', 'L', 'g', 'kg', 'pack', 'caja', 'servicio');
    $unit = trim((string)$unit);
    return in_array($unit, $allowed, true) ? $unit : 'unidad';
}

// ¡Corregido: Capturamos la categoría!
$category_id = isset($_POST['category_id']) && $_POST['category_id'] !== '' ? (int)$_POST['category_id'] : null;
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$sku = isset($_POST['sku']) ? trim($_POST['sku']) : '';
$price = isset($_POST['price']) ? (float)$_POST['price'] : 0.0;
$stock = isset($_POST['stock']) ? (float)$_POST['stock'] : 0.0;
$unit = product_clean_unit($_POST['unit'] ?? 'unidad');
$is_active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;
$description = isset($_POST['description']) ? trim($_POST['description']) : '';
$cost = isset($_POST['cost']) ? (float)$_POST['cost'] : 0.0;

$errors = array();

if ($name === '') {
    $errors['name'] = 'El nombre del producto es obligatorio.';
}

if ($price < 0) {
    $errors['price'] = 'El precio no puede ser negativo.';
}

if (!empty($errors)) {
    $_SESSION['form_errors'] = $errors;
    $_SESSION['form_old'] = $_POST;
    header('Location: /modules/products/product_create.php'); // O redirigir al index dependiendo de tu flujo
    exit;
}

try {
    // ¡Corregido: Insertamos la category_id en la base de datos!
    $stmt = $pdo->prepare("INSERT INTO products (category_id, name, sku, price, cost, stock, unit, is_active, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute(array($category_id, $name, $sku, $price, $cost, $stock, $unit, $is_active, $description));

    header('Location: /modules/products/index.php');
    exit;

} catch (Throwable $e) {
    die("Error crítico al guardar el producto: " . $e->getMessage());
}