<?php
/**
 * NEPHRO ERP - PREMIUM STOCK TRACKER (v8.1 - Full Dashboard)
 */
global $pdo;

if (!function_exists('h')) {
    function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, "UTF-8"); }
}

// 1. Geliştirilmiş İstatistik Sorguları
$stok_ozet = $pdo->query("SELECT 
    COUNT(*) as toplam_kalem,
    SUM(CASE WHEN stok_miktari <= kritik_seviye THEN 1 ELSE 0 END) as kritik_sayisi,
    SUM(stok_miktari) as toplam_adet,
    SUM(CASE WHEN stok_miktari > kritik_seviye AND stok_miktari <= (kritik_seviye * 1.5) THEN 1 ELSE 0 END) as uyari_sayisi,
    AVG(stok_miktari) as ortalama_stok,
    (SELECT COUNT(DISTINCT stok_id) FROM stok_hareketleri WHERE DATE(islem_tarihi) = CURDATE()) as gunluk_hareket
    FROM stok")->fetch(PDO::FETCH_ASSOC);

// 2. Kritik Stoklar (Eksik Yüzdesi Hesaplanmış)
$kritik_listesi = $pdo->query("SELECT s.*, 
    ROUND(( (s.kritik_seviye - s.stok_miktari) / NULLIF(s.kritik_seviye, 0) ) * 100, 0) as eksik_yuzde
    FROM stok s 
    WHERE stok_miktari <= kritik_seviye 
    ORDER BY eksik_yuzde DESC, stok_miktari ASC 
    LIMIT 6")->fetchAll(PDO::FETCH_ASSOC);

// 3. Son Hareketler
$son_hareketler = $pdo->query("SELECT sh.*, s.urun_adi, k.ad_soyad
    FROM stok_hareketleri sh 
    LEFT JOIN stok s ON sh.stok_id = s.id 
    LEFT JOIN kullanicilar k ON sh.kullanici_id = k.id 
    ORDER BY sh.islem_tarihi DESC LIMIT 8")->fetchAll(PDO::FETCH_ASSOC);

// 4. En Çok Hareket Görenler (Son 30 Gün)
$populer_urunler = $pdo->query("SELECT s.urun_adi, s.stok_miktari, COUNT(sh.id) as h_sayisi
    FROM stok_hareketleri sh
    JOIN stok s ON sh.stok_id = s.id
    WHERE sh.islem_tarihi >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY s.id ORDER BY h_sayisi DESC LIMIT 4")->fetchAll(PDO::FETCH_ASSOC);

// 5. Stok Durum Dağılımı
$dist = $pdo->query("SELECT 
    SUM(CASE WHEN stok_miktari = 0 THEN 1 ELSE 0 END) as sifir,
    SUM(CASE WHEN stok_miktari > 0 AND stok_miktari <= kritik_seviye THEN 1 ELSE 0 END) as kritik,
    SUM(CASE WHEN stok_miktari > kritik_seviye THEN 1 ELSE 0 END) as guvenli
    FROM stok")->fetch(PDO::FETCH_ASSOC);
?>

<style>
    :root { 
        --p: #4361ee; --s: #64748b; --bg: #f8fafc; --card: #ffffff; --dark: #0f172a; 
        --danger: #ef4444; --success: #10b981; --warning: #f59e0b; --info: #3b82f6;
    }
    
    .db-wrapper { max-width: 1400px; margin: 0 auto; padding: 15px; background: var(--bg); }

    /* Üst İstatistikler */
    .st-grid-top { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 15px; margin-bottom: 25px; }
    .st-card-mini { background: var(--card); padding: 20px; border-radius: 20px; border: 1px solid #e2e8f0; display: flex; align-items: center; gap: 15px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02); }
    .st-card-mini i { width: 48px; height: 48px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 1.3rem; }

    /* Ana Dashboard Layout */
    .st-main-layout { display: grid; grid-template-columns: 1.2fr 0.8fr; gap: 20px; }
    @media (max-width: 1100px) { .st-main-layout { grid-template-columns: 1fr; } }

    .panel-lux { background: var(--card); border-radius: 24px; padding: 25px; border: 1px solid #e2e8f0; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.04); margin-bottom: 20px; }
    .panel-lux h3 { font-size: 1.1rem; font-weight: 800; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; color: var(--dark); border-bottom: 1px solid #f1f5f9; padding-bottom: 15px; }

    /* Kritik Ürünler */
    .k-item { display: flex; align-items: center; padding: 12px 15px; background: #fef2f2; border-radius: 16px; margin-bottom: 10px; border: 1px solid #fee2e2; }
    .k-info { flex: 1; }
    .k-info b { display: block; font-size: 0.95rem; color: #991b1b; }
    .k-info span { font-size: 0.7rem; color: #ef4444; font-weight: 700; }
    .k-val { background: var(--danger); color: white; padding: 8px 12px; border-radius: 10px; font-weight: 900; font-size: 1rem; }

    /* Dağılım Kartları */
    .dist-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 20px; }
    .dist-box { padding: 15px; border-radius: 18px; text-align: center; border: 1px solid #f1f5f9; }
    .dist-box b { font-size: 1.5rem; display: block; color: var(--dark); }
    .dist-box small { font-size: 10px; font-weight: 800; color: var(--s); text-transform: uppercase; }

    /* Hızlı Aksiyon Butonları */
    .action-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
    .btn-action { 
        display: flex; align-items: center; justify-content: center; gap: 8px; 
        padding: 15px; border-radius: 15px; font-weight: 700; text-decoration: none; 
        font-size: 0.85rem; transition: 0.3s; border: none; cursor: pointer;
    }
    .btn-p { background: var(--p); color: white; }
    .btn-s { background: #f1f5f9; color: var(--dark); border: 1px solid #e2e8f0; }
    .btn-action:hover { transform: translateY(-3px); box-shadow: 0 5px 15px rgba(0,0,0,0.1); }

    /* Timeline */
    .tm-list { position: relative; padding-left: 15px; border-left: 2px solid #f1f5f9; }
    .tm-item { position: relative; margin-bottom: 15px; padding-left: 15px; }
    .tm-item::before { content: ''; position: absolute; left: -22px; top: 5px; width: 10px; height: 10px; border-radius: 50%; background: #cbd5e1; border: 2px solid #fff; }
    .tm-item.in::before { background: var(--success); }
    .tm-item.out::before { background: var(--danger); }
    .tm-item b { font-size: 0.85rem; display: block; }
    .tm-item small { font-size: 0.7rem; color: var(--s); }

    /* Grafik */
    .bar-container { height: 160px; display: flex; align-items: flex-end; gap: 10px; border-bottom: 1px solid #f1f5f9; padding-bottom: 5px; }
    .bar-group { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 5px; }
    .bar { width: 20px; border-radius: 4px 4px 0 0; min-height: 2px; }
</style>

<div class="db-wrapper">
    <div class="st-grid-top">
        <div class="st-card-mini">
            <i class="fas fa-layer-group" style="background: #eff6ff; color: var(--p);"></i>
            <div><small>TOPLAM KALEM</small><b><?= $stok_ozet['toplam_kalem'] ?> Kalem</b></div>
        </div>
        <div class="st-card-mini">
            <i class="fas fa-exclamation-circle" style="background: #fef2f2; color: var(--danger);"></i>
            <div><small>KRİTİK STOK</small><b><?= $stok_ozet['kritik_sayisi'] ?> Ürün</b></div>
        </div>
        <div class="st-card-mini">
            <i class="fas fa-truck-loading" style="background: #f0fdf4; color: var(--success);"></i>
            <div><small>TOPLAM MİKTAR</small><b><?= number_format($stok_ozet['toplam_adet']) ?> Adet</b></div>
        </div>
        <div class="st-card-mini">
            <i class="fas fa-history" style="background: #fffbeb; color: var(--warning);"></i>
            <div><small>BUGÜNKÜ HAREKET</small><b><?= $stok_ozet['gunluk_hareket'] ?> Kayıt</b></div>
        </div>
    </div>

    <div class="st-main-layout">
        <div class="st-left">
            <div class="panel-lux">
                <h3><i class="fas fa-fire" style="color: var(--danger)"></i> Tedarik Bekleyen Kritik Stoklar</h3>
                <div class="k-list">
                    <?php foreach($kritik_listesi as $k): ?>
                    <div class="k-item">
                        <div class="k-info">
                            <b><?= h($k['urun_adi']) ?></b>
                            <span>Eksik Oranı: %<?= $k['eksik_yuzde'] ?> | Hedef: <?= $k['kritik_seviye'] ?></span>
                        </div>
                        <div class="k-val"><?= $k['stok_miktari'] ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="panel-lux">
                <h3><i class="fas fa-chart-area" style="color: var(--p)"></i> Haftalık Aktivite (Giriş / Çıkış)</h3>
                <div class="bar-container">
                    <?php 
                    for($i=6; $i>=0; $i--) {
                        $t = date('Y-m-d', strtotime("-$i days"));
                        $in = $pdo->query("SELECT SUM(miktar) FROM stok_hareketleri WHERE DATE(islem_tarihi)='$t' AND islem_tipi='Giriş'")->fetchColumn() ?: 0;
                        $out = $pdo->query("SELECT SUM(miktar) FROM stok_hareketleri WHERE DATE(islem_tarihi)='$t' AND islem_tipi='Çıkış'")->fetchColumn() ?: 0;
                        $m = 100; // Ölçeklendirme
                        $hi = min(120, ($in / $m) * 100); $ho = min(120, ($out / $m) * 100);
                    ?>
                    <div class="bar-group">
                        <div style="display:flex; align-items:flex-end; gap:3px; height:120px;">
                            <div class="bar" style="height:<?=$hi?>px; background:var(--success)"></div>
                            <div class="bar" style="height:<?=$ho?>px; background:var(--danger)"></div>
                        </div>
                        <small style="font-size:9px; font-weight:700;"><?= date('d.m', strtotime($t)) ?></small>
                    </div>
                    <?php } ?>
                </div>
            </div>
        </div>

        <div class="st-right">
            <div class="panel-lux">
                <h3><i class="fas fa-bolt" style="color: var(--warning)"></i> Hızlı İşlemler</h3>
                <div class="action-grid">
                    <a href="index.php?sayfa=stok-liste" class="btn-action btn-p"><i class="fas fa-plus"></i> Ürün Ekle</a>
                    <a href="index.php?sayfa=stok-liste" class="btn-action btn-s"><i class="fas fa-search"></i> Stok Bul</a>
                    <a href="index.php?sayfa=stok-hareket" class="btn-action btn-s"><i class="fas fa-exchange-alt"></i> Hareket</a>
                    <a href="index.php?sayfa=cihazlar" class="btn-action btn-s"><i class="fas fa-print"></i> Barkod</a>
                </div>
            </div>

            <div class="panel-lux">
                <h3><i class="fas fa-chart-pie" style="color: var(--info)"></i> Stok Durum Dağılımı</h3>
                <div class="dist-grid">
                    <div class="dist-box" style="background: #f0fdf4;"><small>Güvenli</small><b><?= $dist['guvenli'] ?></b></div>
                    <div class="dist-box" style="background: #fffbeb;"><small>Kritik</small><b><?= $dist['kritik'] ?></b></div>
                    <div class="dist-box" style="background: #fef2f2;"><small>Tükendi</small><b><?= $dist['sifir'] ?></b></div>
                    <div class="dist-box" style="background: #f8fafc;"><small>Toplam</small><b><?= $stok_ozet['toplam_kalem'] ?></b></div>
                </div>
            </div>

            <div class="panel-lux">
                <h3><i class="fas fa-history" style="color: var(--s)"></i> Akış</h3>
                <div class="tm-list">
                    <?php foreach($son_hareketler as $sh): ?>
                    <div class="tm-item <?= $sh['islem_tipi'] == 'Giriş' ? 'in' : 'out' ?>">
                        <b><?= h($sh['urun_adi']) ?> (<?= $sh['islem_tipi'] == 'Giriş' ? '+' : '-' ?><?= $sh['miktar'] ?>)</b>
                        <small><?= date('H:i', strtotime($sh['islem_tarihi'])) ?> | <?= h($sh['ad_soyad']) ?></small>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>