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

const char* ssid = "xieqa_router";
const char* password = "11111111";

const char* host = "xieqa.com"; 
String apiKey = "sk-iot-ae668322907d9cee9a9cf1bd8225609f"; 
String deviceID = "lampu_kamar";        

const int RELAY_PIN = D5; 

void setup() {
  Serial.begin(115200);
  pinMode(RELAY_PIN, OUTPUT);
  digitalWrite(RELAY_PIN, LOW); 

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

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    
    WiFiClientSecure client;
    client.setInsecure(); // Wajib untuk HTTPS
    
    HTTPClient http;

    String url = "https://" + String(host) + "/ai/api/iot_gateway.php?k=" + apiKey + "&d=" + deviceID;
    
    // --- TAMBAHAN PENTING (Agar tidak dianggap BOT) ---
    http.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36");
    // --------------------------------------------------

    Serial.print("Requesting: ");
    Serial.println(url);

    http.begin(client, url); 
    int httpCode = http.GET();

    if (httpCode > 0) {
      String payload = http.getString();
      Serial.println("Response Code: " + String(httpCode));
      Serial.println("Payload: " + payload);

      if (payload == "1") {
        digitalWrite(RELAY_PIN, HIGH);
      } else {
        digitalWrite(RELAY_PIN, LOW);
      }
    } else {
      Serial.print("Error HTTP: ");
      Serial.println(httpCode);
    }
    http.end();
  }
  
  delay(1000); 
}
