#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecure.h>

// --- 1. KONFIGURASI WIFI & SERVER ---
const char* ssid = "xieqa_router";            // Sesuai file 1
const char* password = "11111111";     // Sesuai file 1
const char* host = "xieqa.com";
String apiKey = "sk-iot-d071690f8c42745892a05dda5da0fb89"; // API Key sama untuk kedua alat

// --- 2. KONFIGURASI ID ALAT (Wajib beda) ---
String id_lampu = "lampu_kamar";      // ID untuk Relay
String id_tanah = "sensor_tanah";     // ID untuk Sensor

// --- 3. PIN DEFINITION ---
const int PIN_RELAY = D5; 
const int PIN_SENSOR = A0; 

// --- 4. KALIBRASI SENSOR TANAH (SUDAH DIPERBAIKI) ---
// Berdasarkan data Bapak: Raw Kering = 663.
// Kita set AirValue 670 agar saat di udara terbaca 0% (Kering)
const int AirValue = 670;    // Nilai saat kering (Udara)
const int WaterValue = 350;  // Nilai saat basah (Air)

// --- 5. TIMER (PENGGANTI DELAY) ---
unsigned long lastCheckLampu = 0;
unsigned long lastSendSensor = 0;

void setup() {
  Serial.begin(115200);
  
  // Setup Pin
  pinMode(PIN_RELAY, OUTPUT);
  // PENTING: Untuk Relay Active LOW, HIGH = Mati, LOW = Nyala.
  // Kita set HIGH dulu agar saat alat nyala, lampu tetap MATI.
  digitalWrite(PIN_RELAY, HIGH); 

  // Koneksi WiFi
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" Connected!");
}

void loop() {
  // Pastikan WiFi Connect
  if (WiFi.status() == WL_CONNECTED) {
    unsigned long now = millis();

    // --- TUGAS 1: CEK STATUS LAMPU (Tiap 1 Detik) ---
    // Agar respon cepat saat disuruh nyala/mati
    if (now - lastCheckLampu > 1000) {
      lastCheckLampu = now;
      cekStatusLampu();
    }

    // --- TUGAS 2: KIRIM DATA SENSOR (Tiap 5 Detik) ---
    // Agar tidak membebani server
    if (now - lastSendSensor > 5000) {
      lastSendSensor = now;
      bacaDanKirimSensor();
    }
  }
}

// --- FUNGSI 1: CEK LAMPU ---
void cekStatusLampu() {
  WiFiClientSecure client;
  client.setInsecure();
  HTTPClient http;

  // URL Cek Status (Hanya kirim k & d)
  String url = "https://" + String(host) + "/ai/api/iot_gateway.php?k=" + apiKey + "&d=" + id_lampu;
  
  http.setUserAgent("Mozilla/5.0 (ESP8266-Lamp)");
  http.begin(client, url);
  
  int httpCode = http.GET();
  if (httpCode > 0) {
    String payload = http.getString();
    // Logika Relay (Active Low)
    if (payload == "1") {
      digitalWrite(PIN_RELAY, LOW); // NYALA (Active Low)
    } else {
      digitalWrite(PIN_RELAY, HIGH);  // MATI (Active Low)
    }
    // Serial.println("Lampu: " + payload); // Uncomment untuk debug
  }
  http.end();
}

// --- FUNGSI 2: BACA & KIRIM SENSOR ---
void bacaDanKirimSensor() {
  // 1. Baca Analog
  int rawValue = analogRead(PIN_SENSOR);
  
  // 2. Hitung Persen (Mapping Baru)
  int persen = map(rawValue, AirValue, WaterValue, 0, 100);
  if (persen < 0) persen = 0;
  if (persen > 100) persen = 100;

  // 3. Kirim ke Server
  WiFiClientSecure client;
  client.setInsecure();
  HTTPClient http;

  // URL Kirim Data (Pakai &v=...)
  String nilai = String(persen) + "%";
  nilai.replace("%", "%25"); // Encode persen
  
  String url = "https://" + String(host) + "/ai/api/iot_gateway.php?k=" + apiKey + "&d=" + id_tanah + "&v=" + nilai;
  
  http.setUserAgent("Mozilla/5.0 (ESP8266-Soil)");
  http.begin(client, url);
  
  int httpCode = http.GET();
  if (httpCode > 0) {
    Serial.println("Sensor Terkirim: " + String(persen) + "% (Raw: " + String(rawValue) + ")");
  } else {
    Serial.println("Gagal Kirim Sensor");
  }
  http.end();
}
