<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../includes/auth.php';
requireLogin();
requirePermission('view_inventory');

require_once __DIR__ . '/../../config/database.php';

$company_id = $_SESSION['company_id'] ?? 0;

/* ===============================
COLLECT FORM DATA
================================ */

$category_id      = $_POST['category_id'] ?? null;
$item_type        = trim($_POST['item_type'] ?? 'PRODUCT');
$product_name     = trim($_POST['product_name'] ?? '');
$brand            = trim($_POST['brand'] ?? '');
$model            = trim($_POST['model'] ?? '');
$sku              = trim($_POST['sku'] ?? '');
$description      = trim($_POST['description'] ?? '');
$cost             = (float)($_POST['cost_price'] ?? 0);
$sell             = (float)($_POST['selling_price'] ?? 0);
$track_inventory  = (int)($_POST['track_inventory'] ?? 0);
$stock_qty        = (int)($_POST['stock_qty'] ?? 0);

/* ===============================
VALIDATION
================================ */

if(!$product_name){
    die("Item name is required.");
}

if(!$category_id){
    die("Category is required.");
}

/* ===============================
INSERT ITEM (STILL USING inventory_products)
================================ */

$stmt = $pdo->prepare("
INSERT INTO inventory_products
(
company_id,
category_id,
item_type,
product_name,
brand,
model,
sku,
description,
cost_price,
selling_price,
track_inventory,
stock_qty,
status
)
VALUES
(?,?,?,?,?,?,?,?,?,?,?,?, 'active')
");

$stmt->execute([
$company_id,
$category_id,
$item_type,
$product_name,
$brand,
$model,
$sku,
$description,
$cost,
$sell,
$track_inventory,
$stock_qty
]);

header("Location: index.php");
exit;