<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../functions/stok_fonksiyonlari.php';
yetkili_mi();

$sayfa_baslik = __('reports_best_selling_products');

// Filtreleme parametreleri
$baslangic_tarihi = $_GET['baslangic_tarihi'] ?? date('Y-m-01'); // Ay başı
$bitis_tarihi = $_GET['bitis_tarihi'] ?? date('Y-m-d'); // Bugün
$limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT) ?: 20;

// Aktif şirket ID'sini al
$aktif_sirket_id = $_SESSION['aktif_sirket_id'] ?? 0;

// En çok satan ürünler raporunu getir
try {
    $sql = "SELECT 
                u.id,
                u.urun_adi,
                u.birim,
                u.satis_fiyati,
                SUM(sh.miktar) as toplam_satis_miktari,
                SUM(sh.toplam_tutar) as toplam_satis_tutari,
                COUNT(DISTINCT sh.cari_id) as farkli_musteri_sayisi,
                COUNT(sh.id) as satis_sayisi,
                AVG(sh.birim_fiyat) as ortalama_satis_fiyati,
                MAX(sh.tarih) as son_satis_tarihi,
                MIN(sh.tarih) as ilk_satis_tarihi
            FROM urunler u
            INNER JOIN stok_hareketleri sh ON u.id = sh.urun_id AND sh.sirket_id = ?
            WHERE sh.hareket_turu = 'cikis' 
            AND sh.tarih BETWEEN ? AND ?
            AND u.aktif = 1 AND u.sirket_id = ?
            GROUP BY u.id, u.urun_adi, u.birim, u.satis_fiyati
            ORDER BY toplam_satis_tutari DESC
            LIMIT ?";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([$aktif_sirket_id, $baslangic_tarihi, $bitis_tarihi, $aktif_sirket_id, $limit]);
    $en_cok_satan_urunler = $stmt->fetchAll();
    
    // Toplam satış istatistikleri
    $sql_toplam = "SELECT 
                        COUNT(DISTINCT sh.urun_id) as toplam_urun_sayisi,
                        SUM(sh.miktar) as toplam_satis_miktari,
                        SUM(sh.toplam_tutar) as toplam_satis_tutari,
                        COUNT(DISTINCT sh.cari_id) as toplam_musteri_sayisi
                   FROM stok_hareketleri sh
                   INNER JOIN urunler u ON sh.urun_id = u.id AND u.sirket_id = ?
                   WHERE sh.hareket_turu = 'cikis' 
                   AND sh.tarih BETWEEN ? AND ?
                   AND sh.sirket_id = ?";
    
    $stmt_toplam = $db->prepare($sql_toplam);
    $stmt_toplam->execute([$aktif_sirket_id, $baslangic_tarihi, $bitis_tarihi, $aktif_sirket_id]);
    $toplam_istatistikler = $stmt_toplam->fetch();
    
} catch (PDOException $e) {
    error_log("En çok satan ürünler raporu hatası: " . $e->getMessage());
    $_SESSION['hata'] = "Rapor yüklenirken bir hata oluştu.";
    $en_cok_satan_urunler = [];
    $toplam_istatistikler = [];
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Odjoo Yönetim - <?= temizle($sayfa_baslik) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .stat-card {
            transition: transform 0.2s;
        }
        .stat-card:hover {
            transform: translateY(-2px);
        }
        .rank-badge {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            font-weight: bold;
        }
        @media print {
            .no-print { display: none !important; }
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <div class="container mt-4">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2><i class="bi bi-trophy"></i> <?= temizle($sayfa_baslik) ?></h2>
                    <div class="no-print">
                        <button onclick="window.print()" class="btn btn-outline-secondary me-2">
                            <i class="bi bi-printer"></i> <?= __('print') ?>
                        </button>
                        <a href="stok_raporlari.php" class="btn btn-outline-primary">
                            <i class="bi bi-arrow-left"></i> <?= __('detailed_reports') ?>
                        </a>
                    </div>
                </div>

                <!-- Filtreleme Formu -->
                <div class="card mb-4 no-print">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-funnel me-2"></i><?= __('report_filters') ?></h5>
                    </div>
                    <div class="card-body">
                        <form method="get" class="row g-3">
                            <div class="col-md-4">
                                <label for="baslangic_tarihi" class="form-label"><?= __('start_date') ?></label>
                                <input type="date" class="form-control" id="baslangic_tarihi" name="baslangic_tarihi" 
                                       value="<?= htmlspecialchars($baslangic_tarihi) ?>">
                            </div>
                            <div class="col-md-4">
                                <label for="bitis_tarihi" class="form-label"><?= __('end_date') ?></label>
                                <input type="date" class="form-control" id="bitis_tarihi" name="bitis_tarihi" 
                                       value="<?= htmlspecialchars($bitis_tarihi) ?>">
                            </div>
                            <div class="col-md-2">
                                <label for="limit" class="form-label"><?= __('number_to_show') ?></label>
                                <select class="form-select" id="limit" name="limit">
                                    <option value="10" <?= $limit == 10 ? 'selected' : '' ?>><?= __('first_10') ?></option>
                                    <option value="20" <?= $limit == 20 ? 'selected' : '' ?>><?= __('first_20') ?></option>
                                    <option value="50" <?= $limit == 50 ? 'selected' : '' ?>><?= __('first_50') ?></option>
                                    <option value="100" <?= $limit == 100 ? 'selected' : '' ?>><?= __('first_100') ?></option>
                                </select>
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary">
                                    <i class="bi bi-search"></i> <?= __('fetch') ?>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Özet İstatistikler -->
                <?php if (!empty($toplam_istatistikler)): ?>
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card stat-card bg-primary text-white">
                            <div class="card-body text-center">
                                <h4><?= number_format($toplam_istatistikler['toplam_urun_sayisi']) ?></h4>
                                <small><?= __('sold_product_variety') ?></small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card bg-success text-white">
                            <div class="card-body text-center">
                                <h4><?= number_format($toplam_istatistikler['toplam_satis_miktari'], 0, ',', '.') ?></h4>
                                <small><?= __('total_sales_quantity') ?></small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card bg-warning text-white">
                            <div class="card-body text-center">
                                <h4><?= number_format($toplam_istatistikler['toplam_satis_tutari'], 0, ',', '.') . ' ' . getParaBirimiSembolu() ?></h4>
                                <small><?= __('total_sales_amount') ?></small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card bg-info text-white">
                            <div class="card-body text-center">
                                <h4><?= number_format($toplam_istatistikler['toplam_musteri_sayisi']) ?></h4>
                                <small><?= __('distinct_customers') ?></small>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- En Çok Satan Ürünler Tablosu -->
                <div class="card">
                    <div class="card-header bg-light">
                        <h5 class="mb-0">
                            <i class="bi bi-bar-chart me-2"></i><?= __('reports_best_selling_products') ?>
                            <span class="badge bg-secondary"><?= count($en_cok_satan_urunler) ?></span>
                        </h5>
                        <small class="text-muted">
                            <?= __('date_range') ?>: <?= date('d.m.Y', strtotime($baslangic_tarihi)) ?> - <?= date('d.m.Y', strtotime($bitis_tarihi)) ?>
                        </small>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($en_cok_satan_urunler)): ?>
                            <div class="text-center p-4">
                                <i class="bi bi-inbox display-1 text-muted"></i>
                                <p class="text-muted mt-2"><?= __('no_sales_in_range') ?></p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover mb-0">
                                    <thead class="table-light">
                                        <tr>
                                            <th class="text-center"><?= __('rank') ?></th>
                                            <th><?= __('product_name') ?></th>
                                            <th class="text-end"><?= __('sales_quantity') ?></th>
                                            <th class="text-end"><?= __('sales_amount') ?></th>
                                            <th class="text-end"><?= __('average_price') ?></th>
                                            <th class="text-center"><?= __('customer_count') ?></th>
                                            <th class="text-center"><?= __('sales_count') ?></th>
                                            <th class="text-center"><?= __('last_sale') ?></th>
                                            <th class="text-center"><?= __('performance') ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $toplam_tutar = $toplam_istatistikler['toplam_satis_tutari'] ?? 1;
                                        foreach ($en_cok_satan_urunler as $index => $urun): 
                                            $sira = $index + 1;
                                            $yuzde_pay = ($urun['toplam_satis_tutari'] / $toplam_tutar) * 100;
                                            
                                            // Sıra rengini belirle
                                            $rank_class = 'bg-secondary';
                                            if ($sira == 1) $rank_class = 'bg-warning text-dark';
                                            elseif ($sira == 2) $rank_class = 'bg-secondary';
                                            elseif ($sira == 3) $rank_class = 'bg-warning text-dark';
                                            elseif ($sira <= 10) $rank_class = 'bg-primary';
                                        ?>
                                            <tr>
                                                <td class="text-center">
                                                    <div class="rank-badge <?= $rank_class ?>">
                                                        <?php if ($sira == 1): ?>
                                                            <i class="bi bi-trophy-fill"></i>
                                                        <?php elseif ($sira == 2): ?>
                                                            <i class="bi bi-award-fill"></i>
                                                        <?php elseif ($sira == 3): ?>
                                                            <i class="bi bi-star-fill"></i>
                                                        <?php else: ?>
                                                            <?= $sira ?>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                                <td>
                                                    <strong><?= temizle($urun['urun_adi']) ?></strong>
                                                    <br><small class="text-muted"><?= temizle($urun['birim']) ?></small>
                                                </td>
                                                <td class="text-end">
                                                    <strong><?= number_format($urun['toplam_satis_miktari'], 2, ',', '.') ?></strong>
                                                </td>
                                                <td class="text-end">
                                                    <strong><?= number_format($urun['toplam_satis_tutari'], 2, ',', '.') . ' ' . getParaBirimiSembolu() ?></strong>
                                                    <br><small class="text-muted"><?= __('percent_share', [':share' => number_format($yuzde_pay, 1)]) ?></small>
                                                </td>
                                                <td class="text-end">
                                                    <?= number_format($urun['ortalama_satis_fiyati'], 2, ',', '.') . ' ' . getParaBirimiSembolu() ?>
                                                </td>
                                                <td class="text-center">
                                                    <span class="badge bg-info"><?= $urun['farkli_musteri_sayisi'] ?></span>
                                                </td>
                                                <td class="text-center">
                                                    <span class="badge bg-success"><?= $urun['satis_sayisi'] ?></span>
                                                </td>
                                                <td class="text-center">
                                                    <small><?= date('d.m.Y', strtotime($urun['son_satis_tarihi'])) ?></small>
                                                </td>
                                                <td class="text-center">
                                                    <div class="progress" style="height: 20px;">
                                                        <div class="progress-bar bg-<?= $sira <= 3 ? 'warning' : ($sira <= 10 ? 'primary' : 'secondary') ?>" 
                                                             role="progressbar" 
                                                             style="width: <?= min(100, $yuzde_pay * 5) ?>%"
                                                             title="<?= __('percent_share', [':share' => number_format($yuzde_pay, 1)]) ?>">
                                                            <?= number_format($yuzde_pay, 1) ?>%
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <?php include __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>

