<?php
require_once __DIR__ . '/config.php';
require_auth();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(['error' => 'Method not allowed'], 405);
}

$db = get_db();
$input = json_input();

$costingId = (int)($input['costing_id'] ?? 0);
$newStdPrice = $input['new_std_price'] ?? null;
$overrideGroupPrice = !empty($input['override_group_price']);
$newGroupPrice = $input['new_group_price'] ?? null;
$note = trim($input['note'] ?? '');

if (!$costingId || $newStdPrice === null) {
    respond(['error' => 'costing_id and new_std_price are required'], 422);
}

// Standard business rule from the mockups: Group Price auto-calculates
// from Standard Price unless the user explicitly overrides it.
$groupPrice = $overrideGroupPrice && $newGroupPrice !== null
    ? (float)$newGroupPrice
    : round((float)$newStdPrice * 0.9635, 2); // approximates the ~3.65% discount seen in sample data

$stmt = $db->prepare('UPDATE costings SET std_price = ?, group_price = ? WHERE id = ?');
$stmt->execute([$newStdPrice, $groupPrice, $costingId]);

respond([
    'ok' => true,
    'costing_id' => $costingId,
    'std_price' => (float)$newStdPrice,
    'group_price' => $groupPrice,
    'note' => $note,
]);
