<?php
require_once __DIR__ . '/../../app/includes/auth.php';
require_once __DIR__ . '/../../app/includes/product_helpers.php';
require_auth(); require_role_access('*'); verify_csrf();

[$data, $errors] = validate_product_input($_POST);
if ($errors) {
    flash('error', implode(' ', $errors));
    redirect('/products/create.php');
}
if (duplicate_product_exists($data)) {
    flash('error', 'A product with the same name, brand, and model already exists.');
    redirect('/products/create.php');
}

$stmt = db()->prepare('INSERT INTO products (product_category, product_name, description, brand, model, unit, unit_price, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$stmt->execute([$data['product_category'], $data['product_name'], $data['description'], $data['brand'], $data['model'], $data['unit'], $data['unit_price'], $data['status'], now(), now()]);
log_activity('product_created', 'Created product ' . $data['product_name'] . '.');
flash('success', 'Product added successfully.');
redirect('/products/index.php');
