<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
auth_require_login();
$pdo = crm_pdo();

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); echo json_encode(['ok'=>false,'error'=>'Method not allowed']); exit;
}

gp_require_csrf();

$projectId = (int)($_POST['project_id'] ?? 0);
if ($projectId <= 0) { echo json_encode(['ok'=>false,'error'=>'Invalid project']); exit; }

gp_require_project_edit($pdo, $projectId);

$fields = [
    'length', 'width', 'depth_shallow', 'depth_deep', 'volume_m3',
    'pump_flow_m3h', 'filter_diam_mm', 'skimmer_count',
    'outlet_count', 'main_drain_count', 'vacuum_point_count', 'lighting_count'
];

$data = [];
foreach ($fields as $f) {
    $val = trim((string)($_POST[$f] ?? ''));
    $data[$f] = $val !== '' ? $val : null;
}
$data['notes'] = trim((string)($_POST['notes'] ?? '')) ?: null;

// UPSERT
$cols = array_keys($data);
$setClause = implode(', ', array_map(fn($c) => "$c = :$c", $cols));

$existing = $pdo->prepare("SELECT id FROM pool_calculator_specs WHERE project_id = ?");
$existing->execute([$projectId]);

if ($existing->fetch()) {
    $sql = "UPDATE pool_calculator_specs SET $setClause WHERE project_id = :project_id";
} else {
    $allCols = implode(', ', $cols);
    $allVals = implode(', ', array_map(fn($c) => ":$c", $cols));
    $sql = "INSERT INTO pool_calculator_specs (project_id, $allCols) VALUES (:project_id, $allVals)";
}

$params = [':project_id' => $projectId];
foreach ($data as $k => $v) $params[":$k"] = $v;

$st = $pdo->prepare($sql);
$st->execute($params);

echo json_encode(['ok' => true]);
