<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: products.php');
    exit;
}

$userId = $_SESSION['user_id'];

$stmt = $pdo->prepare("SELECT id FROM companies WHERE user_id = ? LIMIT 1");
$stmt->execute([$userId]);
$company = $stmt->fetch();

if (!$company) {
    header('Location: settings.php');
    exit;
}

$companyId = $company['id'];

$id = $_POST['id'] ?? '';
$type = $_POST['type'] ?? 'product';
$name = trim($_POST['name'] ?? '');
$description = trim($_POST['description'] ?? '');
$sku = trim($_POST['sku'] ?? '');
$price = floatval($_POST['price'] ?? 0);

if (empty($name) || $price <= 0) {
    $_SESSION['error'] = 'Name and valid price are required.';
    header('Location: products.php');
    exit;
}

if ($id) {
    $stmt = $pdo->prepare("UPDATE products SET type=?, name=?, description=?, sku=?, price=? WHERE id=? AND company_id=?");
    $stmt->execute([$type, $name, $description, $sku, $price, $id, $companyId]);
    header('Location: products.php?msg=updated');
} else {
    $stmt = $pdo->prepare("INSERT INTO products (company_id, type, name, description, sku, price) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$companyId, $type, $name, $description, $sku, $price]);
    header('Location: products.php?msg=added');
}
?>