<?php
session_start();
require_once 'config/database.php';

// Layout variables
$page_title = 'DMAppsESP - Cihaz Düzenle';
$breadcrumb_title = 'Cihaz Düzenle';
$current_page = 'devices';
$extra_css = '<style>
    .form-section {
        background: white;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .sensor-item {
        border: 1px solid #ddd;
        border-radius: 5px;
        padding: 15px;
        margin-bottom: 10px;
        background: #f8f9fa;
    }
    .sensor-item .remove-btn {
        float: right;
        color: #dc3545;
        cursor: pointer;
    }
    .config-editor {
        background: #f8f9fa;
        border: 1px solid #ddd;
        border-radius: 5px;
        padding: 10px;
        font-family: monospace;
        min-height: 100px;
    }
    .status-indicator {
        display: inline-block;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        margin-right: 5px;
    }
    .status-online { background-color: #28a745; }
    .status-offline { background-color: #dc3545; }
    .status-error { background-color: #ffc107; }
</style>';

$extra_js = '<script>
let sensorCount = 0;

function addSensor() {
    sensorCount++;
    const sensorHtml = `
        <div class="sensor-item" id="sensor-${sensorCount}">
            <span class="remove-btn" onclick="removeSensor(${sensorCount})">✕</span>
            <div class="row">
                <div class="col-md-3">
                    <label class="form-label">Sensör Kodu:</label>
                    <input type="text" class="form-control" name="sensors[${sensorCount}][sensor_code]" placeholder="Örn: DHT22_TEMP">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Sensör Tipi:</label>
                    <select class="form-select" name="sensors[${sensorCount}][sensor_type]">
                        <option value="">Seçin...</option>
                        <option value="temperature">Sıcaklık</option>
                        <option value="humidity">Nem</option>
                        <option value="pressure">Basınç</option>
                        <option value="motion">Hareket</option>
                        <option value="light">Işık</option>
                        <option value="gas">Gaz</option>
                        <option value="voltage">Voltaj</option>
                        <option value="current">Akım</option>
                        <option value="power">Güç</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Pin:</label>
                    <input type="number" class="form-control" name="sensors[${sensorCount}][pin]" min="0" max="39">
                </div>
                <div class="col-md-2">
                    <label class="form-label">Aktif:</label>
                    <div class="form-check mt-2">
                        <input class="form-check-input" type="checkbox" name="sensors[${sensorCount}][enabled]" checked>
                        <label class="form-check-label">Aktif</label>
                    </div>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Rol:</label>
                    <select class="form-select" name="sensors[${sensorCount}][role]">
                        <option value="user">User</option>
                        <option value="admin">Admin</option>
                    </select>
                </div>
            </div>
            <div class="row mt-2">
                <div class="col-12">
                    <label class="form-label">Konfigürasyon (JSON):</label>
                    <textarea class="form-control config-editor" name="sensors[${sensorCount}][config]" rows="2" placeholder=\'{"interval": 5000, "threshold": 25}\'></textarea>
                </div>
            </div>
        </div>
    `;
    
    document.getElementById("sensorsContainer").insertAdjacentHTML("beforeend", sensorHtml);
}

function removeSensor(id) {
    const element = document.getElementById("sensor-" + id);
    if (element) {
        element.remove();
    }
}

function validateForm() {
    const deviceName = document.getElementById("deviceName").value;
    if (!deviceName.trim()) {
        alert("Cihaz adı boş olamaz!");
        return false;
    }
    
    // JSON konfigürasyonlarını doğrula
    const configs = document.querySelectorAll(".config-editor");
    for (let config of configs) {
        if (config.value.trim()) {
            try {
                JSON.parse(config.value);
            } catch (e) {
                alert("JSON konfigürasyonu geçersiz: " + e.message);
                return false;
            }
        }
    }
    
    return true;
}

function testConnection() {
    const deviceId = document.getElementById(\'deviceId\').value;
    
    fetch(\'api/devices.php?action=test_connection&device_id=\' + deviceId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById(\'connectionStatus\').innerHTML = 
                    \'<span class="status-indicator status-online"></span>Bağlantı Başarılı\';
            } else {
                document.getElementById(\'connectionStatus\').innerHTML = 
                    \'<span class="status-indicator status-offline"></span>Bağlantı Başarısız: \' + data.message;
            }
        })
        .catch(error => {
            document.getElementById(\'connectionStatus\').innerHTML = 
                \'<span class="status-indicator status-error"></span>Hata: \' + error.message;
        });
}

function saveDevice() {
    if (!validateForm()) {
        return;
    }
    
    const formData = new FormData(document.getElementById(\'deviceForm\'));
    
    fetch(\'api/devices.php?action=update\', {
        method: \'POST\',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(\'Cihaz başarıyla güncellendi!\');
            window.location.href = \'devices.php\';
        } else {
            alert(\'Hata: \' + data.message);
        }
    })
    .catch(error => {
        alert(\'Hata: \' + error.message);
    });
}
</script>';

// Cihaz bilgilerini getir
$device_id = $_GET['id'] ?? 0;
$device = null;

if ($device_id > 0) {
    $stmt = $con->prepare("SELECT * FROM devices WHERE id = ?");
    $stmt->bind_param("i", $device_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $device = $result->fetch_assoc();
    }
}

if (!$device) {
    header('Location: devices.php');
    exit;
}

require_once 'layouts/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1 class="h3 mb-4">Cihaz Düzenle: <?php echo htmlspecialchars($device['name']); ?></h1>
            
            <form id="deviceForm" method="post" onsubmit="return false;">
                <input type="hidden" name="device_id" value="<?php echo $device_id; ?>">
                
                <!-- Temel Bilgiler -->
                <div class="form-section">
                    <h5>Temel Bilgiler</h5>
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label">Cihaz Adı:</label>
                            <input type="text" class="form-control" id="deviceName" name="name" value="<?php echo htmlspecialchars($device['name']); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Açıklama:</label>
                            <input type="text" class="form-control" name="description" value="<?php echo htmlspecialchars($device['description']); ?>">
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-4">
                            <label class="form-label">Cihaz ID:</label>
                            <input type="text" class="form-control" id="deviceId" value="<?php echo htmlspecialchars($device['device_id']); ?>" readonly>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">ESP Model:</label>
                            <select class="form-select" name="esp_model">
                                <option value="ESP32" <?php echo $device['esp_model'] == 'ESP32' ? 'selected' : ''; ?>>ESP32</option>
                                <option value="ESP32-S2" <?php echo $device['esp_model'] == 'ESP32-S2' ? 'selected' : ''; ?>>ESP32-S2</option>
                                <option value="ESP32-S3" <?php echo $device['esp_model'] == 'ESP32-S3' ? 'selected' : ''; ?>>ESP32-S3</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Durum:</label>
                            <div id="connectionStatus">
                                <span class="status-indicator status-<?php echo $device['status']; ?>"></span>
                                <?php echo ucfirst($device['status']); ?>
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-primary mt-2" onclick="testConnection()">Bağlantı Test</button>
                        </div>
                    </div>
                </div>
                
                <!-- Konfigürasyon -->
                <div class="form-section">
                    <h5>Cihaz Konfigürasyonu</h5>
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label">Mevcut Mod:</label>
                            <select class="form-select" name="current_mode">
                                <option value="SETUP" <?php echo $device['current_mode'] == 'SETUP' ? 'selected' : ''; ?>>Setup</option>
                                <option value="PROVISION" <?php echo $device['current_mode'] == 'PROVISION' ? 'selected' : ''; ?>>Provision</option>
                                <option value="ONLINE" <?php echo $device['current_mode'] == 'ONLINE' ? 'selected' : ''; ?>>Online</option>
                                <option value="MOTOR_CONTROL" <?php echo $device['current_mode'] == 'MOTOR_CONTROL' ? 'selected' : ''; ?>>Motor Control</option>
                                <option value="PROTECTION" <?php echo $device['current_mode'] == 'PROTECTION' ? 'selected' : ''; ?>>Protection</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Firmware Versiyonu:</label>
                            <input type="text" class="form-control" name="firmware_version" value="<?php echo htmlspecialchars($device['firmware_version']); ?>">
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-12">
                            <label class="form-label">Genel Konfigürasyon (JSON):</label>
                            <textarea class="form-control config-editor" name="config" rows="4"><?php echo htmlspecialchars($device['config'] ?? ''); ?></textarea>
                        </div>
                    </div>
                </div>
                
                <!-- Sensörler -->
                <div class="form-section">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5>Sensörler</h5>
                        <button type="button" class="btn btn-primary" onclick="addSensor()">+ Sensör Ekle</button>
                    </div>
                    <div id="sensorsContainer">
                        <!-- Sensörler JavaScript ile eklenecek -->
                    </div>
                </div>
                
                <!-- Butonlar -->
                <div class="row">
                    <div class="col-12">
                        <button type="button" class="btn btn-primary" onclick="saveDevice()">Kaydet</button>
                        <a href="devices.php" class="btn btn-secondary">İptal</a>
                        <a href="device_detail.php?id=<?php echo $device_id; ?>" class="btn btn-info">Detaylar</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<?php require_once 'layouts/footer.php'; ?>
