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

class StatisticsManager {
    private $db;
    private $date;
    
    public function __construct($db, $date = null) {
        $this->db = $db;
        $this->date = $date ?? date('Y-m-d');
    }
    
    public function getMemberStats() {
    $query = "SELECT 
        h.hour,
        COUNT(k.id) AS count
    FROM 
        (SELECT 0 AS hour UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 
         UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 
         UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 
         UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15 
         UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19 
         UNION ALL SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23) h
    LEFT JOIN kullanicilar k
        ON HOUR(FROM_UNIXTIME(k.user_kayit)) = h.hour
        AND DATE(FROM_UNIXTIME(k.user_kayit)) = :date
        AND k.user_bot = 0
    GROUP BY h.hour
    ORDER BY h.hour";

    $stmt = $this->db->prepare($query);
    $stmt->execute(['date' => $this->date]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

    
    public function getSalesStats() {
    $query = "SELECT 
        h.hour,
        COUNT(o.id) AS count
    FROM 
        (SELECT 0 AS hour UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 
         UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 
         UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 
         UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15 
         UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19 
         UNION ALL SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23) h
    LEFT JOIN odemeler o
        ON HOUR(FROM_UNIXTIME(o.tarih)) = h.hour
        AND DATE(FROM_UNIXTIME(o.tarih)) = :date
    LEFT JOIN kullanicilar k
        ON k.id = o.user_id
        AND k.user_bot = 0
    GROUP BY h.hour
    ORDER BY h.hour";

    $stmt = $this->db->prepare($query);
    $stmt->execute(['date' => $this->date]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

}

// Sayfa işlemleri
$selected_date = $_POST['selected_date'] ?? date('Y-m-d');
$stats = new StatisticsManager($db, $selected_date);

try {
    $member_stats = $stats->getMemberStats();
    $sales_stats = $stats->getSalesStats();
    
    // İstatistikleri hesapla
    $total_members = array_sum(array_column($member_stats, 'count'));
    $total_sales = array_sum(array_column($sales_stats, 'count'));
    $max_member_hour = array_reduce($member_stats, function($carry, $item) {
        return ($carry['count'] ?? 0) > $item['count'] ? $carry : $item;
    }, ['hour' => 0, 'count' => 0]);
    
} catch (PDOException $e) {
    error_log("Database Error: " . $e->getMessage());
    $error_message = "Veriler alınırken bir hata oluştu.";
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kayıt ve Satış Sayısı</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/boxicons@2.0.7/css/boxicons.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #4e73df;
            --secondary-color: #858796;
            --success-color: #1cc88a;
        }
        
        body {
            background-color: #f8f9fc;
            font-family: 'Nunito', sans-serif;
        }
        
        .container {
            max-width: 500px;
            padding: 0.5rem;
        }
        
        @media (max-width: 992px) {
            .container {
                max-width: 100%;
            }
        }
        
        .stats-card {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
            margin-bottom: 1.5rem;
        }
        
        .stats-table {
            font-size: 0.875rem;
            width: 100%;
            margin: 0;
            border-collapse: collapse;
        }
        
        .stats-table th {
            background: var(--primary-color);
            color: white;
            font-weight: normal;
            font-size: 0.875rem;
            padding: 8px;
            border: 1px solid #4668d9;
        }
        
        .stats-table td {
            vertical-align: middle;
            padding: 8px;
            font-size: 0.875rem;
            font-weight: bold;
            border: 1px solid #dee2e6;
        }
        
        .zero-value {
            color: var(--secondary-color);
        }
        
        .highlight-row {
            background-color: rgba(78, 115, 223, 0.05);
        }
        
        .total-row {
            background-color: var(--primary-color);
            color: white;
            font-weight: 600;
            border: 1px solid #4668d9 !important;
        }
        
        .total-row td {
            border-color: #4668d9;
        }
        
        .stats-summary {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 0.75rem;
            margin-bottom: 1.5rem;
        }
        
        .summary-card {
            padding: 1rem;
            border-radius: 8px;
            color: white;
        }
        
        .summary-card.primary {
            background: linear-gradient(45deg, var(--primary-color), #6610f2);
        }
        
        .summary-card.success {
            background: linear-gradient(45deg, var(--success-color), #20c997);
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 0.25rem;
            }
            
            .stats-table {
                font-size: 0.75rem;
            }
            
            .stats-table td, .stats-table th {
                padding: 0.5rem;
            }
            
            .stats-summary {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <div class="stats-card p-4">
            <!-- Tarih Seçici -->
            <form method="post" class="mb-4">
                <div class="row align-items-center">
                    <div class="col-md-auto">
                        <h5 class="mb-0">Günlük İstatistikler</h5>
                    </div>
                    <div class="col">
                        <div class="d-flex gap-2">
                            <input type="date" name="selected_date" 
                                   value="<?= htmlspecialchars($selected_date) ?>" 
                                   class="form-control" required>
                            <button type="submit" class="btn btn-primary d-flex align-items-center gap-2">
                                <i class='bx bx-search'></i><span>Göster</span>
                            </button>
                        </div>
                    </div>
                </div>
            </form>

            <!-- Özet Kartları -->
            <div class="stats-summary">
                <div class="summary-card primary">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="mb-0">Toplam Üye</h6>
                            <h3 class="mb-0"><?= $total_members ?></h3>
                        </div>
                        <i class='bx bxs-user-plus' style="font-size: 2.5rem;"></i>
                    </div>
                </div>
                <div class="summary-card success">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="mb-0">Toplam Satış</h6>
                            <h3 class="mb-0"><?= $total_sales ?></h3>
                        </div>
                        <i class='bx bxs-cart-add' style="font-size: 2.5rem;"></i>
                    </div>
                </div>
            </div>

            <?php if (isset($error_message)): ?>
                <div class="alert alert-danger"><?= $error_message ?></div>
            <?php else: ?>
                <!-- İstatistik Tablosu -->
                <div class="table-responsive">
                    <table class="table stats-table table-bordered table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Saat</th>
                                <th>Üye Kayıt</th>
                                <th>Satış</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($member_stats as $hour => $data): ?>
                                <?php 
                                $member_count = $data['count'];
                                $sales_count = $sales_stats[$hour]['count'];
                                $is_peak = $data['hour'] == $max_member_hour['hour'];
                                ?>
                                <tr class="<?= $is_peak ? 'highlight-row' : '' ?>">
                                    <td><?= sprintf("%02d:00 - %02d:59", $data['hour'], $data['hour']) ?></td>
                                    <td>
                                        <span class="<?= $member_count == 0 ? 'zero-value' : '' ?>">
                                            <?= $member_count ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="<?= $sales_count == 0 ? 'zero-value' : '' ?>">
                                            <?= $sales_count ?>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            <tr class="total-row">
                                <td>TOPLAM</td>
                                <td><?= $total_members ?></td>
                                <td><?= $total_sales ?></td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- İstatistik Özeti -->
                <div class="alert alert-info mt-3 mb-0">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <i class='bx bxs-info-circle bx-sm'></i>
                        </div>
                        <div class="col">
                            <small>
                                En yoğun kayıt: <strong><?= sprintf("%02d:00-%02d:59", $max_member_hour['hour'], $max_member_hour['hour']) ?></strong>
                                (<?= $max_member_hour['count'] ?> kayıt)<br>
                                Ortalama saatlik kayıt: <strong><?= round($total_members / 24, 1) ?></strong>
                            </small>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
