list, add, and edit providers essential functions working

This commit is contained in:
matt committed 2026-10-21 02:52:36 -07:00
1 parent b2a4307eae
commit 269366b7b6
4 files changed
+200 -69

No files matched your search

+11 -12
View File
@@ -46,15 +46,12 @@ if ($rateOptionsSetting && isset($rateOptionsSetting['value'])) {
}
// Update form handling to process selected rates
$selectedRates = $_POST['rates'] ?? [];
$selectedRateKeys = $_POST['rate_selected'] ?? [];
$ratesArray = [];
foreach ($selectedRates as $item) {
$parts = explode(':', $item, 2);
if (count($parts) == 2) {
$ratesArray[] = [$parts[0] => $parts[1]];
foreach ($selectedRateKeys as $key) {
$value = $_POST['rate_value'][$key] ?? '0';
$ratesArray[] = [$key => $value];
}
}
$created = null;
$errors = [];
@@ -126,14 +123,17 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
<label>Photo URL:<br><input type="text" name="photo" value="<?=htmlspecialchars($_POST['photo'] ?? '')?>"></label>
<?php if (!empty($rateOptions)) : ?>
<label>Rate Options:<br>
<?php foreach ($rateOptions as $option) :
<?php
foreach ($rateOptions as $option) :
// echo $option;
$key = $option;
$value = 0;
?>
<input type="checkbox" name="rates[]" value="<?=htmlspecialchars($key . ':' . $value)?>"
<?php if (in_array($key . ':' . $value, $selectedRates)) echo 'checked'; ?>>
<?=htmlspecialchars($key)?>: <?=htmlspecialchars($value)?> <br>
<input type="checkbox" name="rate_selected[]" value="<?=htmlspecialchars($key)?>"
<?php if (in_array($key, $selectedRateKeys)) echo 'checked'; ?>>
<?=htmlspecialchars($key)?>:
<input type="number" name="rate_value[<?=htmlspecialchars($key)?>]" value="<?=htmlspecialchars($ratesArray[$key] ?? $value)?>" style="width:60px;">
<br>
<?php endforeach; ?>
</label>
<?php endif; ?>
@@ -144,4 +144,3 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
</body>
</html>
+2 -2
View File
@@ -2,7 +2,7 @@
<?php
// config.php
// Base URL for the API
# define('BASE_API_URL', 'http://172.25.1.105:5000');
define('BASE_API_URL', 'http://127.0.0.1:5000');
define('BASE_API_URL', 'http://172.25.1.105:5000');
#define('BASE_API_URL', 'http://127.0.0.1:5000');
?>
+152 -52
View File
@@ -1,72 +1,140 @@
<?php
// Correct array syntax and fix PHP errors in edit_provider.php
// edit_provider.php
// This page allows editing a provider's details.
// It expects a provider id passed via the query string: ?id=123
// Edit an existing fitness provider.
// Handles rate options similar to add_provider.php.
// file settings
require_once __DIR__ . '/config.php';
$provider_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$provider_id = (int)($_GET['id'] ?? 0);
if ($provider_id <= 0) {
echo '<h1>Error</h1>' .
'<p>Provider ID is missing or invalid.</p>';
echo '<h1>Error</h1><p>Provider ID is missing or invalid.</p>';
exit;
}
// API base URL
// ------------------------------------------------------------------
// Helper: Call the API (GET/PUT) – returns decoded JSON or null
function callApi(string $method, string $path, $body = null)
{
$url = BASE_API_URL . $path;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
return null;
}
return json_decode($response, true);
}
// ------------------------------------------------------------------
// Handle form submission
// 1️⃣ Get provider details
$provider = callApi('GET', '/providers?id=' . $provider_id);
if (!$provider) {
echo '<h1>Error</h1><p>Could not load provider details.</p>';
exit;
}
if (is_array($provider) && count($provider) > 0 && isset($provider[0])) {
$provider = $provider[0];
}
// 2️⃣ Get rate‑option list (comma‑separated string → array)
$rateSetting = callApi('GET', '/settings/rate_options');
$rateOptions = [];
if ($rateSetting && isset($rateSetting['value'])) {
$rateOptions = array_map('trim', explode(',', $rateSetting['value']));
}
// 3️⃣ Decode the API’s rate string (JSON → array of arrays)
$ratesData = $provider['rates'] ?? '[]';
$decoded = [];
if (is_string($ratesData)) {
$decoded = json_decode($ratesData, true);
if (json_last_error() !== JSON_ERROR_NONE) {
$decoded = []; // bad JSON – treat as empty
}
} elseif (is_array($ratesData)) {
$decoded = $ratesData; // already an array – legacy path
}
// 4️⃣ Build two helper arrays
$selectedRateKeys = []; // lowercase keys of selected rates
$ratesAssoc = []; // key → value
foreach ($decoded as $entry) {
if (!is_array($entry)) continue;
foreach ($entry as $k => $v) {
$kTrim = strtolower(trim($k));
$selectedRateKeys[] = $kTrim;
$ratesAssoc[$kTrim] = $v;
}
}
// 5️⃣ Find orphan rates (present in $decoded but not in $rateOptions)
$orphanRates = [];
$orphanKeys = [];
foreach ($decoded as $entry) {
if (!is_array($entry)) continue;
foreach ($entry as $k => $v) {
$kTrim = strtolower(trim($k));
if (!in_array($kTrim, array_map('strtolower', $rateOptions))) {
$orphanRates[$kTrim] = $v;
$orphanKeys[] = $kTrim;
}
}
}
// ------------------------------------------------------------------
// 6️⃣ Handle form POST
// --- Handle form POST -------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Collect submitted data
// Base payload
$payload = [
'name' => $_POST['name'] ?? '',
'age' => (int)($_POST['age'] ?? 0),
'photo' => $_POST['photo'] ?? '',
'phone' => $_POST['phone'] ?? '',
'rates' => json_decode($_POST['rates'] ?? 'null', true) ?? [],
'private' => isset($_POST['private']) && $_POST['private'] === 'on',
// Convert checkbox to boolean
'private' => isset($_POST['private']),
];
// Send PUT request to API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_base . '/providers/' . $provider_id);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// ------------------------------------------------------------------
// Rebuild the rates array from the form.
$finalRates = [];
if ($httpCode >= 400) {
$error = json_decode($response, true)['error'] ?? 'Update failed';
echo '<h1>Error</h1><p>' . htmlspecialchars($error) . '</p>';
} else {
// Success: redirect back to provider list
// 1️⃣ Add the selected valid rate options (value may be changed by the user)
$selectedRateKeysRaw = $_POST['rate_selected'] ?? [];
foreach ($selectedRateKeysRaw as $opt) { // $opt is the original rate name
$newVal = $_POST['rate_value'][$opt] ?? '0'; // the updated value
$finalRates[] = [$opt => $newVal];
}
// 2️⃣ Add orphan rates that the user chose **not** to delete
$orphanDeleteSet = array_flip(array_map('strtolower', $_POST['orphan_delete'] ?? []));
foreach ($orphanRates as $key => $value) { // $key is already lower‑cased
if (!isset($orphanDeleteSet[strtolower($key)])) {
$finalRates[] = [$key => $value];
}
}
// 3️⃣ Encode the new array as JSON
//$payload['rates'] = !empty($finalRates) ? json_encode($finalRates) : null;
$payload['rates'] = !empty($finalRates) ? $finalRates : null;
// ------------------------------------------------------------------
// Submit the updated provider
$result = callApi('PUT', '/providers/' . $provider_id, $payload);
if ($result) {
header('Location: list_providers.php');
exit;
}
}
// Fetch current provider details for the form (GET request)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_base . '/providers?id=' . $provider_id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
echo '<h1>Error</h1><p>Could not load provider details.</p>';
exit;
}
$provider = json_decode($response, true);
// API may return array for GET by id
if (is_array($provider) && count($provider) > 0 && isset($provider[0])) {
$provider = $provider[0];
echo '<h1>Error</h1><p>Failed to update provider.</p>';
}
?>
@@ -89,12 +157,44 @@ if (is_array($provider) && count($provider) > 0 && isset($provider[0])) {
<div class="card">
<h1>Edit Provider</h1>
<form method="post" id="editForm">
<label>Name: <input type="text" name="name" id="name" required value="<?php echo htmlspecialchars($provider['name'] ?? ''); ?>"></label>
<label>Age: <input type="number" name="age" id="age" required value="<?php echo htmlspecialchars($provider['age'] ?? ''); ?>"></label>
<label>Photo URL: <input type="text" name="photo" id="photo" value="<?php echo htmlspecialchars($provider['photo'] ?? ''); ?>"></label>
<label>Phone: <input type="text" name="phone" id="phone" required value="<?php echo htmlspecialchars($provider['phone'] ?? ''); ?>"></label>
<label>Rates (JSON):<textarea name="rates" id="rates" rows="4"><?php echo htmlspecialchars(json_encode($provider['rates'] ?? [], JSON_PRETTY_PRINT)); ?></textarea></label>
<label>Private: <input type="checkbox" name="private" id="private" <?php echo (!empty($provider['private'])) ? 'checked' : ''; ?>></label>
<!-- Basic fields -->
<label>Name: <input type="text" name="name" required value="<?php echo htmlspecialchars($provider['name'] ?? ''); ?>"></label>
<label>Age: <input type="number" name="age" required value="<?php echo htmlspecialchars($provider['age'] ?? ''); ?>"></label>
<label>Photo URL: <input type="text" name="photo" value="<?php echo htmlspecialchars($provider['photo'] ?? ''); ?>"></label>
<label>Phone: <input type="text" name="phone" required value="<?php echo htmlspecialchars($provider['phone'] ?? ''); ?>"></label>
<!-- Rate options -->
<?php if (!empty($rateOptions)) : ?>
<label>Rate Options:<br>
<?php foreach ($rateOptions as $opt) :
$key = strtolower(trim($opt));
$value = $ratesAssoc[$key] ?? 0;
?>
<input type="checkbox" name="rate_selected[]" value="<?php echo htmlspecialchars($opt); ?>"
<?php if (in_array($key, $selectedRateKeys)) echo 'checked'; ?> >
<?php echo htmlspecialchars($opt); ?>:
<input type="number" name="rate_value[<?php echo htmlspecialchars($opt); ?>]" value="<?php echo htmlspecialchars($value); ?>" style="width:60px;">
<br>
<?php endforeach; ?>
</label>
<?php endif; ?>
<!-- Orphan rates – show value and a Delete checkbox -->
<?php if (!empty($orphanRates)) : ?>
<label>Orphan Rates:<br>
<?php foreach ($orphanRates as $key => $value) : ?>
<?php echo htmlspecialchars($key); ?>:
<input type="number" value="<?php echo htmlspecialchars($value); ?>" style="width:60px;" disabled>
<input type="checkbox" name="orphan_delete[]" value="<?php echo htmlspecialchars($key); ?>" style="margin-left:10px;"> Delete
<br>
<?php endforeach; ?>
</label>
<?php endif; ?>
<!-- Private flag -->
<label><input type="checkbox" name="private" <?php echo (!empty($provider['private'])) ? 'checked' : ''; ?>> Private</label><br>
<!-- Buttons -->
<button type="submit">Save</button>
<button type="button" onclick="window.location.href='list_providers.php'">Cancel</button>
</form>
+35 -3
View File
@@ -34,6 +34,27 @@ function callApi(string $method, string $path, $body = null)
$providers = callApi('GET', '/providers');
$providers = $providers ?? [];
// Normalize rates for display
foreach ($providers as &$p) {
$rates = $p['rates'] ?? '';
if (is_string($rates)) {
$decoded = json_decode($rates, true);
if (json_last_error() !== JSON_ERROR_NONE) {
// try stripping slashes
$unescaped = stripslashes($rates);
$decoded = json_decode($unescaped, true);
}
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
$p['rates'] = $decoded;
} else {
// leave as is
$p['rates'] = $rates;
}
} elseif (is_array($rates)) {
$p['rates'] = $rates;
}
}
unset($p);
// -----------------------------------------------------------------------
?>
<!DOCTYPE html>
@@ -77,6 +98,19 @@ $providers = $providers ?? [];
const providers = <?php echo json_encode($providers); ?>;
let currentSort = { field: null, asc: true };
// Helper to format rates into readable lines
function formatRates(rates) {
if (!rates) return '';
if (Array.isArray(rates)) {
return rates.map(r => {
const key = Object.keys(r)[0];
const val = r[key];
return `${key}: ${val}`;
}).join('<br>');
}
return rates;
}
function renderTable(data) {
const tbody = document.querySelector('#providers-table tbody');
tbody.innerHTML = '';
@@ -88,7 +122,7 @@ function renderTable(data) {
<td>${p.phone || ''}</td>
<td>${p.age || ''}</td>
<td>${p.photo ? `<img src="${p.photo}" alt="Photo">` : ''}</td>
<td>${p.rates}</td>
<td>${formatRates(p.rates)}</td>
<td>${p.private ? 'Yes' : 'No'}</td>
<td><a href="edit_provider.php?id=${p.id}">Edit</a></td>
`;
@@ -143,5 +177,3 @@ document.getElementById('search').addEventListener('input', e => {
</script>
</body>
</html>