<?php
/**
 * apikey/index.php - IoT Command Center (Full GUI Management)
 * Fitur: Create Device via Web, Create API Key, Monitoring Sensor
 */
session_start();
include '../config/database.php';

// 1. Cek Login & Session
if (!isset($_SESSION['user_id'])) { header("Location: ../auth/login_page.php"); exit; }
$user_id = $_SESSION['user_id'];
$msg = "";

// --- LOGIC A: BUAT API KEY BARU ---
if (isset($_POST['create_key'])) {
    $label = mysqli_real_escape_string($conn, $_POST['label']);
    $new_key = 'sk-iot-' . bin2hex(random_bytes(16)); // Generate Key Acak
    
    if(mysqli_query($conn, "INSERT INTO user_api_keys (user_id, key_string, label) VALUES ('$user_id', '$new_key', '$label')")) {
        $msg = "<div class='alert alert-success alert-dismissible fade show'>API Key berhasil dibuat! <button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
    }
}

// --- LOGIC B: TAMBAH ALAT BARU (INI YANG MENGGANTIKAN INSERT MANUAL) ---
if (isset($_POST['add_device'])) {
    // Ambil input dari Form
    $dev_label = mysqli_real_escape_string($conn, $_POST['dev_label']); // Cth: Sensor Jantung
    
    // Ubah ID jadi huruf kecil & ganti spasi dengan garis bawah (Cth: Sensor Jantung -> sensor_jantung)
    // Agar aman dibaca Arduino
    $raw_id = $_POST['dev_id'];
    $dev_id = mysqli_real_escape_string($conn, strtolower(str_replace(' ', '_', $raw_id))); 
    
    // Cek apakah ID sudah ada?
    $cek = mysqli_query($conn, "SELECT id FROM iot_devices WHERE user_id='$user_id' AND device_id='$dev_id'");
    
    if(mysqli_num_rows($cek) > 0) {
        $msg = "<div class='alert alert-danger alert-dismissible fade show'>Gagal! ID '$dev_id' sudah digunakan. Gunakan ID lain. <button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
    } else {
        // QUERY INSERT OTOMATIS
        // Default status = 0 (Mati), last_value = '0' (Kosong)
        $q = "INSERT INTO iot_devices (user_id, device_id, label, status, last_value) VALUES ('$user_id', '$dev_id', '$dev_label', 0, '0')";
        
        if(mysqli_query($conn, $q)) {
            $msg = "<div class='alert alert-success alert-dismissible fade show'>Perangkat '$dev_label' berhasil didaftarkan! ID Sistem: <b>$dev_id</b> <button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
        } else {
            $msg = "<div class='alert alert-danger'>Database Error: ".mysqli_error($conn)."</div>";
        }
    }
}

// --- LOGIC C: HAPUS ---
if (isset($_GET['del_key'])) {
    $id = (int)$_GET['del_key'];
    mysqli_query($conn, "DELETE FROM user_api_keys WHERE id='$id' AND user_id='$user_id'");
    header("Location: index.php"); exit;
}
if (isset($_GET['del_dev'])) {
    $id = (int)$_GET['del_dev'];
    mysqli_query($conn, "DELETE FROM iot_devices WHERE id='$id' AND user_id='$user_id'");
    header("Location: index.php"); exit;
}

