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

$pdo = getDbConnection();

$client_id = (int)($_POST['client_id'] ?? 0);
$origin_port_id = (int)($_POST['origin_port_id'] ?? 0);
$dest_port_id = (int)($_POST['dest_port_id'] ?? 0);
$volume = $_POST['volume'] !== '' ? (float)$_POST['volume'] : null;
$unit = trim($_POST['unit'] ?? '');
$price_expected = $_POST['price_expected'] !== '' ? (float)$_POST['price_expected'] : null;

// Validation minimale
if ($client_id <= 0 || $origin_port_id <= 0 || $dest_port_id <= 0 || $volume === null || $unit === '') {
    die("Tous les champs obligatoires doivent être remplis");
}

$stmt = $pdo->prepare("
    INSERT INTO demands (client_id, origin_port_id, dest_port_id, volume, unit, price_expected)
    VALUES (:client_id, :origin_port_id, :dest_port_id, :volume, :unit, :price_expected)
");
$stmt->execute([
    ':client_id' => $client_id,
    ':origin_port_id' => $origin_port_id,
    ':dest_port_id' => $dest_port_id,
    ':volume' => $volume,
    ':unit' => $unit,
    ':price_expected' => $price_expected
]);
$_SESSION['success_message'] = "✅ Enregistrement réussi !";

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