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

// Layout variables
$page_title = 'DMAppsESP - Raporlar';
$breadcrumb_title = 'Raporlar';
$current_page = 'reports';
$extra_css = '<style>
    .report-card {
        background: white;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .filter-section {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
    }
    .report-preview {
        border: 1px solid #ddd;
        border-radius: 5px;
        padding: 15px;
        background: #f8f9fa;
        min-height: 200px;
    }
    .export-options {
        display: flex;
        gap: 10px;
        margin-top: 10px;
    }
    .btn-export {
        padding: 8px 16px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        text-decoration: none;
        display: inline-block;
    }
    .btn-pdf { background: #dc3545; color: white; }
    .btn-excel { background: #28a745; color: white; }
    .btn-csv { background: #007bff; color: white; }
</style>';

$extra_js = '<script>
function generateReport() {
    const reportType = document.getElementById(\'reportType\').value;
    const dateFrom = document.getElementById(\'dateFrom\').value;
    const dateTo = document.getElementById(\'dateTo\').value;
    const deviceId = document.getElementById(\'deviceId\').value;
    const format = document.getElementById(\'format\').value;
    
    // Parametreleri kontrol et
    if (!dateFrom || !dateTo) {
        alert(\'Tarih aralığı seçiniz!\');
        return;
    }
    
    // Raporu oluştur
    const params = new URLSearchParams({
        type: reportType,
        date_from: dateFrom,
        date_to: dateTo,
        device_id: deviceId,
        format: format
    });
    
    // Preview göster
    fetch(\'api/reports.php?action=preview&\' + params.toString())
        .then(response => response.json())
        .then(data => {
            updatePreview(data);
        });
}

function updatePreview(data) {
    const preview = document.getElementById(\'reportPreview\');
    
    if (data.success) {
        let html = \'<h5>Rapor Önizlemi</h5>\';
        html += \'<p><strong>Kayıt Sayısı:</strong> \' + data.total_records + \'</p>\';
        html += \'<p><strong>Tarih Aralığı:</strong> \' + data.date_range + \'</p>\';
        html += \'<p><strong>Oluşturulma:</strong> \' + new Date().toLocaleString() + \'</p>\';
        
        if (data.data && data.data.length > 0) {
            html += \'<table class="table table-striped mt-3">\';
            html += \'<thead><tr>\';
            
            // Başlıkları oluştur
            Object.keys(data.data[0]).forEach(key => {
                html += \'<th>\' + key + \'</th>\';
            });
            html += \'</tr></thead><tbody>\';
            
            // Verileri oluştur (ilk 10 kayıt)
            data.data.slice(0, 10).forEach(row => {
                html += \'<tr>\';
                Object.values(row).forEach(value => {
                    html += \'<td>\' + value + \'</td>\';
                });
                html += \'</tr>\';
            });
            
            if (data.data.length > 10) {
                html += \'<tr><td colspan="\'+ Object.keys(data.data[0]).length +\'">... ve \' + (data.data.length - 10) + \' kayıt daha</td></tr>\';
            }
            
            html += \'</tbody></table>\';
        }
        
        preview.innerHTML = html;
    } else {
        preview.innerHTML = \'<div class="alert alert-danger">Hata: \' + data.message + \'</div>\';
    }
}

function exportReport(format) {
    const reportType = document.getElementById(\'reportType\').value;
    const dateFrom = document.getElementById(\'dateFrom\').value;
    const dateTo = document.getElementById(\'dateTo\').value;
    const deviceId = document.getElementById(\'deviceId\').value;
    
    const params = new URLSearchParams({
        type: reportType,
        date_from: dateFrom,
        date_to: dateTo,
        device_id: deviceId,
        format: format
    });
    
    // İndirme penceresini aç
    window.open(\'api/reports.php?action=export&\' + params.toString(), \'_blank\');
}

function scheduleReport() {
    const reportType = document.getElementById(\'reportType\').value;
    const frequency = document.getElementById(\'scheduleFrequency\').value;
    const email = document.getElementById(\'scheduleEmail\').value;
    
    if (!email) {
        alert(\'E-posta adresi giriniz!\');
        return;
    }
    
    fetch(\'api/reports.php?action=schedule\', {
        method: \'POST\',
        headers: {
            \'Content-Type\': \'application/json\'
        },
        body: JSON.stringify({
            type: reportType,
            frequency: frequency,
            email: email
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(\'Rapor zamanlandı!\');
        } else {
            alert(\'Hata: \' + data.message);
        }
    });
}

// Sayfa yüklendiğinde cihazları yükle
document.addEventListener(\'DOMContentLoaded\', function() {
    loadDevices();
});

function loadDevices() {
    fetch(\'api/devices.php?action=list\')
        .then(response => response.json())
        .then(data => {
            const select = document.getElementById(\'deviceId\');
            select.innerHTML = \'<option value="">Tüm Cihazlar</option>\';
            
            if (data.devices) {
                data.devices.forEach(device => {
                    select.innerHTML += \'<option value="\' + device.id + \'">\' + device.name + \' (\' + device.device_id + \')</option>\';
                });
            }
        });
}
</script>';

require_once 'layouts/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1 class="h3 mb-4">Raporlar</h1>
            
            <!-- Filtreler -->
            <div class="filter-section">
                <div class="row">
                    <div class="col-md-3">
                        <label class="form-label">Rapor Tipi:</label>
                        <select class="form-select" id="reportType">
                            <option value="sensor_data">Sensör Verileri</option>
                            <option value="device_status">Cihaz Durumu</option>
                            <option value="user_activity">Kullanıcı Aktivitesi</option>
                            <option value="system_performance">Sistem Performansı</option>
                            <option value="error_logs">Hata Logları</option>
                            <option value="device_usage">Cihaz Kullanımı</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Başlangıç Tarihi:</label>
                        <input type="date" class="form-control" id="dateFrom" value="<?php echo date('Y-m-d', strtotime('-7 days')); ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Bitiş Tarihi:</label>
                        <input type="date" class="form-control" id="dateTo" value="<?php echo date('Y-m-d'); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Cihaz:</label>
                        <select class="form-select" id="deviceId">
                            <option value="">Yükleniyor...</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button class="btn btn-primary w-100" onclick="generateReport()">Oluştur</button>
                    </div>
                </div>
            </div>
            
            <!-- Rapor Önizleme -->
            <div class="report-card">
                <h5>Rapor Önizlemi</h5>
                <div id="reportPreview" class="report-preview">
                    <p class="text-muted">Rapor oluşturmak için yukarıdaki filtreleri seçip "Oluştur" butonuna tıklayın.</p>
                </div>
                
                <!-- Dışa Aktarma Seçenekleri -->
                <div class="export-options">
                    <button class="btn-export btn-pdf" onclick="exportReport('pdf')">
                        📄 PDF İndir
                    </button>
                    <button class="btn-export btn-excel" onclick="exportReport('excel')">
                        📊 Excel İndir
                    </button>
                    <button class="btn-export btn-csv" onclick="exportReport('csv')">
                        📋 CSV İndir
                    </button>
                </div>
            </div>
            
            <!-- Zamanlanmış Raporlar -->
            <div class="report-card">
                <h5>Zamanlanmış Raporlar</h5>
                <div class="row">
                    <div class="col-md-4">
                        <label class="form-label">Frekans:</label>
                        <select class="form-select" id="scheduleFrequency">
                            <option value="daily">Günlük</option>
                            <option value="weekly">Haftalık</option>
                            <option value="monthly">Aylık</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">E-posta:</label>
                        <input type="email" class="form-control" id="scheduleEmail" placeholder="ornek@email.com">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">&nbsp;</label>
                        <button class="btn btn-success w-100" onclick="scheduleReport()">Zamanla</button>
                    </div>
                </div>
            </div>
            
            <!-- Mevcut Raporlar -->
            <div class="report-card">
                <h5>Mevcut Raporlar</h5>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Rapor Adı</th>
                                <th>Tip</th>
                                <th>Tarih Aralığı</th>
                                <th>Oluşturulma</th>
                                <th>Durum</th>
                                <th>İşlemler</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Sensör Verileri - Ocak 2024</td>
                                <td><span class="badge bg-info">Sensör Verileri</span></td>
                                <td>01.01.2024 - 31.01.2024</td>
                                <td>15.02.2024 14:30</td>
                                <td><span class="badge bg-success">Tamamlandı</span></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary">İndir</button>
                                    <button class="btn btn-sm btn-outline-danger">Sil</button>
                                </td>
                            </tr>
                            <tr>
                                <td>Cihaz Durumu - Haftalık</td>
                                <td><span class="badge bg-warning">Cihaz Durumu</span></td>
                                <td>08.02.2024 - 15.02.2024</td>
                                <td>15.02.2024 10:15</td>
                                <td><span class="badge bg-success">Tamamlandı</span></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary">İndir</button>
                                    <button class="btn btn-sm btn-outline-danger">Sil</button>
                                </td>
                            </tr>
                            <tr>
                                <td>Sistem Performansı</td>
                                <td><span class="badge bg-secondary">Sistem Performansı</span></td>
                                <td>01.02.2024 - 15.02.2024</td>
                                <td>15.02.2024 09:45</td>
                                <td><span class="badge bg-warning">İşleniyor</span></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" disabled>İndir</button>
                                    <button class="btn btn-sm btn-outline-danger">İptal</button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Rapor Şablonları -->
            <div class="report-card">
                <h5>Rapor Şablonları</h5>
                <div class="row">
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body">
                                <h6 class="card-title">Aylık Sensör Raporu</h6>
                                <p class="card-text">Aylık sensör verilerini özetleyen rapor.</p>
                                <button class="btn btn-sm btn-outline-primary">Kullan</button>
                                <button class="btn btn-sm btn-outline-secondary">Düzenle</button>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body">
                                <h6 class="card-title">Cihaz Performans Raporu</h6>
                                <p class="card-text">Cihaz performansını analiz eden rapor.</p>
                                <button class="btn btn-sm btn-outline-primary">Kullan</button>
                                <button class="btn btn-sm btn-outline-secondary">Düzenle</button>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body">
                                <h6 class="card-title">Özel Rapor</h6>
                                <p class="card-text">Özel filtrelerle oluşturulan rapor.</p>
                                <button class="btn btn-sm btn-primary">Oluştur</button>
                                <button class="btn btn-sm btn-outline-secondary">Kaydet</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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