<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Kreait\Firebase\Factory;

class DashboardController extends Controller
{
    public function index()
    {
        $factory = (new Factory)
            ->withServiceAccount(base_path(env('FIREBASE_CREDENTIALS')))
            ->withDatabaseUri(env('FIREBASE_DATABASE_URL'));

        $database = $factory->createDatabase();

        $latest = $database->getReference('/sensor/latest')->getValue();
        $historyRaw = $database->getReference('/sensor/history')->getValue();

        $timeseries = collect();
        if ($historyRaw) {
            $timeseries = collect($historyRaw)
                ->sortBy('created_at')
                ->take(50)
                ->map(function($r) {
                    return [
                        't'          => $r['created_at'] ?? '-',
                        'suhu'       => $r['suhu'] ?? 0,
                        'kelembapan' => $r['kelembapan'] ?? 0,
                        'soil'       => $r['soil'] ?? 0,
                    ];
                })->values();
        }

        $latestData = (object)[
            'suhu'       => $latest['suhu'] ?? 0,
            'kelembapan' => $latest['kelembapan'] ?? 0,
            'soil'       => $latest['soil'] ?? 0,
            'created_at' => $latest['updated_at'] ?? null,
        ];

        $images = collect();

        return view('dashboard', [
            'latest'     => $latestData,
            'images'     => $images,
            'timeseries' => $timeseries,
        ]);
    }
}