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

96 lines
2.7 KiB
PHP

<?php
namespace App\Livewire\StationLocator;
use Livewire\Component;
use Illuminate\Support\Facades\Http;
use Jantinnerezo\LivewireAlert\LivewireAlert;
class EditBranch extends Component
{
use LivewireAlert;
public $id;
public $code = '';
public $name = '';
public $details = '';
public $loading = false;
public $title = 'Edit Branch';
protected $rules = [
'code' => 'required|string|max:255',
'name' => 'required|string|max:255',
'details' => 'required|string|max:255',
];
protected $messages = [
'code.required' => 'Branch code is required',
'name.required' => 'Branch name is required!',
'details.required' => 'Branch details is required!',
];
public function mount($id)
{
$this->id = $id;
$this->fetchBranch();
}
public function fetchBranch()
{
try {
$response = Http::get("https://api.example.com/branches/{$this->id}");
if ($response->successful()) {
$branch = $response->json();
$this->code = $branch['code'];
$this->name = $branch['name'];
$this->details = $branch['details'];
} else {
$this->alert('error', 'Failed to fetch branch data.');
return redirect('/branches');
}
} catch (\Exception $e) {
$this->alert('error', 'An error occurred: ' . $e->getMessage());
return redirect('/branches');
}
}
public function save()
{
$this->validate();
$this->loading = true;
try {
$response = Http::put("https://api.example.com/branches/{$this->id}", [
'code' => $this->code,
'name' => $this->name,
'details' => $this->details,
'modified_by' => auth()->user()->name ?? 'user', // Adjust based on your auth
]);
if ($response->successful()) {
$this->alert('success', 'Branch updated successfully! Don\'t forget to sync updated branch to system parameters.');
return redirect('/branches');
} else {
$this->alert('error', 'Failed to update branch.');
}
} 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('/branches');
}
}
public function render()
{
return view('livewire.station-locator.edit-branch')->layout('layouts.app', ['title' => $this->title]);
}
}