cms-laravel/app/Livewire/StationLocator/EditStation.php

234 lines
8.0 KiB
PHP

<?php
namespace App\Livewire\StationLocator;
use Livewire\Component;
use Illuminate\Support\Facades\Http;
use Jantinnerezo\LivewireAlert\LivewireAlert;
class EditStation extends Component
{
use LivewireAlert;
public $id;
public $name = '';
public $location = '';
public $map_URL = '';
public $lat = '';
public $long = '';
public $BranchId = '';
public $contact_number = [];
public $code = '';
public $fuels = [];
public $fuelsData = [];
public $newFuel = [];
public $branches = [];
public $isSched = 2; // 0 = No, 1 = Yes, 2 = Unset
public $date = '';
public $fuelModal = false;
public $removeModal = false;
public $fuelName = '';
public $fuelIndex = '';
public $loading = false;
public $title = 'Edit Station';
protected $rules = [
'name' => 'required|string|max:128',
'location' => 'required|string|max:128',
'map_URL' => 'required|url',
'lat' => 'required|string',
'long' => 'required|string',
'BranchId' => 'required|string',
'contact_number' => 'required|array|min:1',
'contact_number.*' => 'regex:/^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$/|min:7',
'code' => 'required|string',
'isSched' => 'required|in:0,1',
'date' => 'required_if:isSched,1|date',
];
protected $messages = [
'name.required' => 'Station name is required!',
'location.required' => 'Station location is required!',
'map_URL.required' => 'Url is required!',
'lat.required' => 'Lat is required!',
'long.required' => 'Long is required!',
'BranchId.required' => 'Branch is required!',
'contact_number.required' => 'Contact number is required!',
'contact_number.*.regex' => 'Please enter a valid contact number',
'contact_number.*.min' => 'Minimum character is 7',
'code.required' => 'Station code is required!',
'isSched.required' => 'Please select a schedule update value.',
'date.required_if' => 'Scheduled date is required when scheduling is enabled.',
];
public function mount($id)
{
$this->id = $id;
$this->fetchStation();
$this->fetchBranches();
$this->fetchFuels();
}
public function fetchStation()
{
try {
$response = Http::get("https://api.example.com/stations/{$this->id}");
if ($response->successful()) {
$station = $response->json();
$this->name = $station['name'];
$this->location = $station['location'];
$this->map_URL = $station['map_Url'];
$this->lat = $station['lat'];
$this->long = $station['long'];
$this->BranchId = $station['BranchId'];
$this->contact_number = explode(',', $station['contact_number']);
$this->code = $station['code'];
$this->fuels = $this->sortFuels($station['StationFuels'] ?? []);
$this->isSched = $station['Schedule'] ? 1 : 2;
$this->date = $station['Schedule'];
} else {
$this->alert('error', 'Failed to fetch station data.');
}
} catch (\Exception $e) {
$this->alert('error', 'An error occurred: ' . $e->getMessage());
}
}
public function fetchBranches()
{
try {
$response = Http::get('https://api.example.com/branches/noLimit');
if ($response->successful()) {
$this->branches = $response->json()['data'] ?? [];
}
} catch (\Exception $e) {
$this->alert('error', 'An error occurred while fetching branches.');
}
}
public function fetchFuels()
{
try {
$response = Http::get('https://api.example.com/fuels');
if ($response->successful()) {
$this->fuelsData = $response->json()['data'] ?? [];
$this->newFuel = array_filter($this->fuelsData, fn($fuel) => !in_array($fuel['id'], array_column($this->fuels, 'FuelId')));
}
} catch (\Exception $e) {
$this->alert('error', 'An error occurred while fetching fuels.');
}
}
public function sortFuels($fuels)
{
$sorted = array_map(function ($fuel) {
$nameParts = explode(' ', $fuel['Fuel']['name'] ?? $fuel['name']);
$val = (int) end($nameParts) ?: 0;
return ['val' => $val, 'data' => $fuel];
}, $fuels);
usort($sorted, fn($a, $b) => $a['val'] <=> $b['val']);
return array_map(fn($item) => $item['data'], $sorted);
}
public function updateFuels($price, $id, $isFuel = true)
{
$this->fuels = array_map(function ($fuel) use ($price, $id, $isFuel) {
$fuelId = $isFuel ? ($fuel['FuelId'] ?? $fuel['id']) : $fuel['id'];
if ($fuelId === $id) {
$fuel['price'] = $price;
}
return $fuel;
}, $this->fuels);
}
public function addToStationFuel($selectedFuels)
{
$newFuels = array_filter($this->fuelsData, fn($fuel) => in_array($fuel['id'], $selectedFuels));
$this->fuels = array_merge($this->fuels, array_map(fn($fuel) => [
'FuelId' => $fuel['id'],
'name' => $fuel['name'],
'price' => '0.00',
], $newFuels));
$this->newFuel = array_filter($this->newFuel, fn($fuel) => !in_array($fuel['id'], $selectedFuels));
$this->fuelModal = false;
}
public function removeFuel($index, $name)
{
$this->fuelIndex = $index;
$this->fuelName = $name;
$this->removeModal = true;
}
public function confirmRemoveFuel()
{
$this->fuels = array_filter($this->fuels, fn($_, $i) => $i !== $this->fuelIndex, ARRAY_FILTER_USE_BOTH);
$this->removeModal = false;
$this->fetchFuels();
}
public function save()
{
$this->validate();
if (empty($this->fuels) && $this->isSched == 1) {
$this->alert('error', 'Cannot schedule a station without fuel.');
return;
}
if ($this->fuels && array_filter($this->fuels, fn($fuel) => in_array($fuel['price'], [0, '0.00', '00.00', null]))) {
$this->alert('error', 'Invalid price for fuel.');
return;
}
$this->loading = true;
try {
$response = Http::put("https://api.example.com/stations/{$this->id}", [
'name' => $this->name,
'location' => $this->location,
'map_Url' => $this->map_URL,
'lat' => $this->lat,
'long' => $this->long,
'contact_number' => implode(',', $this->contact_number),
'BranchId' => $this->BranchId,
'code' => $this->code,
'Schedule' => $this->isSched == 1 ? $this->date : null,
'NewStationFuel' => array_map(fn($fuel) => [
'FuelId' => $fuel['FuelId'],
'price' => $fuel['price'],
], $this->fuels),
'modified_by' => auth()->user()->name ?? 'user', // Adjust based on your auth
]);
if ($response->successful()) {
$this->alert('success', 'Station updated successfully!');
return redirect('/stations');
} else {
$this->alert('error', 'Failed to update station.');
}
} catch (\Exception $e) {
$this->alert('error', 'An error occurred: ' . $e->getMessage());
} finally {
$this->loading = false;
}
}
public function cancel()
{
if (confirm('Are you sure you want to discard changes?')) {
return redirect('/stations');
}
}
public function render()
{
return view('livewire.station-locator.edit-station', [
'branches' => $this->branches,
'fuelsData' => $this->fuelsData,
'newFuel' => $this->newFuel,
])->layout('layouts.app', ['title' => $this->title]);
}
}