<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class HistoryController extends Controller
{
    // Path relatif ke file Firebase JSON export
    protected $firebaseJsonPath = 'public/reports/firebase_export.json';
    
    // Path relatif untuk file history sensor lokal
    protected $reportFilePath = 'public/reports/report.json';

    /**
     * Mendapatkan semua data history sensor
     */
    public function getAll()
    {
        // Debug log
        Log::info('HistoryController@getAll dipanggil');
        
        // Inisialisasi array untuk menyimpan history
        $history = [];
        
        try {
            // Periksa apakah file Firebase export ada
            if (Storage::exists($this->firebaseJsonPath)) {
                Log::info('File Firebase export ditemukan');
                
                // Baca file JSON Firebase
                $jsonData = Storage::get($this->firebaseJsonPath);
                $firebaseData = json_decode($jsonData, true);
                
                // Jika struktur Firebase terdeteksi, ambil data sensor dari situ
                if ($firebaseData && isset($firebaseData['sensor'])) {
                    $timestamp = now()->toIso8601String();
                    
                    // Jika ada timestamp di file Firebase, gunakan itu
                    if (isset($firebaseData['status']['last_seen'])) {
                        $today = Carbon::today()->format('Y-m-d');
                        $timestamp = Carbon::parse($today . ' ' . $firebaseData['status']['last_seen'])->toIso8601String();
                    }
                    
                    // Tambahkan data sensor suhu
                    if (isset($firebaseData['sensor']['suhu'])) {
                        $history[] = [
                            'timestamp' => $timestamp,
                            'sensor' => 'suhu',
                            'newValue' => $firebaseData['sensor']['suhu']
                        ];
                    }
                    
                    // Tambahkan data sensor kelembaban
                    if (isset($firebaseData['sensor']['kelembaban'])) {
                        $history[] = [
                            'timestamp' => $timestamp,
                            'sensor' => 'kelembaban',
                            'newValue' => $firebaseData['sensor']['kelembaban']
                        ];
                    }
                    
                    // Tambahkan data sensor cahaya
                    if (isset($firebaseData['sensor']['cahaya'])) {
                        $history[] = [
                            'timestamp' => $timestamp,
                            'sensor' => 'cahaya',
                            'newValue' => $firebaseData['sensor']['cahaya']
                        ];
                    }
                    
                    // Tambahkan data sensor kelembapan tanah
                    if (isset($firebaseData['sensor']['kelembapan_tanah'])) {
                        $history[] = [
                            'timestamp' => $timestamp,
                            'sensor' => 'kelembapan_tanah',
                            'newValue' => $firebaseData['sensor']['kelembapan_tanah']
                        ];
                    }
                    
                    Log::info('Data sensor dari Firebase berhasil diambil');
                }
            }
            
            // Periksa juga file history lokal jika ada
            if (Storage::exists($this->reportFilePath)) {
                Log::info('File history lokal ditemukan');
                $localJsonData = Storage::get($this->reportFilePath);
                $localHistory = json_decode($localJsonData, true) ?: [];
                
                // Gabungkan data lokal dengan data dari Firebase
                $history = array_merge($history, $localHistory);
                
                // Urutkan berdasarkan timestamp terbaru
                usort($history, function($a, $b) {
                    return strtotime($b['timestamp']) - strtotime($a['timestamp']);
                });
                
                Log::info('Data history lokal berhasil diambil dan digabungkan');
            }
            
            // Jika tidak ada data sama sekali, kembalikan array kosong
            if (empty($history)) {
                Log::info('Tidak ada data history yang ditemukan');
                return response()->json([]);
            }
            
            Log::info('Total data history: ' . count($history));
            return response()->json($history);
            
        } catch (\Exception $e) {
            Log::error('Error saat mengambil data history: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Terjadi kesalahan saat mengambil data history: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Mendapatkan data langsung dari Firebase (untuk testing)
     */
    public function getFirebaseData()
    {
        try {
            // Cek apakah file Firebase export ada
            if (!Storage::exists($this->firebaseJsonPath)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'File Firebase export tidak ditemukan'
                ], 404);
            }

            // Baca file JSON Firebase
            $jsonData = Storage::get($this->firebaseJsonPath);
            $firebaseData = json_decode($jsonData, true);
            
            return response()->json([
                'status' => 'success',
                'data' => $firebaseData
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Terjadi kesalahan: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Mendapatkan data sensor terkini dengan status dan aksi
     */
    public function getCurrentSensorData()
    {
        try {
            // Cek apakah file Firebase export ada
            if (!Storage::exists($this->firebaseJsonPath)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'File Firebase export tidak ditemukan'
                ], 404);
            }

            // Baca file JSON Firebase
            $jsonData = Storage::get($this->firebaseJsonPath);
            $firebaseData = json_decode($jsonData, true);
            
            // Periksa apakah data sensor ada
            if (!isset($firebaseData['sensor'])) {
                return response()->json([
                    'status' => 'error', 
                    'message' => 'Data sensor tidak ditemukan'
                ], 404);
            }
            
            // Siapkan data yang akan dikembalikan
            $sensorData = [
                'suhu' => [
                    'nilai' => $firebaseData['sensor']['suhu'] ?? null,
                    'status' => $this->getSuhuStatus($firebaseData['sensor']['suhu'] ?? null),
                    'aksi' => $this->getSuhuAksi($firebaseData['sensor']['suhu'] ?? null)
                ],
                'kelembaban' => [
                    'nilai' => $firebaseData['sensor']['kelembapan_tanah'] ?? null,
                    'status' => $this->getKelembabanStatus($firebaseData['sensor']['kelembapan_tanah'] ?? null),
                    'aksi' => $this->getKelembabanAksi($firebaseData['sensor']['kelembapan_tanah'] ?? null)
                ],
                'cahaya' => [
                    'nilai' => $firebaseData['sensor']['cahaya'] ?? null,
                    'status' => $this->getCahayaStatus($firebaseData['sensor']['cahaya'] ?? null),
                    'aksi' => $this->getCahayaAksi($firebaseData['sensor']['cahaya'] ?? null)
                ],
                'connected' => $firebaseData['status']['connected'] ?? false,
                'last_seen' => $firebaseData['status']['last_seen'] ?? null
            ];
            
            return response()->json([
                'status' => 'success',
                'data' => $sensorData
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Terjadi kesalahan: ' . $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Menentukan status suhu berdasarkan nilai
     */
    private function getSuhuStatus($value)
    {
        if ($value === null) return '--';
        
        if ($value < 24) {
            return 'Rendah';
        } else if ($value >= 25 && $value <= 27) {
            return 'Normal';
        } else if ($value >= 28) {
            return 'Tinggi';
        }
        
        return '--';
    }
    
    /**
     * Menentukan aksi suhu berdasarkan nilai
     */
    private function getSuhuAksi($value)
    {
        if ($value === null) return '--';
        
        if ($value < 24) {
            return 'Kipas Off';
        } else if ($value >= 25 && $value <= 27) {
            return 'Kipas Off';
        } else if ($value >= 28) {
            return 'Kipas On';
        }
        
        return '--';
    }
    
    /**
     * Menentukan status kelembaban tanah berdasarkan nilai
     */
    private function getKelembabanStatus($value)
    {
        if ($value === null) return '--';
        
        if ($value < 40) {
            return 'Kering';
        } else if ($value >= 40 && $value < 50) {
            return 'Cukup';
        } else if ($value >= 50 && $value < 60) {
            return 'Optimal';
        } else if ($value >= 60 && $value <= 70) {
            return 'Lembap';
        } else if ($value > 70) {
            return 'Sangat Lembap';
        }
        
        return '--';
    }
    
    /**
     * Menentukan aksi kelembaban tanah berdasarkan nilai
     */
    private function getKelembabanAksi($value)
    {
        if ($value === null) return '--';
        
        if ($value < 40) {
            return 'Pompa Air On';
        } else {
            return 'Pompa Air Off';
        }
    }
    
    /**
     * Menentukan status cahaya berdasarkan nilai
     */
    private function getCahayaStatus($value)
    {
        if ($value === null) return '--';
        
        if ($value < 8000) {
            return 'Rendah';
        } else if ($value >= 8001 && $value <= 11000) {
            return 'Normal';
        } else if ($value > 11001) {
            return 'Tinggi';
        }
        
        return '--';
    }
    
    /**
     * Menentukan aksi cahaya berdasarkan nilai
     */
    private function getCahayaAksi($value)
    {
        if ($value === null) return '--';
        
        if ($value < 8000) {
            return 'Lampu On';
        } else {
            return 'Lampu Off';
        }
    }

    /**
     * Menyimpan data baru ke history
     */
    public function store(Request $request)
    {
        // Validasi request
        $request->validate([
            'sensor' => 'required|string',
            'newValue' => 'required|numeric',
            'timestamp' => 'nullable|string'
        ]);

        // Baca data yang ada
        $history = [];
        if (Storage::exists($this->reportFilePath)) {
            $jsonData = Storage::get($this->reportFilePath);
            $history = json_decode($jsonData, true) ?: [];
        }

        // Buat data baru
        $newData = [
            'timestamp' => $request->input('timestamp', now()->toIso8601String()),
            'sensor' => $request->input('sensor'),
            'newValue' => $request->input('newValue')
        ];

        // Tambahkan data baru ke awal array (terbaru di atas)
        array_unshift($history, $newData);

        // Simpan kembali ke file
        Storage::put($this->reportFilePath, json_encode($history, JSON_PRETTY_PRINT));

        return response()->json([
            'status' => 'success',
            'message' => 'Data berhasil disimpan',
            'data' => $newData
        ]);
    }

    /**
     * Menyinkronkan data dari Firebase Export ke file history lokal
     */
    public function syncFromFirebase()
    {
        try {
            // Periksa apakah file Firebase export ada
            if (!Storage::exists($this->firebaseJsonPath)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'File Firebase export tidak ditemukan'
                ], 404);
            }
            
            // Baca file JSON Firebase
            $jsonData = Storage::get($this->firebaseJsonPath);
            $firebaseData = json_decode($jsonData, true);
            
            // Periksa apakah data sensor ada
            if (!isset($firebaseData['sensor'])) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Data sensor tidak ditemukan di file Firebase'
                ], 400);
            }
            
            // Baca data history yang ada
            $history = [];
            if (Storage::exists($this->reportFilePath)) {
                $localJsonData = Storage::get($this->reportFilePath);
                $history = json_decode($localJsonData, true) ?: [];
            }
            
            // Ambil timestamp
            $timestamp = now()->toIso8601String();
            if (isset($firebaseData['status']['last_seen'])) {
                $today = Carbon::today()->format('Y-m-d');
                $timestamp = Carbon::parse($today . ' ' . $firebaseData['status']['last_seen'])->toIso8601String();
            }
            
            // Tambahkan data sensor suhu
            if (isset($firebaseData['sensor']['suhu'])) {
                $history[] = [
                    'timestamp' => $timestamp,
                    'sensor' => 'suhu',
                    'newValue' => $firebaseData['sensor']['suhu']
                ];
            }
            
            // // Tambahkan data sensor kelembaban
            // if (isset($firebaseData['sensor']['kelembaban'])) {
            //     $history[] = [
            //         'timestamp' => $timestamp,
            //         'sensor' => 'kelembaban',
            //         'newValue' => $firebaseData['sensor']['kelembaban']
            //     ];
            // }
            
            // Tambahkan data sensor cahaya
            if (isset($firebaseData['sensor']['cahaya'])) {
                $history[] = [
                    'timestamp' => $timestamp,
                    'sensor' => 'cahaya',
                    'newValue' => $firebaseData['sensor']['cahaya']
                ];
            }
            
            // Tambahkan data sensor kelembapan tanah
            if (isset($firebaseData['sensor']['kelembapan_tanah'])) {
                $history[] = [
                    'timestamp' => $timestamp,
                    'sensor' => 'kelembapan_tanah',
                    'newValue' => $firebaseData['sensor']['kelembapan_tanah']
                ];
            }
            
            // Urutkan berdasarkan timestamp terbaru
            usort($history, function($a, $b) {
                return strtotime($b['timestamp']) - strtotime($a['timestamp']);
            });
            
            // Simpan kembali ke file
            Storage::put($this->reportFilePath, json_encode($history, JSON_PRETTY_PRINT));
            
            return response()->json([
                'status' => 'success',
                'message' => 'Data berhasil disinkronkan dari Firebase',
                'data_count' => count($history)
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Terjadi kesalahan saat sinkronisasi: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Menghapus satu data dari history
     */
    public function delete(Request $request)
    {
        $request->validate([
            'index' => 'required|integer|min:0'
        ]);

        $index = $request->input('index');
        
        // Baca data yang ada
        if (!Storage::exists($this->reportFilePath)) {
            return response()->json([
                'status' => 'error',
                'message' => 'File history tidak ditemukan'
            ], 404);
        }

        $jsonData = Storage::get($this->reportFilePath);
        $history = json_decode($jsonData, true) ?: [];

        // Pastikan index valid
        if (!isset($history[$index])) {
            return response()->json([
                'status' => 'error',
                'message' => 'Data dengan index tersebut tidak ditemukan'
            ], 404);
        }

        // Hapus data
        array_splice($history, $index, 1);

        // Simpan kembali ke file
        Storage::put($this->reportFilePath, json_encode($history, JSON_PRETTY_PRINT));

        return response()->json([
            'status' => 'success',
            'message' => 'Data berhasil dihapus'
        ]);
    }

    /**
     * Menghapus semua data history
     */
    public function clear()
    {
        // Hapus semua data dengan menyimpan array kosong
        Storage::put($this->reportFilePath, json_encode([]));

        return response()->json([
            'status' => 'success',
            'message' => 'Semua data history berhasil dihapus'
        ]);
    }
} 