<?php
require_once '../config/config.php';
require_once '../includes/auth.php';

requireCompanyLogin();

$companyId = $_SESSION['company_id'];

// Firma bilgileri
$stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
$stmt->execute([$companyId]);
$company = $stmt->fetch();

// İstatistikler
$stats = [];

// Toplam yorum sayısı
$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM reviews WHERE company_id = ? AND status = 'approved'");
$stmt->execute([$companyId]);
$stats['total_reviews'] = $stmt->fetch()['total'];

// Ortalama puan
$ratingStats = calculateAverageRating($companyId);
$stats['average_rating'] = $ratingStats['average'];

// Puanlama dağılımı
$ratingDistribution = getRatingDistribution($companyId);

// Toplam hizmet sayısı
$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM services WHERE company_id = ?");
$stmt->execute([$companyId]);
$stats['total_services'] = $stmt->fetch()['total'];

// Toplam hizmet görüntülenme
$stmt = $pdo->prepare("SELECT SUM(views) as total FROM services WHERE company_id = ?");
$stmt->execute([$companyId]);
$stats['total_service_views'] = $stmt->fetch()['total'] ?? 0;

// Hizmet görüntülenme istatistikleri
$stmt = $pdo->prepare("SELECT title, views FROM services WHERE company_id = ? ORDER BY views DESC LIMIT 5");
$stmt->execute([$companyId]);
$serviceViews = $stmt->fetchAll();

$page_title = 'Dashboard';
include 'includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1 class="h3 mb-4">Hoş Geldiniz, <?= e($company['company_name']) ?></h1>
        </div>
    </div>
    
    <!-- İstatistik Kartları -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-subtitle mb-2">Toplam Yorum</h6>
                            <h2 class="mb-0"><?= $stats['total_reviews'] ?></h2>
                        </div>
                        <i class="fas fa-comments fa-3x opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-subtitle mb-2">Ortalama Puan</h6>
                            <h2 class="mb-0"><?= $stats['average_rating'] ?>/5</h2>
                        </div>
                        <i class="fas fa-star fa-3x opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-subtitle mb-2">Hizmet Sayısı</h6>
                            <h2 class="mb-0"><?= $stats['total_services'] ?></h2>
                        </div>
                        <i class="fas fa-list fa-3x opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card bg-warning text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="card-subtitle mb-2">Toplam Görüntülenme</h6>
                            <h2 class="mb-0"><?= $stats['total_service_views'] ?></h2>
                        </div>
                        <i class="fas fa-eye fa-3x opacity-50"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <!-- Puanlama Dağılım Grafiği -->
        <div class="col-md-6 mb-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Puanlama Dağılımı</h5>
                </div>
                <div class="card-body">
                    <canvas id="ratingChart" height="200"></canvas>
                </div>
            </div>
        </div>
        
        <!-- Hizmet Görüntülenme İstatistikleri -->
        <div class="col-md-6 mb-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">En Çok Görüntülenen Hizmetler</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($serviceViews)): ?>
                        <p class="text-muted mb-0">Henüz hizmet görüntülenmesi yok.</p>
                    <?php else: ?>
                        <canvas id="serviceViewsChart" height="200"></canvas>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Puanlama Detayları -->
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Puanlama Detayları</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Puan</th>
                                    <th>Yorum Sayısı</th>
                                    <th>Yüzde</th>
                                    <th>Görsel</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $totalReviews = array_sum($ratingDistribution);
                                for ($i = 5; $i >= 1; $i--): 
                                    $count = $ratingDistribution[$i];
                                    $percentage = $totalReviews > 0 ? ($count / $totalReviews * 100) : 0;
                                ?>
                                    <tr>
                                        <td><?= $i ?> Yıldız</td>
                                        <td><?= $count ?></td>
                                        <td><?= number_format($percentage, 1) ?>%</td>
                                        <td>
                                            <div class="progress" style="height: 20px;">
                                                <div class="progress-bar" role="progressbar" style="width: <?= $percentage ?>%" aria-valuenow="<?= $percentage ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endfor; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
// Puanlama Dağılım Grafiği
const ratingCtx = document.getElementById('ratingChart');
if (ratingCtx) {
    new Chart(ratingCtx, {
        type: 'bar',
        data: {
            labels: ['5 Yıldız', '4 Yıldız', '3 Yıldız', '2 Yıldız', '1 Yıldız'],
            datasets: [{
                label: 'Yorum Sayısı',
                data: [
                    <?= $ratingDistribution[5] ?>,
                    <?= $ratingDistribution[4] ?>,
                    <?= $ratingDistribution[3] ?>,
                    <?= $ratingDistribution[2] ?>,
                    <?= $ratingDistribution[1] ?>
                ],
                backgroundColor: [
                    'rgba(40, 167, 69, 0.8)',
                    'rgba(40, 167, 69, 0.6)',
                    'rgba(255, 193, 7, 0.8)',
                    'rgba(255, 193, 7, 0.6)',
                    'rgba(220, 53, 69, 0.8)'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
}

// Hizmet Görüntülenme Grafiği
const serviceViewsCtx = document.getElementById('serviceViewsChart');
if (serviceViewsCtx) {
    new Chart(serviceViewsCtx, {
        type: 'doughnut',
        data: {
            labels: [<?= implode(',', array_map(function($s) { return "'" . addslashes($s['title']) . "'"; }, $serviceViews)) ?>],
            datasets: [{
                data: [<?= implode(',', array_column($serviceViews, 'views')) ?>],
                backgroundColor: [
                    'rgba(54, 162, 235, 0.8)',
                    'rgba(255, 99, 132, 0.8)',
                    'rgba(255, 206, 86, 0.8)',
                    'rgba(75, 192, 192, 0.8)',
                    'rgba(153, 102, 255, 0.8)'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
}
</script>

<?php include 'includes/footer.php'; ?>





