Files
Spacetraders/buy-ships.php
2026-02-11 22:53:42 -06:00

266 lines
11 KiB
PHP

<?php
/**
* Spacetraders ship purchasing page.
*
* @package SpacetradersAPI
* @author Keith Solomon <keith@keithsolomon.net>
* @license MIT License
* @version GIT: <git_id>
* @link https://git.keithsolomon.net/keith/Spacetraders
*/
require_once __DIR__ . '/lib/spacetraders-api.php';
require_once __DIR__ . '/lib/spacetraders-storage.php';
$config = require __DIR__ . '/lib/project-config.php';
$storage = new SpacetradersStorage( $config['db_path'] );
$token = $storage->getAgentToken();
$statusMessage = '';
$errorMessage = '';
$ships = array();
$shipyards = array();
$agent = array();
$currentSystemSymbol = '';
$waypointShipMap = array();
if (! is_string( $token ) || trim( $token ) === '' ) {
$envToken = getenv( 'SPACETRADERS_TOKEN' );
if (is_string( $envToken ) && trim( $envToken ) !== '' ) {
$token = trim( $envToken );
$storage->setAgentToken( $token );
}
}
if (! is_string( $token ) || trim( $token ) === '' ) {
$tokenError = 'No token found. Set one in config.php or SPACETRADERS_TOKEN.';
}
if (! isset( $tokenError ) ) {
$client = new SpacetradersApi(
trim( $token ),
$config['api_base_url'],
(int) $config['api_timeout'],
$storage,
(int) $config['cache_ttl']
);
}
try {
if (! isset( $tokenError ) ) {
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset( $_POST['ship_type'] ) && isset( $_POST['waypoint_symbol'] )) {
$shipType = trim( (string) $_POST['ship_type'] );
$waypointSymbol = trim( (string) $_POST['waypoint_symbol'] );
if ($shipType !== '' && $waypointSymbol !== '' ) {
$purchaseResponse = $client->purchaseShip( $shipType, $waypointSymbol );
$shipSymbol = (string) ( $purchaseResponse['data']['ship']['symbol'] ?? '' );
$storage->clearAllCache();
$statusMessage = 'Purchased ' . $shipType . ( $shipSymbol !== '' ? ' (' . $shipSymbol . ')' : '' ) . '.';
}
}
$agentResponse = $client->getMyAgent();
$shipsResponse = $client->listMyShips();
$agent = $agentResponse['data'] ?? $agentResponse;
$ships = $shipsResponse['data'] ?? $shipsResponse;
foreach ( $ships as $ship ) {
$shipSymbol = (string) ( $ship['symbol'] ?? '' );
$shipStatus = (string) ( $ship['nav']['status'] ?? '' );
$waypointSymbol = (string) ( $ship['nav']['waypointSymbol'] ?? '' );
if ($shipSymbol === '' || $waypointSymbol === '' || $shipStatus === 'IN_TRANSIT' ) {
continue;
}
if (! isset( $waypointShipMap[ $waypointSymbol ] ) ) {
$waypointShipMap[ $waypointSymbol ] = array();
}
$waypointShipMap[ $waypointSymbol ][] = $shipSymbol;
}
if (isset( $ships[0]['nav']['systemSymbol'] ) && is_string( $ships[0]['nav']['systemSymbol'] ) ) {
$currentSystemSymbol = $ships[0]['nav']['systemSymbol'];
}
if ($currentSystemSymbol === '' && isset( $agent['headquarters'] ) && is_string( $agent['headquarters'] ) ) {
$hqParts = explode( '-', $agent['headquarters'] );
if (count( $hqParts ) >= 2 ) {
$currentSystemSymbol = $hqParts[0] . '-' . $hqParts[1];
}
}
if ($currentSystemSymbol !== '' ) {
$page = 1;
$total = 0;
$waypoints = array();
do {
$waypointsResponse = $client->listWaypoints(
$currentSystemSymbol,
array(
'page' => $page,
'limit' => 20,
)
);
$pageData = $waypointsResponse['data'] ?? array();
if (! is_array( $pageData ) || empty( $pageData ) ) {
break;
}
$waypoints = array_merge( $waypoints, $pageData );
$total = (int) ( $waypointsResponse['meta']['total'] ?? count( $waypoints ) );
$page++;
} while (count( $waypoints ) < $total);
foreach ( $waypoints as $waypoint ) {
$traits = $waypoint['traits'] ?? array();
$hasShipyard = false;
foreach ( $traits as $trait ) {
if ((string) ( $trait['symbol'] ?? '' ) === 'SHIPYARD' ) {
$hasShipyard = true;
break;
}
}
if (! $hasShipyard ) {
continue;
}
$waypointSymbol = (string) ( $waypoint['symbol'] ?? '' );
$record = array(
'waypoint' => $waypoint,
'shipTypes' => array(),
'prices' => array(),
'shipSymbols' => (array) ( $waypointShipMap[ $waypointSymbol ] ?? array() ),
'error' => '',
);
try {
$shipyardResponse = $client->getWaypointShipyard( $currentSystemSymbol, $waypointSymbol );
$shipyardData = $shipyardResponse['data'] ?? array();
$record['shipTypes'] = (array) ( $shipyardData['shipTypes'] ?? array() );
$shipsForSale = (array) ( $shipyardData['ships'] ?? array() );
foreach ( $shipsForSale as $shipForSale ) {
$shipType = (string) ( $shipForSale['type'] ?? '' );
$price = (int) ( $shipForSale['purchasePrice'] ?? 0 );
if ($shipType !== '' && $price > 0 ) {
$record['prices'][ $shipType ] = $price;
}
}
$transactions = (array) ( $shipyardData['transactions'] ?? array() );
foreach ( $transactions as $transaction ) {
$shipType = (string) ( $transaction['shipType'] ?? '' );
$price = (int) ( $transaction['price'] ?? 0 );
if ($shipType !== '' && $price > 0 && ! isset( $record['prices'][ $shipType ] ) ) {
$record['prices'][ $shipType ] = $price;
}
}
} catch (SpacetradersApiException $e) {
$record['error'] = $e->getMessage();
}
$shipyards[] = $record;
}
}
}
} catch (SpacetradersApiException $e) {
$errorMessage = $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spacetraders - Buy Ships</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="container mx-auto px-4 py-8 bg-stone-800 text-gray-200">
<?php require __DIR__ . '/main-menu.php'; ?>
<h1 class="text-3xl font-bold mb-6 underline decoration-gray-300 w-full"><a href="buy-ships.php">Spacetraders - Buy Ships</a></h1>
<?php if (isset( $tokenError ) ) : ?>
<div class="mb-6 border border-red-500 p-4 rounded text-red-300">
<?php echo htmlspecialchars( $tokenError ); ?>
</div>
</body>
</html>
<?php exit; ?>
<?php endif; ?>
<?php if ($statusMessage !== '' ) : ?>
<div class="mb-6 border border-green-500 p-4 rounded text-green-300">
<?php echo htmlspecialchars( $statusMessage ); ?>
</div>
<?php endif; ?>
<?php if ($errorMessage !== '' ) : ?>
<div class="mb-6 border border-red-500 p-4 rounded text-red-300">
<?php echo htmlspecialchars( $errorMessage ); ?>
</div>
<?php endif; ?>
<?php if (empty( $shipyards ) ) : ?>
<div class="border border-gray-600 p-4 rounded">
No shipyards were found in your current system.
</div>
<?php endif; ?>
<?php foreach ( $shipyards as $shipyard ) : ?>
<div class="mb-6 border border-gray-600 p-4 rounded">
<h2 class="text-2xl font-bold mb-3">
Shipyard: <?php echo htmlspecialchars( (string) ( $shipyard['waypoint']['symbol'] ?? '' ) ); ?>
</h2>
<p class="text-sm text-gray-300 mb-3">
Ships Here:
<?php
$shipSymbols = (array) ( $shipyard['shipSymbols'] ?? array() );
echo htmlspecialchars( ! empty( $shipSymbols ) ? formatString( implode( ', ', $shipSymbols ) ) : 'None' );
?>
</p>
<?php if ((string) $shipyard['error'] !== '' ) : ?>
<p class="text-red-300"><?php echo htmlspecialchars( (string) $shipyard['error'] ); ?></p>
<?php else : ?>
<table class="table-auto border-collapse border border-gray-300 w-full">
<tr>
<th class="border border-gray-300 px-4 py-2">Ship Type</th>
<th class="border border-gray-300 px-4 py-2">Known Price</th>
<th class="border border-gray-300 px-4 py-2">Action</th>
</tr>
<?php foreach ( (array) $shipyard['shipTypes'] as $shipTypeRecord ) : ?>
<?php $shipType = (string) ( $shipTypeRecord['type'] ?? '' ); ?>
<?php $knownPrice = (int) ( $shipyard['prices'][ $shipType ] ?? 0 ); ?>
<tr>
<td class="border border-gray-300 px-4 py-2"><?php echo htmlspecialchars( formatString( str_replace( 'SHIP_', '', $shipType ) ) ); ?></td>
<td class="border border-gray-300 px-4 py-2">
<?php echo $knownPrice > 0 ? number_format( $knownPrice ) : 'Unknown'; ?>
</td>
<td class="border border-gray-300 px-4 py-2">
<form method="post" class="inline">
<input type="hidden" name="ship_type" value="<?php echo htmlspecialchars( $shipType ); ?>">
<input type="hidden" name="waypoint_symbol" value="<?php echo htmlspecialchars( (string) ( $shipyard['waypoint']['symbol'] ?? '' ) ); ?>">
<button type="submit" class="px-3 py-1 bg-blue-600 rounded hover:bg-blue-500">Buy</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
</div>
<?php endforeach; ?>
</body>
</html>