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

// Debug
error_log("Database connection: " . ($con ? "OK" : "NULL"));

// 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 statistics
$devices_sql = "SELECT 
    COUNT(*) as total_devices,
    SUM(CASE WHEN status = 'online' THEN 1 ELSE 0 END) as online_devices,
    SUM(CASE WHEN status = 'offline' THEN 1 ELSE 0 END) as offline_devices
    FROM devices WHERE owner_id = $user_id";
$devices_result = $con->query($devices_sql);
$device_stats = $devices_result ? $devices_result->fetch_assoc() : ['total_devices' => 0, 'online_devices' => 0, 'offline_devices' => 0];

// Get recent sensor data
$sensor_sql = "SELECT sd.*, d.device_name 
               FROM sensor_data sd 
               JOIN devices d ON sd.device_id = d.device_id 
               WHERE d.owner_id = $user_id 
               ORDER BY sd.timestamp DESC 
               LIMIT 10";
$sensor_result = $con->query($sensor_sql);
$sensor_data = $sensor_result ? $sensor_result->fetch_all(MYSQLI_ASSOC) : [];

// Layout variables
$page_title = 'Dashboard';
$breadcrumb_title = 'Dashboard';
$current_page = 'dashboard';
$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 layout-fixed">
<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">
            <?php if ($user['role'] === 'admin'): ?>
            <!-- Admin Dashboard -->
            <div class="row">
                <!-- Small boxes (Stat box) -->
                <div class="row">
                    <div class="col-lg-3 col-6">
                        <div class="small-box bg-info">
                            <div class="inner">
                                <h3><?php echo $device_stats['total_devices']; ?></h3>
                                <p>Toplam Cihaz</p>
                            </div>
                            <div class="icon">
                                <i class="fas fa-microchip"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-3 col-6">
                        <div class="small-box bg-success">
                            <div class="inner">
                                <h3><?php echo $device_stats['online_devices']; ?></h3>
                                <p>Online Cihaz</p>
                            </div>
                            <div class="icon">
                                <i class="fas fa-wifi"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-3 col-6">
                        <div class="small-box bg-warning">
                            <div class="inner">
                                <h3><?php echo $device_stats['offline_devices']; ?></h3>
                                <p>Offline Cihaz</p>
                            </div>
                            <div class="icon">
                                <i class="fas fa-wifi-slash"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-3 col-6">
                        <div class="small-box bg-danger">
                            <div class="inner">
                                <h3>0</h3>
                                <p>Hata Raporu</p>
                            </div>
                            <div class="icon">
                                <i class="fas fa-exclamation-triangle"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Info boxes -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-chart-pie mr-1"></i>
                                    Cihaz Durumu
                                </h3>
                            </div>
                            <div class="card-body">
                                <div class="chart-container" style="position: relative; height:300px;">
                                    <canvas id="deviceStatusChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-chart-line mr-1"></i>
                                    Son Sensör Verileri
                                </h3>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>Cihaz</th>
                                                <th>Sensör</th>
                                                <th>Değer</th>
                                                <th>Zaman</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($sensor_data as $row): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($row['device_name']); ?></td>
                                                <td><?php echo htmlspecialchars($row['sensor_id']); ?></td>
                                                <td><?php echo htmlspecialchars($row['value']); ?> <?php echo htmlspecialchars($row['unit']); ?></td>
                                                <td><?php echo date('H:i', strtotime($row['timestamp'])); ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php else: ?>
            <!-- User Dashboard -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-user mr-1"></i>
                                Hoş Geldin, <?php echo htmlspecialchars($user['username']); ?>!
                            </h3>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="info-box">
                                        <span class="info-box-icon bg-info"><i class="fas fa-microchip"></i></span>
                                        <div class="info-box-content">
                                            <span class="info-box-text">Cihazlarım</span>
                                            <span class="info-box-number"><?php echo $device_stats['total_devices']; ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="info-box">
                                        <span class="info-box-icon bg-success"><i class="fas fa-wifi"></i></span>
                                        <div class="info-box-content">
                                            <span class="info-box-text">Online</span>
                                            <span class="info-box-number"><?php echo $device_stats['online_devices']; ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="info-box">
                                        <span class="info-box-icon bg-warning"><i class="fas fa-wifi-slash"></i></span>
                                        <div class="info-box-content">
                                            <span class="info-box-text">Offline</span>
                                            <span class="info-box-number"><?php echo $device_stats['offline_devices']; ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="info-box">
                                        <span class="info-box-icon bg-primary"><i class="fas fa-user"></i></span>
                                        <div class="info-box-content">
                                            <span class="info-box-text">Rol</span>
                                            <span class="info-box-number"><?php echo ucfirst($user['role']); ?></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row mt-4">
                                <div class="col-md-12">
                                    <h4>Cihazlarım</h4>
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Cihaz Adı</th>
                                                    <th>Durum</th>
                                                    <th>Son Aktivite</th>
                                                    <th>İşlemler</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td>Örnek Cihaz 1</td>
                                                    <td><span class="badge badge-success">Online</span></td>
                                                    <td>2 dakika önce</td>
                                                    <td>
                                                        <button class="btn btn-sm btn-info"><i class="fas fa-eye"></i></button>
                                                        <button class="btn btn-sm btn-warning"><i class="fas fa-cog"></i></button>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </section>
    </div>
</div>

<script>
<?php if ($user['role'] === 'admin'): ?>
// Admin Device Status Chart
Morris.Donut({
    element: 'deviceStatusChart',
    data: [
        {label: "Online", value: <?php echo $device_stats['online_devices']; ?>},
        {label: "Offline", value: <?php echo $device_stats['offline_devices']; ?>}
    ],
    resize: true,
    colors: ['#00a65a', '#f56954']
});
<?php endif; ?>

// Auto-refresh dashboard
setInterval(function() {
    location.reload();
}, 30000); // Refresh every 30 seconds
</script>

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