Files
Fitness/web/html/edit_provider.php
2026-10-28 22:24:12 -07:00

321 lines
12 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
// edit_provider.php
// Edit an existing fitness provider.
// Handles rate options similar to add_provider.php.
require_once __DIR__ . '/../fitness-config.php';
$provider_id = (int)($_GET['id'] ?? 0);
if ($provider_id <= 0) {
echo '<h1>Error</h1><p>Provider ID is missing or invalid.</p>';
exit;
}
// ------------------------------------------------------------------
// 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);
}
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// Helper: upload photos (multipart)
// Returns the JSON response from the API (or null on error)
function uploadPhotosApi(int $provider_id, array $files): ?array
{
$url = BASE_API_URL . "/api/providers/{$provider_id}/photos";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Build multipart array
$multipart = [];
foreach ($files['tmp_name'] as $i => $tmp) {
if ($files['name'][$i] === '') continue;
$multipart[] = [
'name' => 'photos',
'contents' => fopen($tmp, 'r'),
'filename' => $files['name'][$i]
];
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $multipart);
// Let PHP set the correct Content‑Type boundary
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: multipart/form-data']);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($httpCode < 400) ? json_decode($response, true) : null;
}
// 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];
}
// 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']));
}
// 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
}
// 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;
}
}
// 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;
}
}
}
// ------------------------------------------------------------------
// Handle form POST
/*
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Base payload
$payload = [
'name' => $_POST['name'] ?? '',
'age' => (int)($_POST['age'] ?? 0),
'photo' => $_POST['photo'] ?? '',
'phone' => $_POST['phone'] ?? '',
// Convert checkbox to boolean
'private' => isset($_POST['private']),
];
// ------------------------------------------------------------------
// Rebuild the rates array from the form.
$finalRates = [];
// 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];
}
// 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];
}
}
// 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;
}
echo '<h1>Error</h1><p>Failed to update provider.</p>';
}*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
/* -------- 1. Build the base payload -------- */
$payload = [
'name' => $_POST['name'] ?? '',
'age' => (int)($_POST['age'] ?? 0),
'photo' => $_POST['photo'] ?? '',
'phone' => $_POST['phone'] ?? '',
'private' => isset($_POST['private']),
];
/* -------- 2. Re‑build the rates array -------- */
$finalRates = [];
$selectedRateKeysRaw = $_POST['rate_selected'] ?? [];
foreach ($selectedRateKeysRaw as $opt) {
$newVal = $_POST['rate_value'][$opt] ?? '0';
$finalRates[] = [$opt => $newVal];
}
// orphan rates that the user chose *not* to delete
$orphanDeleteSet = array_flip(array_map('strtolower', $_POST['orphan_delete'] ?? []));
foreach ($orphanRates as $key => $value) {
if (!isset($orphanDeleteSet[$key])) {
$finalRates[] = [$key => $value];
}
}
$payload['rates'] = !empty($finalRates) ? $finalRates : null;
/* -------- 3. Call the API to update provider -------- */
$result = callApi('PUT', "/providers/{$provider_id}", $payload);
if (!$result) {
echo '<h1>Error</h1><p>Failed to update provider.</p>';
exit;
}
/* -------- 4. Upload photos if any were chosen -------- */
if (!empty($_FILES['photos']['name'][0])) {
$uploadRes = uploadPhotosApi($provider_id, $_FILES['photos']);
if ($uploadRes && isset($uploadRes['photos'])) {
// Update main photo if the user selected one
$selectedMain = $_POST['main_photo'] ?? null;
if ($selectedMain) {
callApi('PUT', "/api/providers/{$provider_id}/main_photo",
['url' => $selectedMain]);
}
} else {
// Photo upload failed – you may want to show a message
echo '<p style="color:red;">Photo upload failed.</p>';
}
}
/* -------- 5. Set the chosen main photo from the new uploads -------- */
// If a main photo was chosen from the new uploads, send it
if (!empty($_POST['main_photo'])) {
callApi('PUT', "/api/providers/{$provider_id}/main_photo",
['url' => $_POST['main_photo']]);
}
/* -------- 6. Redirect back to the list -------- */
header('Location: list_providers.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Provider</title>
<link rel="stylesheet" href="https://cosmostat.matt-cloud.com/src/styles.css">
<style>
body {font-family: Arial, sans-serif; margin: 20px;}
form {max-width: 600px;}
label {display: block; margin-top: 10px;}
input[type=text], input[type=number], textarea {width: 100%; padding: 8px; box-sizing: border-box;}
input[type=checkbox] {margin-top: 5px;}
button {margin-top: 15px; padding: 10px 15px;}
</style>
</head>
<body>
<div class="card">
<h1>Edit Provider</h1>
<form method="post" id="editForm">
<!-- Basic fields -->
<?php if (!empty($provider['photos'])): ?>
<fieldset>
<legend>Existing Photos</legend>
<div style="display:flex; flex-wrap:wrap;">
<?php foreach ($provider['photos'] as $idx => $url): ?>
<div style="margin:4px; text-align:center;">
<img src="<?= htmlspecialchars($url) ?>" style="max-width:100px; height:auto;">
<br>
<input type="radio" name="main_photo" value="<?= htmlspecialchars($url) ?>"
<?= ($provider['main_photo'] ?? '') === $url ? 'checked' : '' ?>>
<label>Thumbnail</label>
</div>
<?php endforeach; ?>
</div>
</fieldset>
<?php endif; ?>
<fieldset>
<legend>Upload New Photos</legend>
<label>
<input type="file" name="photos[]" multiple accept="image/*">
</label>
<p>You can select several images at once.</p>
</fieldset>
<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>
</div>
</body>
</html>