MIF_E31222307/app/Http/Controllers/TimezoneController.php

103 lines
3.3 KiB
PHP

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
use DateTimeZone;
class TimezoneController extends Controller
{
public function index()
{
$currentTimezone = config('app.timezone');
$currentTime = Carbon::now();
$availableTimezones = $this->getAvailableTimezones();
return view('user.timezone', compact('currentTimezone', 'currentTime', 'availableTimezones'));
}
public function update(Request $request)
{
$timezone = $request->input('timezone');
// Validate timezone
if (!in_array($timezone, DateTimeZone::listIdentifiers())) {
return redirect()->back()->with('error', 'Timezone tidak valid!');
}
// Update .env file
$this->updateEnvFile('APP_TIMEZONE', $timezone);
// Clear config cache
\Artisan::call('config:clear');
return redirect()->back()->with('success', 'Timezone berhasil diperbarui ke ' . $timezone);
}
public function getCurrentTime()
{
$timezone = request('timezone', config('app.timezone'));
$currentTime = Carbon::now($timezone);
return response()->json([
'timezone' => $timezone,
'current_time' => $currentTime->format('Y-m-d H:i:s'),
'formatted_time' => $currentTime->format('d M Y H:i:s'),
'day_name' => $currentTime->format('l'),
'time_only' => $currentTime->format('H:i:s'),
'date_only' => $currentTime->format('d M Y')
]);
}
private function getAvailableTimezones()
{
$timezones = [
'Asia/Jakarta' => 'WIB (UTC+7)',
'Asia/Makassar' => 'WITA (UTC+8)',
'Asia/Jayapura' => 'WIT (UTC+9)',
'UTC' => 'UTC (UTC+0)',
'Asia/Singapore' => 'Singapore (UTC+8)',
'Asia/Kuala_Lumpur' => 'Malaysia (UTC+8)',
'Asia/Bangkok' => 'Thailand (UTC+7)',
'Asia/Manila' => 'Philippines (UTC+8)',
'Asia/Ho_Chi_Minh' => 'Vietnam (UTC+7)',
'Asia/Seoul' => 'Korea (UTC+9)',
'Asia/Tokyo' => 'Japan (UTC+9)',
'Asia/Shanghai' => 'China (UTC+8)',
'America/New_York' => 'New York (UTC-5)',
'America/Los_Angeles' => 'Los Angeles (UTC-8)',
'Europe/London' => 'London (UTC+0)',
'Europe/Paris' => 'Paris (UTC+1)',
'Europe/Berlin' => 'Berlin (UTC+1)',
'Australia/Sydney' => 'Sydney (UTC+10)',
'Australia/Perth' => 'Perth (UTC+8)',
];
return $timezones;
}
private function updateEnvFile($key, $value)
{
$path = base_path('.env');
if (file_exists($path)) {
$content = file_get_contents($path);
// Check if key exists
if (strpos($content, $key . '=') !== false) {
// Update existing key
$content = preg_replace(
'/^' . $key . '=.*/m',
$key . '=' . $value,
$content
);
} else {
// Add new key
$content .= "\n" . $key . '=' . $value;
}
file_put_contents($path, $content);
}
}
}