<?php
/**
 * controllers/newProductSubmit.php
 *
 * POST handler: inserts a new product into fertiliser_specifications.
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../lib/auth.php';
require_once __DIR__ . '/../lib/csrf.php';

requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: /dashboard/client-settings/product-list.php');
    exit;
}

if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
    $_SESSION['flash_error'] = 'Invalid CSRF token. Please try again.';
    header('Location: /dashboard/client-settings/product-list.php');
    exit;
}

$name     = trim($_POST['name']     ?? '');
$chemical = trim($_POST['chemical'] ?? '');

if ($name === '') {
    $_SESSION['flash_error'] = 'Product name is required.';
    header('Location: /dashboard/client-settings/product-list.php');
    exit;
}

$pdo    = getDBConnection();
$userId = getCurrentUserId();

$nutrients    = ['N', 'P', 'K', 'Na', 'Ca', 'Mg', 'B', 'Zn', 'Cu', 'Mn', 'Fe', 'Co', 'Mo'];
$colList      = 'modx_user_id, name, chemical, ' . implode(', ', array_map(fn($c) => "`$c`", $nutrients));
$placeholders = implode(', ', array_fill(0, count($nutrients) + 3, '?'));

$values = [$userId, $name, $chemical];
foreach ($nutrients as $col) {
    $val = trim((string) ($_POST[$col] ?? '0'));
    $values[] = is_numeric($val) ? $val : '0';
}

try {
    $stmt = $pdo->prepare("INSERT INTO fertiliser_specifications ($colList) VALUES ($placeholders)");
    $stmt->execute($values);
    $_SESSION['flash_success'] = 'Product "' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '" added successfully.';
} catch (\PDOException $e) {
    $_SESSION['flash_error'] = 'Failed to add product. Please try again.';
}

header('Location: /dashboard/client-settings/product-list.php');
exit;
