<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Kreait\Firebase\Factory;
use App\Services\WhatsAppNotifier;
use Illuminate\Support\Facades\Log;

class SensorController extends Controller
{
    protected $batasSuhu = 28; // sesuaikan batas suhu kamu

    public function store(Request $request)
    {
        $secret = $request->header('X-SYNC-SECRET');
        if (env('FIREBASE_SYNC_SECRET') && $secret !== env('FIREBASE_SYNC_SECRET')) {
            return response()->json(['error' => 'unauthorized'], 403);
        }

        $data = $request->validate([
            'suhu' => 'nullable|numeric',
            'soil' => 'nullable|numeric',
            'kelembapan' => 'nullable|numeric',
            'image_base64' => 'nullable|string',
        ]);

        $factory = (new Factory)
            ->withServiceAccount(base_path(env('FIREBASE_CREDENTIALS')))
            ->withDatabaseUri(env('FIREBASE_DATABASE_URL'));

        $database = $factory->createDatabase();

        $payload = [
            'suhu' => $data['suhu'] ?? null,
            'kelembapan' => $data['kelembapan'] ?? null,
            'soil' => $data['soil'] ?? null,
            'timestamp' => now()->toDateTimeString(),
        ];

        $database->getReference('/sensor/latest')->set($payload);
        $database->getReference('/sensor/history')->push($payload);

        if (!empty($data['suhu']) && $data['suhu'] > $this->batasSuhu) {
            try {
                $result = app(WhatsAppNotifier::class)->send(
                    "⚠️ Peringatan! Suhu alat saat ini {$data['suhu']}°C, melebihi batas {$this->batasSuhu}°C."
                );
                Log::info('Fonnte response: ' . json_encode($result));
            } catch (\Exception $e) {
                Log::error('Fonnte error: ' . $e->getMessage());
            }
        }

        if (!empty($data['image_base64'])) {
            try {
                $database->getReference('/sensor/last_image')->set([
                    'image_base64' => $data['image_base64'],
                    'timestamp' => now()->toDateTimeString(),
                ]);
            } catch (\Exception $e) {
                // ignore
            }
        }

        return response()->json(['status' => 'ok'], 201);
    }
}