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

// Get user info
$user_id = $_SESSION['user_id'];
$sql = "SELECT username, email, role FROM users WHERE id = $user_id";
$result = $con->query($sql);
$user = $result ? $result->fetch_assoc() : null;

// If user not found, create empty user array to prevent sidebar errors
if (!$user) {
    $user = [
        'username' => 'Unknown',
        'email' => '',
        'role' => 'user'
    ];
}

// Get device ID
$device_id = $_GET['id'] ?? 0;
if (!$device_id) {
    header('Location: devices.php');
    exit();
}

// Get device details (only owner can see)
$device_sql = "SELECT * FROM devices WHERE id = $device_id AND owner_id = $user_id";
$device_result = $con->query($device_sql);
$device = $device_result ? $device_result->fetch_assoc() : null;

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

// Get sensor data
$sensor_sql = "SELECT * FROM sensor_data WHERE device_id = $device_id ORDER BY timestamp DESC LIMIT 50";
$sensor_result = $con->query($sensor_sql);
$sensor_data = $sensor_result ? $sensor_result->fetch_all(MYSQLI_ASSOC) : [];

// Layout variables
$page_title = 'Cihaz Detayı';
$breadcrumb_title = 'Cihaz Detayı';
$current_page = 'devices';
$extra_css = '<link rel="stylesheet" href="assets/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">';
$page_scripts = '<script src="assets/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="assets/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>';
?>

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

<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <?php require_once 'layouts/navbar.php'; ?>
    <?php require_once 'layouts/sidebar.php'; ?>

    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <?php require_once 'layouts/header_dashboard.php'; ?>

        <!-- Main content -->
        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-microchip mr-1"></i>
                                <?php echo htmlspecialchars($device['device_name']); ?>
                            </h3>
                            <div class="card-tools">
                                <a href="devices.php" class="btn btn-secondary btn-sm">
                                    <i class="fas fa-arrow-left"></i> Geri Dön
                                </a>
                                <a href="edit_device.php?id=<?php echo $device['id']; ?>" class="btn btn-warning btn-sm">
                                    <i class="fas fa-cog"></i> Düzenle
                                </a>
                            </div>
                        </div>
                        
                        <div class="card-body">
                            <!-- Device Info -->
                            <div class="row mb-4">
                                <div class="col-md-6">
                                    <h5>Cihaz Bilgileri</h5>
                                    <table class="table table-bordered">
                                        <tr>
                                            <th style="width: 150px;">Cihaz Adı</th>
                                            <td><?php echo htmlspecialchars($device['device_name']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Device ID</th>
                                            <td><code><?php echo htmlspecialchars($device['device_id']); ?></code></td>
                                        </tr>
                                        <tr>
                                            <th>Durum</th>
                                            <td>
                                                <?php if ($device['status'] === 'online'): ?>
                                                    <span class="badge badge-success">Online</span>
                                                <?php else: ?>
                                                    <span class="badge badge-danger">Offline</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th>Ekran Tipi</th>
                                            <td><?php echo htmlspecialchars($device['screen_type'] ?? 'Bilinmiyor'); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Konum</th>
                                            <td><?php echo htmlspecialchars($device['location'] ?? '-'); ?></td>
                                        </tr>
                                        <tr>
                                            <th>Son Aktivite</th>
                                            <td><?php echo $device['last_activity'] ? date('d.m.Y H:i', strtotime($device['last_activity'])) : '-'; ?></td>
                                        </tr>
                                    </table>
                                </div>
                                <div class="col-md-6">
                                    <h5>Kontrol Paneli</h5>
                                    <div class="row">
                                        <div class="col-6 mb-3">
                                            <button class="btn btn-success btn-block" onclick="sendCommand('restart')">
                                                <i class="fas fa-redo"></i> Yeniden Başlat
                                            </button>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <button class="btn btn-warning btn-block" onclick="sendCommand('reset')">
                                                <i class="fas fa-undo"></i> Sıfırla
                                            </button>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <button class="btn btn-info btn-block" onclick="sendCommand('ping')">
                                                <i class="fas fa-wifi"></i> Ping
                                            </button>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <button class="btn btn-danger btn-block" onclick="sendCommand('shutdown')">
                                                <i class="fas fa-power-off"></i> Kapat
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Sensor Data -->
                            <h5>Sensör Verileri</h5>
                            <table id="sensorDataTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>Zaman</th>
                                        <th>Sensör</th>
                                        <th>Değer</th>
                                        <th>Birim</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($sensor_data as $sensor): ?>
                                    <tr>
                                        <td><?php echo date('d.m.Y H:i:s', strtotime($sensor['timestamp'])); ?></td>
                                        <td><?php echo htmlspecialchars($sensor['sensor_id']); ?></td>
                                        <td><?php echo htmlspecialchars($sensor['value']); ?></td>
                                        <td><?php echo htmlspecialchars($sensor['unit'] ?? ''); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#sensorDataTable').DataTable({
        "responsive": true,
        "lengthChange": false,
        "autoWidth": false,
        "ordering": true,
        "info": true,
        "paging": true,
        "search": true,
        "order": [[0, "desc"]],
        "language": {
            "search": "Ara:",
            "lengthMenu": "Show _MENU_ entries",
            "info": "Showing _START_ to _END_ of _TOTAL_ entries",
            "paginate": {
                "first": "İlk",
                "last": "Son",
                "next": "Sonraki",
                "previous": "Önceki"
            }
        }
    });
});

function sendCommand(command) {
    if (confirm('"' + command + '" komutunu göndermek istediğinizden emin misiniz?')) {
        alert('Komut gönderildi: ' + command);
        // Burada AJAX ile komut gönderilecek
    }
}
</script>

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