<?php
$ROOT = dirname(__DIR__, 3);
require_once $ROOT . '/config/config.php';
require_once $ROOT . '/src/lib/session.php';
require_auth();

$pdo = getDbConnection();

$competitor_id = (int)($_POST['competitor_id'] ?? 0);
$origin_port_id = (int)($_POST['origin_port_id'] ?? 0);
$dest_port_id = (int)($_POST['dest_port_id'] ?? 0);
$price = $_POST['price'] !== '' ? (float)$_POST['price'] : null;

// Validation stricte
if ($competitor_id <= 0 || $origin_port_id <= 0 || $dest_port_id <= 0 || $price === null) {
    die("Tous les champs sont obligatoires");
}

// Insertion
$stmt = $pdo->prepare("
    INSERT INTO competitor_prices (competitor_id, origin_port_id, dest_port_id, price)
    VALUES (:competitor_id, :origin_port_id, :dest_port_id, :price)
");
$stmt->execute([
    ':competitor_id' => $competitor_id,
    ':origin_port_id' => $origin_port_id,
    ':dest_port_id' => $dest_port_id,
    ':price' => $price
]);

$_SESSION['success_message'] = "✅ Enregistrement réussi !";

// Retour direct à la page précédente
header("Location: ../competitors.php");
exit;
