<?php
/**
 * add_s2s_debt.php — Payment Server Endpoint
 * 
 * Inserts passenger wallet credit/debit records (debt/penalty).
 * Authenticated via X-S2S-Api-Key header matching the S2S_SHARED_KEY environment variable.
 */

require_once __DIR__ . '/../../jwtconnect.php';

define('S2S_SHARED_KEY', getenv('S2S_SHARED_KEY'));

$providedKey = $_SERVER['HTTP_X_S2S_API_KEY'] ?? '';

if (empty($providedKey) || $providedKey !== S2S_SHARED_KEY) {
    http_response_code(401);
    printFailure("Unauthorized: Invalid or missing X-S2S-Api-Key.");
    exit;
}

$passengerID = filterRequest("passengerID");
$amount      = filterRequest("amount");

if (empty($passengerID) || !isset($amount)) {
    printFailure("Missing required parameters: passengerID, amount");
    exit;
}

try {
    $con->beginTransaction();

    $sql = "INSERT INTO `passengerWallet` (
        `passenger_id`,
        `balance`
    ) VALUES (
        :passengerID,
        :amount
    );";

    $stmt = $con->prepare($sql);
    $stmt->execute([
        ':passengerID' => $passengerID,
        ':amount' => $amount
    ]);

    if ($stmt->rowCount() > 0) {
        $con->commit();
        printSuccess("Record saved successfully");
    } else {
        $con->rollBack();
        printFailure("Failed to save record");
    }
} catch (Exception $e) {
    if ($con->inTransaction()) {
        $con->rollBack();
    }
    printFailure("An error occurred: " . $e->getMessage());
}
?>
