<?php

namespace App\Http\Controllers;
use App\Models\AppSetting;
use App\Models\JadwalSholat;
use App\Models\SholatJumat;
use App\Models\Pengumuman;
use App\Models\Keuangan;
use Carbon\Carbon;

class WelcomeController extends Controller
{
	public function index()
	{
		$settings = AppSetting::first();
		
		if (!$settings) {
			$settings = AppSetting::create([
				'nama_aplikasi' => 'Masjid Al-Ikhlas',
				'footer' => 'Hak Cipta © <a href="https://wa.me/628179851011" target="_blank">Ali Mochtar Development System</a> ' . now()->year,
				'running_text' => 'Selamat datang di Masjid Al-Ikhlas',
			]);
		}
		
		$jadwalSholat = JadwalSholat::all();
		
		$today = Carbon::today('Asia/Jakarta');
		$sholatJumat = SholatJumat::where('tanggal', '>=', $today)
		->orderBy('tanggal', 'asc')
		->first();
		
		$pengumuman = Pengumuman::where('tanggal', '>=', $today)
		->orderBy('tanggal', 'asc')
		->take(3)
		->get();
		
		$keuanganSummary = [
			'total_pemasukan' => Keuangan::sum('pemasukan'),
			'total_pengeluaran' => Keuangan::sum('pengeluaran'),
			'saldo' => Keuangan::sum('pemasukan') - Keuangan::sum('pengeluaran'),
		];
		
		return view('welcome', compact('settings', 'jadwalSholat', 'sholatJumat', 'pengumuman', 'keuanganSummary'));
	}

	public function getDataTimestamp()
	{
		$latestTimestamps = [
			AppSetting::max('updated_at'),
			JadwalSholat::max('updated_at'),
			SholatJumat::max('updated_at'),
			Pengumuman::max('updated_at'),
			Keuangan::max('updated_at'),
		];

		$latestTimestamp = max(array_filter($latestTimestamps, fn($value) => !is_null($value)));

		return response()->json([
			'timestamp' => $latestTimestamp ? Carbon::parse($latestTimestamp)->toIso8601String() : null,
		]);
	}
}