// Ambil Data dari Database untuk ditampilkan
$list_keys = mysqli_query($conn, "SELECT * FROM user_api_keys WHERE user_id='$user_id' ORDER BY id DESC");
$list_devs = mysqli_query($conn, "SELECT * FROM iot_devices WHERE user_id='$user_id' ORDER BY id DESC");
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IoT Control Center</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        body { background: #f3f4f6; font-family: 'Segoe UI', sans-serif; }
        .card-box { background: white; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.05); border: none; }
        .api-code { font-family: monospace; background: #eef2ff; color: #4f46e5; padding: 4px 8px; border-radius: 4px; font-size: 0.85rem; }
        .badge-sensor { background: #dbeafe; color: #1e40af; font-size: 0.8rem; padding: 5px 10px; border-radius: 20px; }
    </style>
</head>
<body>

<div class="container py-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="fw-bold text-dark"><i class="bi bi-grid-fill text-primary"></i> IoT Dashboard</h3>
            <p class="text-muted mb-0">Kelola Alat & Sensor Tanpa Coding Manual</p>
        </div>
        <a href="../index.php" class="btn btn-outline-secondary rounded-pill"><i class="bi bi-arrow-left"></i> Kembali Chat</a>
    </div>

    <?= $msg ?>

    <div class="row g-4">
        
        <div class="col-lg-8">
            <div class="card-box p-4 h-100">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="fw-bold"><i class="bi bi-cpu me-2"></i>Daftar Perangkat</h5>
                    <button class="btn btn-primary btn-sm rounded-pill px-3" data-bs-toggle="modal" data-bs-target="#modalAddDev">
                        <i class="bi bi-plus-circle"></i> Tambah Alat Baru
                    </button>
                </div>

                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>Nama Label</th>
                                <th>ID Sistem (Untuk Arduino)</th>
                                <th>Status / Data Realtime</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(mysqli_num_rows($list_devs) > 0): ?>
                                <?php while($d = mysqli_fetch_assoc($list_devs)): ?>
                                <tr>
                                    <td class="fw-bold text-dark"><?= htmlspecialchars($d['label']) ?></td>
                                    <td><code><?= htmlspecialchars($d['device_id']) ?></code></td>
                                    <td>
                                        <?php if($d['last_value'] != '0' && $d['last_value'] != ''): ?>
                                            <span class="badge-sensor">
                                                <i class="bi bi-activity"></i> DATA: <b><?= htmlspecialchars($d['last_value']) ?></b>
                                            </span>
                                            <div class="text-muted" style="font-size:10px; margin-top:2px">
                                                Update: <?= date('H:i:s', strtotime($d['last_updated'])) ?>
                                            </div>
                                        <?php else: ?>
                                            <?php if($d['status'] == 1): ?>
                                                <span class="badge bg-success">NYALA</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">MATI</span>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a href="?del_dev=<?= $d['id'] ?>" class="btn btn-sm btn-light text-danger" onclick="return confirm('Hapus alat ini?')"><i class="bi bi-trash"></i></a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr><td colspan="4" class="text-center text-muted py-4">Belum ada alat. Klik tombol <b>Tambah Alat Baru</b> di atas.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card-box p-4 bg-white">
                <h6 class="fw-bold mb-3 text-secondary"><i class="bi bi-key-fill me-2"></i>Kunci Akses (API Key)</h6>
                
                <form method="POST" class="d-flex gap-2 mb-4">
                    <input type="text" name="label" class="form-control form-control-sm" placeholder="Label (Mis: ESP32 Rumah)" required>
                    <button type="submit" name="create_key" class="btn btn-dark btn-sm"><i class="bi bi-plus"></i></button>
                </form>

                <div class="d-flex flex-column gap-2">
                    <?php while($k = mysqli_fetch_assoc($list_keys)): ?>
                        <div class="border rounded p-2 d-flex justify-content-between align-items-center">
                            <div style="overflow:hidden;">
                                <div class="fw-bold" style="font-size:12px"><?= htmlspecialchars($k['label']) ?></div>
                                <div class="api-code text-truncate" style="max-width: 150px;"><?= $k['key_string'] ?></div>
                            </div>
                            <div class="d-flex gap-1">
                                <button class="btn btn-sm text-primary" onclick="navigator.clipboard.writeText('<?= $k['key_string'] ?>'); alert('Disalin!')"><i class="bi bi-copy"></i></button>
                                <a href="?del_key=<?= $k['id'] ?>" class="btn btn-sm text-danger" onclick="return confirm('Hapus key ini?')"><i class="bi bi-x"></i></a>
                            </div>
                        </div>
                    <?php endwhile; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- CODE EXAMPLE SECTION -->
    <div class="row g-4 mt-2">
        <div class="col-12">
            <div class="card-box p-4 bg-white border-0 shadow-sm" style="border-radius: 16px;">
                <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
                    <div class="d-flex align-items-center gap-3">
                        <h5 class="fw-bold m-0" style="color: #1e293b;"><i class="bi bi-braces text-primary me-2"></i>Integrasi ESP8266</h5>
                        
                        <ul class="nav nav-pills bg-light p-1 rounded-pill" id="codeTab" role="tablist" style="font-size: 13px; font-weight: 600;">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link rounded-pill px-3 py-1 text-secondary" id="led-only-tab" data-bs-toggle="pill" data-bs-target="#led-only" type="button" role="tab">LED Saja</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active rounded-pill px-3 py-1" id="led-sensor-tab" data-bs-toggle="pill" data-bs-target="#led-sensor" type="button" role="tab">LED + Sensor Tanah</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link rounded-pill px-3 py-1 text-secondary" id="heart-sensor-tab" data-bs-toggle="pill" data-bs-target="#heart-sensor" type="button" role="tab">Sensor Jantung</button>
                            </li>
                        </ul>
                    </div>
                </div>
                
                <div class="alert small border-0 d-flex align-items-center" style="background: #fffbeb; color: #b45309; border-radius: 12px;">
                    <i class="bi bi-info-circle-fill fs-5 me-3 text-warning"></i> 
                    <div>Sesuaikan <b>ssid</b>, <b>password</b> wifi, <b>apiKey</b>, dan <b>deviceID</b> pada kode di bawah dengan data Anda sebelum melakukan upload ke board ESP8266.</div>
                </div>

                <div class="tab-content mt-4" id="codeTabContent">
                    
                    <!-- TAB 2: LED + SENSOR (ACTIVE) -->
                    <div class="tab-pane fade show active" id="led-sensor" role="tabpanel">
                        <div class="d-flex justify-content-end mb-2">
                            <a href="esp8266_led_sensor.ino" download="esp8266_led_sensor.ino" class="btn btn-primary btn-sm rounded-pill px-4 shadow-sm" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none;">
                                <i class="bi bi-cloud-arrow-down-fill me-1"></i> Unduh .ino (LED + Sensor)
                            </a>
                        </div>
                        <div class="code-editor-container" style="background: #1e1e1e; border-radius: 12px; overflow: hidden; box-shadow: 0 10px 25px rgba(0,0,0,0.1);">
                    <div class="editor-header d-flex justify-content-between align-items-center px-3 py-2" style="background: #2d2d2d; border-bottom: 1px solid #404040;">
                        <div class="mac-dots d-flex gap-2">
                            <span style="width: 12px; height: 12px; background: #ff5f56; border-radius: 50%; display: inline-block; box-shadow: 0 0 4px rgba(255,95,86,0.3);"></span>
                            <span style="width: 12px; height: 12px; background: #ffbd2e; border-radius: 50%; display: inline-block; box-shadow: 0 0 4px rgba(255,189,46,0.3);"></span>
                            <span style="width: 12px; height: 12px; background: #27c93f; border-radius: 50%; display: inline-block; box-shadow: 0 0 4px rgba(39,201,63,0.3);"></span>
                        </div>
                        <div class="file-name text-muted small" style="font-family: 'Consolas', monospace; font-size: 12px; color: #858585 !important;">esp8266_led_sensor.ino</div>
                        <button class="btn btn-sm text-light d-flex align-items-center gap-1" style="background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.05); border-radius: 6px; font-size: 11px; padding: 4px 10px; transition: 0.2s; cursor: pointer;" onmouseover="this.style.background='rgba(255,255,255,0.2)'" onmouseout="this.style.background='rgba(255,255,255,0.1)'" onclick="navigator.clipboard.writeText(document.getElementById('code-content-sensor').innerText); this.innerHTML='<i class=\'bi bi-check2\'></i> Tersalin'; setTimeout(() => this.innerHTML='<i class=\'bi bi-copy\'></i> Salin', 2000);">
                            <i class="bi bi-copy"></i> Salin
                        </button>
                    </div>
                    
                    <!-- Area Scroll Kode Custom -->
                    <style>
                        .custom-scrollbar::-webkit-scrollbar { width: 8px; height: 8px; }
                        .custom-scrollbar::-webkit-scrollbar-track { background: #1e1e1e; }
                        .custom-scrollbar::-webkit-scrollbar-thumb { background: #424242; border-radius: 4px; }
                        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #555; }
                    </style>

                    <pre class="p-4 m-0 custom-scrollbar" style="max-height: 450px; overflow-y: auto; overflow-x: auto; font-size: 13.5px; line-height: 1.65;"><code id="code-content-sensor" style="font-family: 'Consolas', 'Fira Code', 'Courier New', monospace; color: #d4d4d4;"><span style="color: #c586c0;">#include</span> <span style="color: #ce9178;">&lt;ESP8266WiFi.h&gt;</span>
<span style="color: #c586c0;">#include</span> <span style="color: #ce9178;">&lt;ESP8266HTTPClient.h&gt;</span>
<span style="color: #c586c0;">#include</span> <span style="color: #ce9178;">&lt;WiFiClientSecure.h&gt;</span>

<span style="color: #6a9955;">// --- 1. KONFIGURASI WIFI & SERVER ---</span>
<span style="color: #569cd6;">const char*</span> ssid = <span style="color: #ce9178;">"xieqa_router"</span>;            <span style="color: #6a9955;">// Sesuai file 1</span>
<span style="color: #569cd6;">const char*</span> password = <span style="color: #ce9178;">"11111111"</span>;     <span style="color: #6a9955;">// Sesuai file 1</span>
<span style="color: #569cd6;">const char*</span> host = <span style="color: #ce9178;">"xieqa.com"</span>;
<span style="color: #4ec9b0;">String</span> apiKey = <span style="color: #ce9178;">"sk-iot-d071690f8c42745892a05dda5da0fb89"</span>; <span style="color: #6a9955;">// API Key sama untuk kedua alat</span>

<span style="color: #6a9955;">// --- 2. KONFIGURASI ID ALAT (Wajib beda) ---</span>
<span style="color: #4ec9b0;">String</span> id_lampu = <span style="color: #ce9178;">"lampu_kamar"</span>;      <span style="color: #6a9955;">// ID untuk Relay</span>
<span style="color: #4ec9b0;">String</span> id_tanah = <span style="color: #ce9178;">"sensor_tanah"</span>;     <span style="color: #6a9955;">// ID untuk Sensor</span>

<span style="color: #6a9955;">// --- 3. PIN DEFINITION ---</span>
<span style="color: #569cd6;">const int</span> PIN_RELAY = D5; 
<span style="color: #569cd6;">const int</span> PIN_SENSOR = A0; 

<span style="color: #6a9955;">// --- 4. KALIBRASI SENSOR TANAH (SUDAH DIPERBAIKI) ---</span>
<span style="color: #6a9955;">// Berdasarkan data Bapak: Raw Kering = 663.</span>
<span style="color: #6a9955;">// Kita set AirValue 670 agar saat di udara terbaca 0% (Kering)</span>
<span style="color: #569cd6;">const int</span> AirValue = <span style="color: #b5cea8;">670</span>;    <span style="color: #6a9955;">// Nilai saat kering (Udara)</span>
<span style="color: #569cd6;">const int</span> WaterValue = <span style="color: #b5cea8;">350</span>;  <span style="color: #6a9955;">// Nilai saat basah (Air)</span>

<span style="color: #6a9955;">// --- 5. TIMER (PENGGANTI DELAY) ---</span>
<span style="color: #569cd6;">unsigned long</span> lastCheckLampu = <span style="color: #b5cea8;">0</span>;
<span style="color: #569cd6;">unsigned long</span> lastSendSensor = <span style="color: #b5cea8;">0</span>;

<span style="color: #569cd6;">void</span> <span style="color: #dcdcaa;">setup</span>() {
  Serial.<span style="color: #dcdcaa;">begin</span>(<span style="color: #b5cea8;">115200</span>);
  
  <span style="color: #6a9955;">// Setup Pin</span>
  <span style="color: #dcdcaa;">pinMode</span>(PIN_RELAY, OUTPUT);
  <span style="color: #6a9955;">// PENTING: Untuk Relay Active LOW, HIGH = Mati, LOW = Nyala.</span>
  <span style="color: #6a9955;">// Kita set HIGH dulu agar saat alat nyala, lampu tetap MATI.</span>
  <span style="color: #dcdcaa;">digitalWrite</span>(PIN_RELAY, HIGH); 

  <span style="color: #6a9955;">// Koneksi WiFi</span>
  WiFi.<span style="color: #dcdcaa;">begin</span>(ssid, password);
  Serial.<span style="color: #dcdcaa;">print</span>(<span style="color: #ce9178;">"Connecting to WiFi"</span>);
  <span style="color: #c586c0;">while</span> (WiFi.<span style="color: #dcdcaa;">status</span>() != WL_CONNECTED) {
    <span style="color: #dcdcaa;">delay</span>(<span style="color: #b5cea8;">500</span>);
    Serial.<span style="color: #dcdcaa;">print</span>(<span style="color: #ce9178;">"."</span>);
  }
  Serial.<span style="color: #dcdcaa;">println</span>(<span style="color: #ce9178;">" Connected!"</span>);
}

<span style="color: #569cd6;">void</span> <span style="color: #dcdcaa;">loop</span>() {
  <span style="color: #6a9955;">// Pastikan WiFi Connect</span>
  <span style="color: #c586c0;">if</span> (WiFi.<span style="color: #dcdcaa;">status</span>() == WL_CONNECTED) {
    <span style="color: #569cd6;">unsigned long</span> now = <span style="color: #dcdcaa;">millis</span>();

    <span style="color: #6a9955;">// --- TUGAS 1: CEK STATUS LAMPU (Tiap 1 Detik) ---</span>
    <span style="color: #c586c0;">if</span> (now - lastCheckLampu > <span style="color: #b5cea8;">1000</span>) {
      lastCheckLampu = now;
      <span style="color: #dcdcaa;">cekStatusLampu</span>();
    }

    <span style="color: #6a9955;">// --- TUGAS 2: KIRIM DATA SENSOR (Tiap 5 Detik) ---</span>
    <span style="color: #c586c0;">if</span> (now - lastSendSensor > <span style="color: #b5cea8;">5000</span>) {
      lastSendSensor = now;
      <span style="color: #dcdcaa;">bacaDanKirimSensor</span>();
    }
  }
}

<span style="color: #6a9955;">// --- FUNGSI 1: CEK LAMPU ---</span>
<span style="color: #569cd6;">void</span> <span style="color: #dcdcaa;">cekStatusLampu</span>() {
  <span style="color: #4ec9b0;">WiFiClientSecure</span> client;
  client.<span style="color: #dcdcaa;">setInsecure</span>();
  <span style="color: #4ec9b0;">HTTPClient</span> http;

  <span style="color: #4ec9b0;">String</span> url = <span style="color: #ce9178;">"https://"</span> + <span style="color: #4ec9b0;">String</span>(host) + <span style="color: #ce9178;">"/ai/api/iot_gateway.php?k="</span> + apiKey + <span style="color: #ce9178;">"&d="</span> + id_lampu;
  
  http.<span style="color: #dcdcaa;">setUserAgent</span>(<span style="color: #ce9178;">"Mozilla/5.0 (ESP8266-Lamp)"</span>);
  http.<span style="color: #dcdcaa;">begin</span>(client, url);
  
  <span style="color: #569cd6;">int</span> httpCode = http.<span style="color: #dcdcaa;">GET</span>();
  <span style="color: #c586c0;">if</span> (httpCode > <span style="color: #b5cea8;">0</span>) {
    <span style="color: #4ec9b0;">String</span> payload = http.<span style="color: #dcdcaa;">getString</span>();
    <span style="color: #6a9955;">// Logika Relay (Active Low)</span>
    <span style="color: #c586c0;">if</span> (payload == <span style="color: #ce9178;">"1"</span>) {
      <span style="color: #dcdcaa;">digitalWrite</span>(PIN_RELAY, LOW); <span style="color: #6a9955;">// NYALA (Active Low)</span>
    } <span style="color: #c586c0;">else</span> {
      <span style="color: #dcdcaa;">digitalWrite</span>(PIN_RELAY, HIGH);  <span style="color: #6a9955;">// MATI (Active Low)</span>
    }
  }
  http.<span style="color: #dcdcaa;">end</span>();
}

<span style="color: #6a9955;">// --- FUNGSI 2: BACA & KIRIM SENSOR ---</span>
<span style="color: #569cd6;">void</span> <span style="color: #dcdcaa;">bacaDanKirimSensor</span>() {
  <span style="color: #6a9955;">// 1. Baca Analog</span>
  <span style="color: #569cd6;">int</span> rawValue = <span style="color: #dcdcaa;">analogRead</span>(PIN_SENSOR);
  
  <span style="color: #6a9955;">// 2. Hitung Persen (Mapping Baru)</span>
  <span style="color: #569cd6;">int</span> persen = <span style="color: #dcdcaa;">map</span>(rawValue, AirValue, WaterValue, <span style="color: #b5cea8;">0</span>, <span style="color: #b5cea8;">100</span>);
  <span style="color: #c586c0;">if</span> (persen < <span style="color: #b5cea8;">0</span>) persen = <span style="color: #b5cea8;">0</span>;
  <span style="color: #c586c0;">if</span> (persen > <span style="color: #b5cea8;">100</span>) persen = <span style="color: #b5cea8;">100</span>;

  <span style="color: #6a9955;">// 3. Kirim ke Server</span>
  <span style="color: #4ec9b0;">WiFiClientSecure</span> client;
  client.<span style="color: #dcdcaa;">setInsecure</span>();
  <span style="color: #4ec9b0;">HTTPClient</span> http;

  <span style="color: #6a9955;">// URL Kirim Data (Pakai &v=...)</span>
  <span style="color: #4ec9b0;">String</span> nilai = <span style="color: #4ec9b0;">String</span>(persen) + <span style="color: #ce9178;">"%"</span>;
  nilai.<span style="color: #dcdcaa;">replace</span>(<span style="color: #ce9178;">"%"</span>, <span style="color: #ce9178;">"%25"</span>); <span style="color: #6a9955;">// Encode persen</span>
  
  <span style="color: #4ec9b0;">String</span> url = <span style="color: #ce9178;">"https://"</span> + <span style="color: #4ec9b0;">String</span>(host) + <span style="color: #ce9178;">"/ai/api/iot_gateway.php?k="</span> + apiKey + <span style="color: #ce9178;">"&d="</span> + id_tanah + <span style="color: #ce9178;">"&v="</span> + nilai;
  
  http.<span style="color: #dcdcaa;">setUserAgent</span>(<span style="color: #ce9178;">"Mozilla/5.0 (ESP8266-Soil)"</span>);
  http.<span style="color: #dcdcaa;">begin</span>(client, url);
  
  <span style="color: #569cd6;">int</span> httpCode = http.<span style="color: #dcdcaa;">GET</span>();
  <span style="color: #c586c0;">if</span> (httpCode > <span style="color: #b5cea8;">0</span>) {
    Serial.<span style="color: #dcdcaa;">println</span>(<span style="color: #ce9178;">"Sensor Terkirim: "</span> + <span style="color: #4ec9b0;">String</span>(persen) + <span style="color: #ce9178;">"% (Raw: "</span> + <span style="color: #4ec9b0;">String</span>(rawValue) + <span style="color: #ce9178;">")"</span>);
  } <span style="color: #c586c0;">else</span> {
    Serial.<span style="color: #dcdcaa;">println</span>(<span style="color: #ce9178;">"Gagal Kirim Sensor"</span>);
  }
  http.<span style="color: #dcdcaa;">end</span>();
}</code></pre>
                        </div>
                    </div>
                    
                    <!-- TAB 1: LED SAJA -->
                    <div class="tab-pane fade" id="led-only" role="tabpanel">
                        <div class="d-flex justify-content-end mb-2">
                            <a href="esp8266_led_only.ino" download="esp8266_led_only.ino" class="btn btn-primary btn-sm rounded-pill px-4 shadow-sm" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none;">
                                <i class="bi bi-cloud-arrow-down-fill me-1"></i> Unduh .ino (LED Saja)
                            </a>
                        </div>
                        <div class="code-editor-container" style="background: #1e1e1e; border-radius: 12px; overflow: hidden; box-shadow: 0 10px 25px rgba(0,0,0,0.1);">
                            <div class="editor-header d-flex justify-content-between align-items-center px-3 py-2" style="background: #2d2d2d; border-bottom: 1px solid #404040;">
                                <div class="mac-dots d-flex gap-2">
                                    <span style="width: 12px; height: 12px; background: #ff5f56; border-radius: 50%; display: inline-block; box-shadow: 0 0 4px rgba(255,95,86,0.3);"></span>
                                    <span style="width: 12px; height: 12px; background: #ffbd2e; border-radius: 50%; display: inline-block; box-shadow: 0 0 4px rgba(255,189,46,0.3);"></span>
                                    <span style="width: 12px; height: 12px; background: #27c93f; border-radius: 50%; display: inline-block; box-shadow: 0 0 4px rgba(39,201,63,0.3);"></span>
                                </div>
                                <div class="file-name text-muted small" style="font-family: 'Consolas', monospace; font-size: 12px; color: #858585 !important;">esp8266_led_only.ino</div>
                                <button class="btn btn-sm text-light d-flex align-items-center gap-1" style="background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.05); border-radius: 6px; font-size: 11px; padding: 4px 10px; transition: 0.2s; cursor: pointer;" onmouseover="this.style.background='rgba(255,255,255,0.2)'" onmouseout="this.style.background='rgba(255,255,255,0.1)'" onclick="navigator.clipboard.writeText(document.getElementById('code-content-led').innerText); this.innerHTML='<i class=\'bi bi-check2\'></i> Tersalin'; setTimeout(() => this.innerHTML='<i class=\'bi bi-copy\'></i> Salin', 2000);">
                                    <i class="bi bi-copy"></i> Salin
                                </button>
                            </div>
                            <pre class="p-4 m-0 custom-scrollbar" style="max-height: 450px; overflow-y: auto; overflow-x: auto; font-size: 13.5px; line-height: 1.65;"><code id="code-content-led" style="font-family: 'Consolas', 'Fira Code', 'Courier New', monospace; color: #d4d4d4;"><span style="color: #c586c0;">#include</span> <span style="color: #ce9178;">&lt;ESP8266WiFi.h&gt;</span>
<span style="color: #c586c0;">#include</span> <span style="color: #ce9178;">&lt;ESP8266HTTPClient.h&gt;</span>
<span style="color: #c586c0;">#include</span> <span style="color: #ce9178;">&lt;WiFiClientSecure.h&gt;</span> 

<span style="color: #569cd6;">const char*</span> ssid = <span style="color: #ce9178;">"xieqa_router"</span>;
<span style="color: #569cd6;">const char*</span> password = <span style="color: #ce9178;">"11111111"</span>;

<span style="color: #569cd6;">const char*</span> host = <span style="color: #ce9178;">"xieqa.com"</span>; 
<span style="color: #4ec9b0;">String</span> apiKey = <span style="color: #ce9178;">"sk-iot-ae668322907d9cee9a9cf1bd8225609f"</span>; 
<span style="color: #4ec9b0;">String</span> deviceID = <span style="color: #ce9178;">"lampu_kamar"</span>;        

<span style="color: #569cd6;">const int</span> RELAY_PIN = D5; 

<span style="color: #569cd6;">void</span> <span style="color: #dcdcaa;">setup</span>() {
  Serial.<span style="color: #dcdcaa;">begin</span>(<span style="color: #b5cea8;">115200</span>);
  <span style="color: #dcdcaa;">pinMode</span>(RELAY_PIN, OUTPUT);
  <span style="color: #dcdcaa;">digitalWrite</span>(RELAY_PIN, LOW); 

  WiFi.<span style="color: #dcdcaa;">begin</span>(ssid, password);
  Serial.<span style="color: #dcdcaa;">print</span>(<span style="color: #ce9178;">"Connecting"</span>);
  <span style="color: #c586c0;">while</span> (WiFi.<span style="color: #dcdcaa;">status</span>() != WL_CONNECTED) {
    <span style="color: #dcdcaa;">delay</span>(<span style="color: #b5cea8;">500</span>);
    Serial.<span style="color: #dcdcaa;">print</span>(<span style="color: #ce9178;">"."</span>);
  }
  Serial.<span style="color: #dcdcaa;">println</span>(<span style="color: #ce9178;">" Connected!"</span>);
}

<span style="color: #569cd6;">void</span> <span style="color: #dcdcaa;">loop</span>() {
  <span style="color: #c586c0;">if</span> (WiFi.<span style="color: #dcdcaa;">status</span>() == WL_CONNECTED) {
    
    <span style="color: #4ec9b0;">WiFiClientSecure</span> client;
    client.<span style="color: #dcdcaa;">setInsecure</span>(); <span style="color: #6a9955;">// Wajib untuk HTTPS</span>
    
    <span style="color: #4ec9b0;">HTTPClient</span> http;

    <span style="color: #4ec9b0;">String</span> url = <span style="color: #ce9178;">"https://"</span> + <span style="color: #4ec9b0;">String</span>(host) + <span style="color: #ce9178;">"/ai/api/iot_gateway.php?k="</span> + apiKey + <span style="color: #ce9178;">"&d="</span> + deviceID;
    
    <span style="color: #6a9955;">// --- TAMBAHAN PENTING (Agar tidak dianggap BOT) ---</span>
    http.<span style="color: #dcdcaa;">setUserAgent</span>(<span style="color: #ce9178;">"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"</span>);
    
    Serial.<span style="color: #dcdcaa;">print</span>(<span style="color: #ce9178;">"Requesting: "</span>);
    Serial.<span style="color: #dcdcaa;">println</span>(url);

    http.<span style="color: #dcdcaa;">begin</span>(client, url); 
    <span style="color: #569cd6;">int</span> httpCode = http.<span style="color: #dcdcaa;">GET</span>();

    <span style="color: #c586c0;">if</span> (httpCode > <span style="color: #b5cea8;">0</span>) {
      <span style="color: #4ec9b0;">String</span> payload = http.<span style="color: #dcdcaa;">getString</span>();
      Serial.<span style="color: #dcdcaa;">println</span>(<span style="color: #ce9178;">"Response Code: "</span> + <span style="color: #4ec9b0;">String</span>(httpCode));
      Serial.<span style="color: #dcdcaa;">println</span>(<span style="color: #ce9178;">"Payload: "</span> + payload);

      <span style="color: #c586c0;">if</span> (payload == <span style="color: #ce9178;">"1"</span>) {
        <span style="color: #dcdcaa;">digitalWrite</span>(RELAY_PIN, HIGH);
      } <span style="color: #c586c0;">else</span> {
        <span style="color: #dcdcaa;">digitalWrite</span>(RELAY_PIN, LOW);
      }
    } <span style="color: #c586c0;">else</span> {
      Serial.<span style="color: #dcdcaa;">print</span>(<span style="color: #ce9178;">"Error HTTP: "</span>);
      Serial.<span style="color: #dcdcaa;">println</span>(httpCode);
    }
    http.<span style="color: #dcdcaa;">end</span>();
  }
  
  <span style="color: #dcdcaa;">delay</span>(<span style="color: #b5cea8;">1000</span>); 
}</code></pre>
                        </div>
                    </div>
                    
                    <!-- TAB 3: SENSOR JANTUNG -->
                    <div class="tab-pane fade" id="heart-sensor" role="tabpanel">
                        <div class="d-flex justify-content-end mb-2">
                            <a href="esp8266_heart_sensor.ino" download="esp8266_heart_sensor.ino" class="btn btn-primary btn-sm rounded-pill px-4 shadow-sm" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none;">
                                <i class="bi bi-cloud-arrow-down-fill me-1"></i> Unduh .ino (Sensor Jantung)
                            </a>
                        </div>
                        <div class="code-editor-container" style="background: #1e1e1e; border-radius: 12px; overflow: hidden; box-shadow: 0 10px 25px rgba(0,0,0,0.1);">
                            <div class="editor-header d-flex justify-content-between align-items-center px-3 py-2" style="background: #2d2d2d; border-bottom: 1px solid #404040;">
                                <div class="mac-dots d-flex gap-2">
                                    <span style="width: 12px; height: 12px; background: #ff5f56; border-radius: 50%; display: inline-block; box-shadow: 0 0 4px rgba(255,95,86,0.3);"></span>
                                    <span style="width: 12px; height: 12px; background: #ffbd2e; border-radius: 50%; display: inline-block; box-shadow: 0 0 4px rgba(255,189,46,0.3);"></span>
                                    <span style="width: 12px; height: 12px; background: #27c93f; border-radius: 50%; display: inline-block; box-shadow: 0 0 4px rgba(39,201,63,0.3);"></span>
                                </div>
                                <div class="file-name text-muted small" style="font-family: 'Consolas', monospace; font-size: 12px; color: #858585 !important;">esp8266_heart_sensor.ino</div>
                                <button class="btn btn-sm text-light d-flex align-items-center gap-1" style="background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.05); border-radius: 6px; font-size: 11px; padding: 4px 10px; transition: 0.2s; cursor: pointer;" onmouseover="this.style.background='rgba(255,255,255,0.2)'" onmouseout="this.style.background='rgba(255,255,255,0.1)'" onclick="navigator.clipboard.writeText(document.getElementById('code-content-heart').innerText); this.innerHTML='<i class=\'bi bi-check2\'></i> Tersalin'; setTimeout(() => this.innerHTML='<i class=\'bi bi-copy\'></i> Salin', 2000);">
                                    <i class="bi bi-copy"></i> Salin
                                </button>
                            </div>
                            <pre class="p-4 m-0 custom-scrollbar" style="max-height: 450px; overflow-y: auto; overflow-x: auto; font-size: 13.5px; line-height: 1.65;"><code id="code-content-heart" style="font-family: 'Consolas', 'Fira Code', 'Courier New', monospace; color: #d4d4d4;"><span style="color: #c586c0;">#include</span> <span style="color: #ce9178;">&lt;ESP8266WiFi.h&gt;</span>
<span style="color: #c586c0;">#include</span> <span style="color: #ce9178;">&lt;ESP8266HTTPClient.h&gt;</span>
<span style="color: #c586c0;">#include</span> <span style="color: #ce9178;">&lt;WiFiClientSecure.h&gt;</span>
<span style="color: #c586c0;">#include</span> <span style="color: #ce9178;">&lt;Wire.h&gt;</span>
<span style="color: #c586c0;">#include</span> <span style="color: #ce9178;">"MAX30105.h"</span>
<span style="color: #c586c0;">#include</span> <span style="color: #ce9178;">"heartRate.h"</span>

<span style="color: #6a9955;">// --- 1. KONFIGURASI WIFI & SERVER ---</span>
<span style="color: #569cd6;">const char*</span> ssid = <span style="color: #ce9178;">"xieqa_router"</span>;
<span style="color: #569cd6;">const char*</span> password = <span style="color: #ce9178;">"11111111"</span>;
<span style="color: #569cd6;">const char*</span> host = <span style="color: #ce9178;">"xieqa.com"</span>;
<span style="color: #4ec9b0;">String</span> apiKey = <span style="color: #ce9178;">"sk-iot-d071690f8c42745892a05dda5da0fb89"</span>;
<span style="color: #4ec9b0;">String</span> id_jantung = <span style="color: #ce9178;">"sensor_jantung"</span>;

<span style="color: #6a9955;">// --- 2. OBJEK SENSOR & VARIABEL ---</span>
<span style="color: #4ec9b0;">MAX30105</span> particleSensor;

<span style="color: #569cd6;">const byte</span> RATE_SIZE = <span style="color: #b5cea8;">10</span>;
<span style="color: #569cd6;">byte</span> rates[RATE_SIZE];
<span style="color: #569cd6;">byte</span> rateSpot = <span style="color: #b5cea8;">0</span>;
<span style="color: #569cd6;">long</span> lastBeat = <span style="color: #b5cea8;">0</span>;
<span style="color: #569cd6;">float</span> beatsPerMinute;
<span style="color: #569cd6;">int</span> beatAvg = <span style="color: #b5cea8;">0</span>;
<span style="color: #569cd6;">bool</span> fingerDetected = <span style="color: #569cd6;">false</span>;
<span style="color: #569cd6;">byte</span> validBeats = <span style="color: #b5cea8;">0</span>;

<span style="color: #6a9955;">// --- 3. VARIABEL KALIBRASI ---</span>
<span style="color: #569cd6;">const long</span> FINGER_THRESHOLD = <span style="color: #b5cea8;">40000</span>;
<span style="color: #569cd6;">byte</span> ledBrightness = <span style="color: #b5cea8;">0x3C</span>;
<span style="color: #569cd6;">byte</span> sampleAverage = <span style="color: #b5cea8;">1</span>;
<span style="color: #569cd6;">byte</span> ledMode = <span style="color: #b5cea8;">2</span>;
<span style="color: #569cd6;">int</span> sampleRate = <span style="color: #b5cea8;">400</span>;
<span style="color: #569cd6;">int</span> pulseWidth = <span style="color: #b5cea8;">411</span>;       
<span style="color: #569cd6;">int</span> adcRange = <span style="color: #b5cea8;">4096</span>;

<span style="color: #569cd6;">unsigned long</span> lastSend = <span style="color: #b5cea8;">0</span>;
<span style="color: #569cd6;">const long</span> interval = <span style="color: #b5cea8;">5000</span>;

<span style="color: #569cd6;">void</span> <span style="color: #dcdcaa;">setup</span>() {
  Serial.<span style="color: #dcdcaa;">begin</span>(<span style="color: #b5cea8;">115200</span>);
  
  Wire.<span style="color: #dcdcaa;">begin</span>(<span style="color: #b5cea8;">4</span>, <span style="color: #b5cea8;">5</span>); 
  Wire.<span style="color: #dcdcaa;">setClock</span>(<span style="color: #b5cea8;">400000</span>);

  WiFi.<span style="color: #dcdcaa;">mode</span>(WIFI_STA);
  WiFi.<span style="color: #dcdcaa;">begin</span>(ssid, password);
  Serial.<span style="color: #dcdcaa;">print</span>(<span style="color: #ce9178;">"Connecting WiFi"</span>);
  <span style="color: #c586c0;">while</span> (WiFi.<span style="color: #dcdcaa;">status</span>() != WL_CONNECTED) {
    <span style="color: #dcdcaa;">delay</span>(<span style="color: #b5cea8;">500</span>);
    Serial.<span style="color: #dcdcaa;">print</span>(<span style="color: #ce9178;">"."</span>);
  }
  Serial.<span style="color: #dcdcaa;">println</span>(<span style="color: #ce9178;">"\nWiFi Connected!"</span>);

  <span style="color: #c586c0;">if</span> (!particleSensor.<span style="color: #dcdcaa;">begin</span>(Wire, I2C_SPEED_FAST)) {
    Serial.<span style="color: #dcdcaa;">println</span>(<span style="color: #ce9178;">"MAX30105 tidak ditemukan!"</span>);
    <span style="color: #c586c0;">while</span> (<span style="color: #b5cea8;">1</span>);
  }

  particleSensor.<span style="color: #dcdcaa;">setup</span>(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange);
  particleSensor.<span style="color: #dcdcaa;">setPulseAmplitudeGreen</span>(<span style="color: #b5cea8;">0</span>);
  
  Serial.<span style="color: #dcdcaa;">println</span>(<span style="color: #ce9178;">"Sistem Siap..."</span>);
}

<span style="color: #569cd6;">void</span> <span style="color: #dcdcaa;">loop</span>() {
  <span style="color: #569cd6;">long</span> irValue = particleSensor.<span style="color: #dcdcaa;">getIR</span>();

  <span style="color: #c586c0;">if</span> (irValue > FINGER_THRESHOLD) {
    <span style="color: #c586c0;">if</span> (<span style="color: #dcdcaa;">checkForBeat</span>(irValue) == <span style="color: #569cd6;">true</span>) {
      <span style="color: #569cd6;">long</span> delta = <span style="color: #dcdcaa;">millis</span>() - lastBeat;
      lastBeat = <span style="color: #dcdcaa;">millis</span>();

      beatsPerMinute = <span style="color: #b5cea8;">60</span> / (delta / <span style="color: #b5cea8;">1000.0</span>);

      <span style="color: #c586c0;">if</span> (beatsPerMinute < <span style="color: #b5cea8;">180</span> &amp;&amp; beatsPerMinute > <span style="color: #b5cea8;">40</span>) {
        rates[rateSpot++] = (<span style="color: #569cd6;">byte</span>)beatsPerMinute;
        rateSpot %= RATE_SIZE;

        <span style="color: #c586c0;">if</span> (validBeats < RATE_SIZE) validBeats++;

        beatAvg = <span style="color: #b5cea8;">0</span>;
        <span style="color: #c586c0;">for</span> (<span style="color: #569cd6;">byte</span> x = <span style="color: #b5cea8;">0</span>; x < validBeats; x++) { 
          beatAvg += rates[x];
        }
        beatAvg /= validBeats;

        Serial.<span style="color: #dcdcaa;">printf</span>(<span style="color: #ce9178;">"BPM: %.1f | Avg: %d\n"</span>, beatsPerMinute, beatAvg);
      }
    }
    fingerDetected = <span style="color: #569cd6;">true</span>;

  } <span style="color: #c586c0;">else</span> {
    fingerDetected = <span style="color: #569cd6;">false</span>;
    beatAvg = <span style="color: #b5cea8;">0</span>;
    rateSpot = <span style="color: #b5cea8;">0</span>;
    validBeats = <span style="color: #b5cea8;">0</span>;
    <span style="color: #dcdcaa;">memset</span>(rates, <span style="color: #b5cea8;">0</span>, <span style="color: #569cd6;">sizeof</span>(rates));
  }

  <span style="color: #c586c0;">if</span> (<span style="color: #dcdcaa;">millis</span>() - lastSend > interval) {
    lastSend = <span style="color: #dcdcaa;">millis</span>();

    <span style="color: #c586c0;">if</span> (WiFi.<span style="color: #dcdcaa;">status</span>() == WL_CONNECTED) {
      <span style="color: #c586c0;">if</span> (fingerDetected &amp;&amp; beatAvg >= <span style="color: #b5cea8;">40</span>) {
        <span style="color: #dcdcaa;">kirimData</span>(id_jantung, <span style="color: #4ec9b0;">String</span>(beatAvg));
      }
    } <span style="color: #c586c0;">else</span> {
      WiFi.<span style="color: #dcdcaa;">reconnect</span>(); 
    }
  }
}

<span style="color: #569cd6;">void</span> <span style="color: #dcdcaa;">kirimData</span>(<span style="color: #4ec9b0;">String</span> devID, <span style="color: #4ec9b0;">String</span> nilai) {
  <span style="color: #c586c0;">if</span> (nilai.<span style="color: #dcdcaa;">toInt</span>() < <span style="color: #b5cea8;">40</span>) <span style="color: #c586c0;">return</span>;

  <span style="color: #4ec9b0;">WiFiClientSecure</span> client;
  client.<span style="color: #dcdcaa;">setInsecure</span>();
  <span style="color: #4ec9b0;">HTTPClient</span> http;

  <span style="color: #4ec9b0;">String</span> url = <span style="color: #ce9178;">"https://"</span> + <span style="color: #4ec9b0;">String</span>(host) + <span style="color: #ce9178;">"/ai/api/iot_gateway.php?k="</span> + apiKey + <span style="color: #ce9178;">"&amp;d="</span> + devID + <span style="color: #ce9178;">"&amp;v="</span> + nilai;
  
  http.<span style="color: #dcdcaa;">setTimeout</span>(<span style="color: #b5cea8;">1500</span>);

  <span style="color: #c586c0;">if</span> (http.<span style="color: #dcdcaa;">begin</span>(client, url)) {
    <span style="color: #569cd6;">int</span> httpCode = http.<span style="color: #dcdcaa;">GET</span>();
    <span style="color: #c586c0;">if</span> (httpCode > <span style="color: #b5cea8;">0</span>) {
      Serial.<span style="color: #dcdcaa;">printf</span>(<span style="color: #ce9178;">"Terkirim BPM: %s\n"</span>, nilai.<span style="color: #dcdcaa;">c_str</span>());
    }
    http.<span style="color: #dcdcaa;">end</span>();
  }
}</code></pre>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalAddDev" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold">Tambah Perangkat IoT</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <div class="alert alert-info small">
                        Daftarkan alat di sini, lalu masukkan ID-nya ke kodingan Arduino.
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">Nama Alat (Label)</label>
                        <input type="text" name="dev_label" class="form-control" placeholder="Contoh: Sensor Jantung" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">ID Unik (Untuk Koding Arduino)</label>
                        <input type="text" name="dev_id" class="form-control" placeholder="Contoh: sensor_jantung" required>
                        <small class="text-muted">Gunakan huruf kecil, tanpa spasi (spasi akan otomatis diubah jadi _)</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" name="add_device" class="btn btn-primary">Simpan ke Database</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>