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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

// 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) {
    header('Location: login.php');
    exit();
}

// 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 for last 24 hours
$sensor_sql = "SELECT * FROM sensor_data 
               WHERE device_id = $device_id 
               AND timestamp >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
               ORDER BY timestamp ASC";
$sensor_result = $con->query($sensor_sql);
$sensor_data = $sensor_result ? $sensor_result->fetch_all(MYSQLI_ASSOC) : [];

// Group data by sensor type
$grouped_data = [];
foreach ($sensor_data as $data) {
    $sensor_id = $data['sensor_id'];
    if (!isset($grouped_data[$sensor_id])) {
        $grouped_data[$sensor_id] = [];
    }
    $grouped_data[$sensor_id][] = [
        'timestamp' => strtotime($data['timestamp']),
        'value' => floatval($data['value']),
        'unit' => $data['unit'] ?? ''
    ];
}

// Layout variables
$page_title = 'Sensör Grafiği';
$breadcrumb_title = 'Sensör Grafiği';
$current_page = 'devices';
$extra_css = '<link rel="stylesheet" href="assets/plugins/morris/morris.css">';
$page_scripts = '<script src="assets/plugins/morris/morris.min.js"></script>
<script src="assets/plugins/morris/raphael-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-chart-line mr-1"></i>
                                <?php echo htmlspecialchars($device['device_name']); ?> - Sensör Grafiği
                            </h3>
                            <div class="card-tools">
                                <a href="device_detail.php?id=<?php echo $device['id']; ?>" class="btn btn-secondary btn-sm">
                                    <i class="fas fa-arrow-left"></i> Geri Dön
                                </a>
                                <button class="btn btn-info btn-sm" onclick="refreshData()">
                                    <i class="fas fa-sync"></i> Yenile
                                </button>
                            </div>
                        </div>
                        
                        <div class="card-body">
                            <!-- Device Info -->
                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <div class="alert alert-info">
                                        <i class="fas fa-info-circle"></i>
                                        <strong>Cihaz:</strong> <?php echo htmlspecialchars($device['device_name']); ?> | 
                                        <strong>Device ID:</strong> <code><?php echo htmlspecialchars($device['device_id']); ?></code> | 
                                        <strong>Durum:</strong> 
                                        <?php if ($device['status'] === 'online'): ?>
                                            <span class="badge badge-success">Online</span>
                                        <?php else: ?>
                                            <span class="badge badge-danger">Offline</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Charts -->
                            <?php if (!empty($grouped_data)): ?>
                                <div class="row">
                                    <?php $chartIndex = 0; ?>
                                    <?php foreach ($grouped_data as $sensor_id => $data): ?>
                                    <div class="col-md-6 mb-4">
                                        <div class="card">
                                            <div class="card-header">
                                                <h5 class="card-title">
                                                    <?php echo htmlspecialchars($sensor_id); ?>
                                                    <?php if (!empty($data[0]['unit'])): ?>
                                                        <small>(<?php echo htmlspecialchars($data[0]['unit']); ?>)</small>
                                                    <?php endif; ?>
                                                </h5>
                                            </div>
                                            <div class="card-body">
                                                <div id="chart-<?php echo $chartIndex; ?>" style="height: 250px;"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php $chartIndex++; ?>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="row">
                                    <div class="col-12">
                                        <div class="alert alert-warning">
                                            <i class="fas fa-exclamation-triangle"></i>
                                            Bu cihaz için son 24 saat içinde sensör verisi bulunamadı.
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <!-- Statistics -->
                            <div class="row mt-4">
                                <div class="col-md-12">
                                    <h5>Sensör İstatistikleri</h5>
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Sensör</th>
                                                    <th>Toplam Okuma</th>
                                                    <th>Min Değer</th>
                                                    <th>Max Değer</th>
                                                    <th>Ortalama</th>
                                                    <th>Son Değer</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($grouped_data as $sensor_id => $data): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($sensor_id); ?></td>
                                                    <td><?php echo count($data); ?></td>
                                                    <td><?php echo min(array_column($data, 'value')); ?></td>
                                                    <td><?php echo max(array_column($data, 'value')); ?></td>
                                                    <td><?php echo round(array_sum(array_column($data, 'value')) / count($data), 2); ?></td>
                                                    <td><?php echo end($data)['value']; ?></td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
</div>

<script>
<?php
$chartIndex = 0;
foreach ($grouped_data as $sensor_id => $data):
    $chartData = [];
    foreach ($data as $point) {
        $chartData[] = [
            'y' => $point['timestamp'] * 1000,
            'a' => $point['value']
        ];
    }
    $chartDataJson = json_encode($chartData);
?>
// Chart <?php echo $chartIndex; ?> - <?php echo htmlspecialchars($sensor_id); ?>
Morris.Line({
    element: 'chart-<?php echo $chartIndex; ?>',
    data: <?php echo $chartDataJson; ?>,
    xkey: 'y',
    ykeys: ['a'],
    labels: ['<?php echo htmlspecialchars($sensor_id); ?>'],
    lineColors: ['#007bff'],
    pointSize: 3,
    hideHover: false,
    resize: true,
    dateFormat: function (x) { return new Date(x).toLocaleString(); },
    xLabels: 'day'
});
<?php
$chartIndex++;
endforeach;
?>

function refreshData() {
    location.reload();
}
</script>

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