<?php
require_once '../includes/auth.php';
require_once '../db.php';
header('Content-Type: application/json');

$name     = trim($_POST['name'] ?? '');
$brand    = trim($_POST['brand'] ?? '');
$category = trim($_POST['category'] ?? '');
$unit     = trim($_POST['unit'] ?? '');
$hsn      = trim($_POST['hsn'] ?? '');

if ($name === '') {
    echo json_encode(['status'=>'error','msg'=>'Product name required']);
    exit;
}

// Optional: prevent duplicate names within same company
$chk = $conn->prepare("SELECT id FROM products WHERE name = ? AND company_id = ?");
$chk->bind_param("si", $name, $cid);
$chk->execute();
$chk->store_result();
if ($chk->num_rows > 0) {
    echo json_encode(['status'=>'error','msg'=>'Product already exists']);
    exit;
}

$stmt = $conn->prepare("
    INSERT INTO products (name, brand, category, unit, hsn_code, status, company_id)
    VALUES (?, ?, ?, ?, ?, 1, ?)
");

$stmt->bind_param("sssssi", $name, $brand, $category, $unit, $hsn, $cid);

if ($stmt->execute()) {
    echo json_encode([
        'status' => 'ok',
        'id'     => $stmt->insert_id,
        'name'   => $name
    ]);
} else {
    echo json_encode(['status'=>'error','msg'=>$stmt->error]);
}
