<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../functions/yardimci_fonksiyonlar.php';
require_once __DIR__ . '/../includes/ayar_fonksiyonlari.php'; // Yeni eklenen satır

// Önce sadece giriş yapılıp yapılmadığını kontrol et.
// yetkili_mi() fonksiyonu şirket de kontrol ettiği için burada henüz çağrılmıyor.
if (!isset($_SESSION['kullanici_id'])) {
    // Çıktı gönderilmeden önce header
    if (!headers_sent()) {
        header("Location: login.php");
        exit();
    } else {
        echo '<script>window.location.href = "login.php";</script>';
        exit();
    }
}

// Eğer kullanıcının şirketi varsa, normal panel verilerini yükle.
if (!empty($_SESSION['kullanici_sirketleri']) && !empty($_SESSION['aktif_sirket_id'])) {
    $aktif_sirket_id = $_SESSION['aktif_sirket_id'];
    $paraBirimi = getParaBirimiSembolu();
    $sayfa_baslik = __("dashboard");
    $stok_islemleri_aktif = get_site_setting($db, 'stok_islemleri_aktif', '0'); // Stok ayarını çek

    // İSTATİSTİKLER
    try {
        // GENEL CARİ VERİLERİ
        $stmt = $db->prepare("SELECT COUNT(*) FROM cariler WHERE sirket_id = ?");
        $stmt->execute([$aktif_sirket_id]);
        $toplam_cari = $stmt->fetchColumn();
        
        // Müşteri Alacakları (Bize Olan Borçlar)
        $stmt = $db->prepare("SELECT SUM(toplam_borc) FROM cariler WHERE sirket_id = ? AND toplam_borc > 0");
        $stmt->execute([$aktif_sirket_id]);
        $toplam_musteri_alacagi = $stmt->fetchColumn() ?: 0.0;

        // Tedarikçi Borçları (Bizim Olan Borçlar)
        $stmt = $db->prepare("SELECT 
                                (SELECT COALESCE(SUM(toplam_alacak), 0) FROM cariler WHERE sirket_id = :sirket_id1 AND toplam_alacak > 0) + 
                                (SELECT COALESCE(SUM(ABS(toplam_borc)), 0) FROM cariler WHERE sirket_id = :sirket_id2 AND toplam_borc < 0)
                            ");
        $stmt->execute([':sirket_id1' => $aktif_sirket_id, ':sirket_id2' => $aktif_sirket_id]);
        $toplam_tedarikci_borcu = $stmt->fetchColumn() ?: 0.0;

        // Net Cari Bakiye
        $stmt = $db->prepare("SELECT SUM(toplam_borc - toplam_alacak) FROM cariler WHERE sirket_id = ?");
        $stmt->execute([$aktif_sirket_id]);
        $net_cari_bakiye = $stmt->fetchColumn() ?: 0.0;

        // HESAP ÖZETLERİ
        $stmt = $db->prepare("SELECT id, hesap_adi, hesap_turu, bakiye FROM hesaplar WHERE sirket_id = ? ORDER BY hesap_adi ASC");
        $stmt->execute([$aktif_sirket_id]);
        $hesap_bakiyeleri = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $stmt = $db->prepare("SELECT SUM(bakiye) FROM hesaplar WHERE sirket_id = ?");
        $stmt->execute([$aktif_sirket_id]);
        $toplam_hesap_bakiye = $stmt->fetchColumn() ?: 0.0;

        // SON GİRİŞLER (Oturum Logları)
        $stmt = $db->prepare("
            SELECT ol.*, k.ad_soyad, k.kullanici_adi
            FROM oturum_loglari ol
            LEFT JOIN kullanicilar k ON ol.kullanici_id = k.id
            WHERE ol.sirket_id = ? AND ol.islem_tipi = 'giris'
            ORDER BY ol.olusturulma_tarihi DESC
            LIMIT 5
        ");
        $stmt->execute([$aktif_sirket_id]);
        $son_girisler = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // AYLIK GELİR-GİDER VERİLERİ (Son 6 ay)
        $aylik_veriler = [];
        for ($i = 5; $i >= 0; $i--) {
            $baslangic = date('Y-m-01', strtotime("-$i months"));
            $bitis = date('Y-m-t', strtotime("-$i months"));
            
            // Gelirler (Satışlar)
            $stmt = $db->prepare("
                SELECT COALESCE(SUM(tutar + toplam_kdv - indirim_tutari), 0) as toplam
                FROM borclar 
                WHERE sirket_id = ? AND tur = 'satis' 
                AND tarih BETWEEN ? AND ?
            ");
            $stmt->execute([$aktif_sirket_id, $baslangic, $bitis]);
            $aylik_veriler[date('m.Y', strtotime($baslangic))]['gelir'] = $stmt->fetchColumn();
            
            // Giderler (Alışlar)
            $stmt = $db->prepare("
                SELECT COALESCE(SUM(tutar + toplam_kdv - indirim_tutari), 0) as toplam
                FROM borclar 
                WHERE sirket_id = ? AND tur = 'alis' 
                AND tarih BETWEEN ? AND ?
            ");
            $stmt->execute([$aktif_sirket_id, $baslangic, $bitis]);
            $aylik_veriler[date('m.Y', strtotime($baslangic))]['gider'] = $stmt->fetchColumn();
        }

        // SON HAREKETLER (Hesap Hareketleri)
        $stmt = $db->prepare("
            SELECT hh.*, c.ad_soyad, h.hesap_adi, b.tur as borc_tur, b.aciklama as borc_aciklama
            FROM hesap_hareketleri hh
            LEFT JOIN cariler c ON hh.cari_id = c.id
            LEFT JOIN hesaplar h ON hh.hesap_id = h.id
            LEFT JOIN borclar b ON hh.borc_id = b.id
            WHERE hh.sirket_id = ?
            ORDER BY hh.tarih DESC, hh.id DESC
            LIMIT 10
        ");
        $stmt->execute([$aktif_sirket_id]);
        $son_hesap_hareketleri = $stmt->fetchAll(PDO::FETCH_ASSOC);

       // VADESİ YAKLAŞAN / GEÇMİŞ BORÇLAR
        $stmt = $db->prepare("
        SELECT b.id, b.cari_id, (b.tutar + b.toplam_kdv - b.indirim_tutari) as toplam_tutar, b.odenen_tutar, b.vade_tarihi, b.aciklama as borc_aciklama, c.ad_soyad,
               DATEDIFF(b.vade_tarihi, CURDATE()) as kalan_gun
        FROM borclar b
        JOIN cariler c ON b.cari_id = c.id
        WHERE b.tur = 'satis' AND b.sirket_id = ? AND b.durum != 'odendi' AND b.vade_tarihi IS NOT NULL
        ORDER BY b.vade_tarihi ASC LIMIT 7");
        $stmt->execute([$aktif_sirket_id]);
        $vadesi_gelen_satislar = $stmt->fetchAll(PDO::FETCH_ASSOC);

     // VADESİ YAKLAŞAN / GEÇMİŞ ÖDEMELER
        $stmt = $db->prepare("
        SELECT b.id, b.cari_id, (b.tutar + b.toplam_kdv - b.indirim_tutari) as toplam_tutar, b.odenen_tutar, b.vade_tarihi, b.aciklama as borc_aciklama, c.ad_soyad,
               DATEDIFF(b.vade_tarihi, CURDATE()) as kalan_gun
        FROM borclar b
        JOIN cariler c ON b.cari_id = c.id
        WHERE b.tur = 'alis' AND b.sirket_id = ? AND b.durum != 'odendi' AND b.vade_tarihi IS NOT NULL
        ORDER BY b.vade_tarihi ASC LIMIT 7");
        $stmt->execute([$aktif_sirket_id]);
        $vadesi_gelen_alislar = $stmt->fetchAll(PDO::FETCH_ASSOC);

    } catch(PDOException $e) {
         error_log("Ana Panel İstatistik Hatası: ".$e->getMessage());
         $_SESSION['hata'] = "Ana panel verileri yüklenirken bir hata oluştu.";
         $toplam_cari = 0; $toplam_musteri_borcu = 0.0; $toplam_tedarikci_alacagi = 0.0; $net_cari_bakiye = 0.0;
         $hesap_bakiyeleri = []; $toplam_hesap_bakiye = 0.0; $son_girisler = []; $aylik_veriler = []; $son_hesap_hareketleri = [];
         $vadesi_gelen_satislar = []; $vadesi_gelen_alislar = [];
    }

    // KISA ÖZET KUTULARI için dinamik veriler
    $toplam_satis = 0;
    $toplam_alis = 0;
    $toplam_fatura = 0;
    try {
        // Toplam Satış
        $stmt = $db->prepare("SELECT SUM(tutar + toplam_kdv - indirim_tutari) FROM borclar WHERE tur = 'satis' AND sirket_id = ?");
        $stmt->execute([$aktif_sirket_id]);
        $toplam_satis = $stmt->fetchColumn() ?: 0;
        // Toplam Alış
        $stmt = $db->prepare("SELECT SUM(tutar + toplam_kdv - indirim_tutari) FROM borclar WHERE tur = 'alis' AND sirket_id = ?");
        $stmt->execute([$aktif_sirket_id]);
        $toplam_alis = $stmt->fetchColumn() ?: 0;
        // Toplam Fatura
        $stmt = $db->prepare("SELECT COUNT(id) FROM borclar WHERE sirket_id = ?");
        $stmt->execute([$aktif_sirket_id]);
        $toplam_fatura = $stmt->fetchColumn() ?: 0;
    } catch (PDOException $e) {
        $toplam_satis = 0;
        $toplam_alis = 0;
        $toplam_fatura = 0;
    }
} else {
    // Şirketi olmayan kullanıcı için varsayılan değerler
    $sayfa_baslik = __("welcome");
}
?>
<!DOCTYPE html>
<html lang="<?= getCurrentLanguage() ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Begeb Creative 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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            background: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }

        .container {
            max-width: 1320px;
        }

        /* Modern Card Styles */
        .modern-card {
            background: white;
            border-radius: 2px;
            border: 1px solid #e2e8f0;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
        }

        .modern-card:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            transform: translateY(-2px);
        }

        /* Welcome Card */
        .welcome-card {
            background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
            border-radius: 2px;
            padding: 2rem;
            color: white;
            border: none;
            box-shadow: 0 4px 20px rgba(59, 130, 246, 0.2);
            margin-bottom: 2rem;
        }

        .welcome-card h4 {
            font-weight: 700;
            font-size: 1.5rem;
            margin-bottom: 0.5rem;
        }

        .welcome-card .text-muted {
            color: rgba(255, 255, 255, 0.8) !important;
            font-size: 0.95rem;
        }

        .welcome-card .badge {
            background: rgba(255, 255, 255, 0.2) !important;
            backdrop-filter: blur(10px);
            padding: 0.5rem 1rem;
            font-weight: 500;
            font-size: 0.875rem;
        }

        /* Quick Action Buttons */
        .quick-actions {
            background: white;
            border-radius: 2px;
            padding: 1.5rem;
            border: 1px solid #e2e8f0;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            margin-bottom: 2rem;
        }

        .quick-actions .btn {
            border-radius: 2px;
            padding: 0.75rem 1.5rem;
            font-weight: 600;
            font-size: 0.9rem;
            border-width: 2px;
            transition: all 0.3s ease;
        }

        .quick-actions .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        /* Stat Cards */
        .stat-card {
            background: white;
            border-radius: 2px;
            padding: 1.5rem;
            border: 1px solid #e2e8f0;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
            height: 100%;
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: currentColor;
        }

        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
        }

        .stat-card .icon-wrapper {
            width: 56px;
            height: 56px;
            border-radius: 2px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 1rem;
            font-size: 1.75rem;
        }

        .stat-card.primary { color: #3b82f6; }
        .stat-card.primary .icon-wrapper { background: rgba(59, 130, 246, 0.1); color: #3b82f6; }

        .stat-card.danger { color: #ef4444; }
        .stat-card.danger .icon-wrapper { background: rgba(239, 68, 68, 0.1); color: #ef4444; }

        .stat-card.success { color: #10b981; }
        .stat-card.success .icon-wrapper { background: rgba(16, 185, 129, 0.1); color: #10b981; }

        .stat-card.warning { color: #f59e0b; }
        .stat-card.warning .icon-wrapper { background: rgba(245, 158, 11, 0.1); color: #f59e0b; }

        .stat-card h6 {
            color: #64748b;
            font-size: 0.875rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-card h3 {
            color: #1e293b;
            font-size: 1.75rem;
            font-weight: 700;
            margin: 0;
        }

        /* Summary Cards */
        .summary-card {
            background: white;
            border-radius: 2px;
            padding: 1.5rem;
            border: 1px solid #e2e8f0;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
            text-align: center;
        }

        .summary-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .summary-card i {
            font-size: 2rem;
            margin-bottom: 0.75rem;
        }

        .summary-card h6 {
            color: #64748b;
            font-size: 0.875rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }

        .summary-card h4 {
            color: #1e293b;
            font-size: 1.5rem;
            font-weight: 700;
            margin: 0;
        }

        /* Section Headers */
        .section-header {
            margin-bottom: 1.5rem;
        }

        .section-header h5 {
            color: #1e293b;
            font-size: 1.125rem;
            font-weight: 700;
            margin: 0;
        }

        /* Chart Card */
        .chart-card {
            background: white;
            border-radius: 2px;
            padding: 1.5rem;
            border: 1px solid #e2e8f0;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
        }

        .chart-card .card-header {
            background: transparent;
            border: none;
            padding: 0 0 1rem 0;
        }

        .chart-card .card-header h5 {
            color: #1e293b;
            font-size: 1.125rem;
            font-weight: 700;
            margin: 0;
        }

        /* List Cards */
        .list-card {
            background: white;
            border-radius: 2px;
            border: 1px solid #e2e8f0;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }

        .list-card .card-header {
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
            padding: 1.25rem 1.5rem;
        }

        .list-card .card-header h5 {
            color: #1e293b;
            font-size: 1rem;
            font-weight: 700;
            margin: 0;
        }

        .list-card .list-group-item {
            border: none;
            border-bottom: 1px solid #f1f5f9;
            padding: 1rem 1.5rem;
            transition: all 0.2s ease;
        }

        .list-card .list-group-item:last-child {
            border-bottom: none;
        }

        .list-card .list-group-item:hover {
            background: #f8fafc;
        }

        /* Badge Styles */
        .badge-soft-primary {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
            font-weight: 600;
            border-radius: 2px;
        }

        .badge-soft-danger {
            background: rgba(239, 68, 68, 0.1);
            color: #ef4444;
            font-weight: 600;
            border-radius: 2px;
        }

        .badge-soft-success {
            background: rgba(16, 185, 129, 0.1);
            color: #10b981;
            font-weight: 600;
            border-radius: 2px;
        }

        .badge-soft-warning {
            background: rgba(245, 158, 11, 0.1);
            color: #f59e0b;
            font-weight: 600;
            border-radius: 2px;
        }

        /* Vade Status */
        .vade-gecmis {
            background-color: rgba(239, 68, 68, 0.05);
            border-left: 3px solid #ef4444;
        }

        .vade-yaklasiyor {
            background-color: rgba(245, 158, 11, 0.05);
            border-left: 3px solid #f59e0b;
        }

        .bakiye-pozitif { color: #10b981; font-weight: 600; }
        .bakiye-negatif { color: #ef4444; font-weight: 600; }

        /* Responsive */
        @media (max-width: 768px) {
            .welcome-card {
                padding: 1.5rem;
            }

            .welcome-card h4 {
                font-size: 1.25rem;
            }

            .stat-card h3 {
                font-size: 1.5rem;
            }

            .container {
                padding-left: 1rem;
                padding-right: 1rem;
            }
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>
	<?php require_once __DIR__ . '/doviz.php'; ?>
	
	
	<div class="container mt-4">
	
        <?php if (empty($_SESSION['kullanici_sirketleri']) || empty($_SESSION['aktif_sirket_id'])): ?>
            <div class="alert alert-warning text-center p-5 mt-5">
                <h3><i class="bi bi-exclamation-triangle me-2"></i> <?= __("no_company_assigned") ?></h3>
                <p class="lead"><?= __("create_company_message") ?></p>
                <a href="sirket_olustur.php" class="btn btn-lg btn-primary mt-3"><i class="bi bi-building-add me-2"></i> <?= __("create_company") ?></a>
            </div>
        <?php else: ?>
        <!-- HOŞ GELDİN BLOĞU -->
        <div class="welcome-card">
            <div class="d-flex flex-wrap align-items-center justify-content-between">
                <div>
                    <h4><?= __("welcome_user", ['name' => temizle($_SESSION['ad_soyad'] ?? 'Kullanıcı')]) ?></h4>
                    <div class="text-muted"><?= __("active_company", ['company' => temizle($_SESSION['aktif_sirket_adi'] ?? '-')]) ?></div>
                </div>
                <div class="text-end mt-3 mt-md-0">
                    <span class="badge"><?= formatDateTime(date('Y-m-d H:i:s')) ?></span>
                </div>
            </div>
        </div>

        <!-- HIZLI İŞLEM BUTONLARI BLOĞU -->
        <div class="quick-actions">
            <div class="d-flex flex-wrap gap-3 justify-content-center">
                <?php if ($stok_islemleri_aktif == '1'): ?>
                <a href="urun_ekle.php" class="btn btn-outline-success"><i class="bi bi-plus-circle me-2"></i><?= __("add_stock") ?></a>
                <?php endif; ?>
                <a href="satis_yeni.php" class="btn btn-outline-primary"><i class="bi bi-file-earmark-plus me-2"></i><?= __("create_invoice") ?></a>
                <a href="cariler.php" class="btn btn-outline-warning"><i class="bi bi-person-plus me-2"></i><?= __("add_customer") ?></a>
                <a href="yedek_islemi.php" class="btn btn-outline-info"><i class="bi bi-cloud-arrow-down me-2"></i><?= __("backup") ?></a>
            </div>
        </div>
        <!-- SİSTEM DUYURUSU/INFO BLOĞU -->
        <div class="row mb-4">
            <div class="col-12">
               <?php include "duyurular.php"; ?>
            </div>
        </div>
        <!-- İSTATİSTİK KARTLARI -->
        <div class="row g-4 mb-4">
            <div class="col-lg-3 col-md-6 col-12">
                <div class="stat-card primary">
                    <div class="icon-wrapper">
                        <i class="bi bi-people-fill"></i>
                    </div>
                    <h6><?= __("total_customers") ?></h6>
                    <h3><?= formatNumber($toplam_cari, 0) ?></h3>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 col-12">
                <div class="stat-card danger">
                    <div class="icon-wrapper">
                        <i class="bi bi-arrow-down-circle"></i>
                    </div>
                    <h6><?= __("customer_receivables") ?></h6>
                    <h3><?= formatNumber($toplam_musteri_alacagi) ?> <?= $paraBirimi ?></h3>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 col-12">
                <div class="stat-card success">
                    <div class="icon-wrapper">
                        <i class="bi bi-arrow-up-circle"></i>
                    </div>
                    <h6><?= __("supplier_debts") ?></h6>
                    <h3><?= formatNumber($toplam_tedarikci_borcu) ?> <?= $paraBirimi ?></h3>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 col-12">
                <div class="stat-card warning">
                    <div class="icon-wrapper">
                        <i class="bi bi-wallet2"></i>
                    </div>
                    <h6><?= __("net_balance") ?></h6>
                    <h3><?= formatNumber($net_cari_bakiye) ?> <?= $paraBirimi ?></h3>
                </div>
            </div>
        </div>
        <!-- KISA ÖZET KUTULARI -->
        <div class="row g-4 mb-4">
            <div class="col-md-4 col-12">
                <div class="summary-card">
                    <i class="bi bi-currency-dollar text-success"></i>
                    <h6><?= __("total_sales") ?></h6>
                    <h4><?= formatNumber($toplam_satis) ?> <?= $paraBirimi ?></h4>
                </div>
            </div>
            <div class="col-md-4 col-12">
                <div class="summary-card">
                    <i class="bi bi-bag-check text-primary"></i>
                    <h6><?= __("total_purchases") ?></h6>
                    <h4><?= formatNumber($toplam_alis) ?> <?= $paraBirimi ?></h4>
                </div>
            </div>
            <div class="col-md-4 col-12">
                <div class="summary-card">
                    <?php 
                    $kar_zarar = $toplam_satis - $toplam_alis;
                    $icon_class = $kar_zarar >= 0 ? 'bi-graph-up-arrow text-success' : 'bi-graph-down-arrow text-danger';
                    $text_class = $kar_zarar >= 0 ? 'text-success' : 'text-danger';
                    ?>
                    <i class="bi <?= $icon_class ?>"></i>
                    <h6><?= __("profit_loss") ?></h6>
                    <h4 class="<?= $text_class ?>"><?= formatNumber($kar_zarar) ?> <?= $paraBirimi ?></h4>
                </div>
            </div>
        </div>
        <!-- AYLIK GELİR-GİDER GRAFİĞİ -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="chart-card">
                    <div class="card-header">
                        <h5><i class="bi bi-graph-up-arrow me-2"></i><?= __("monthly_income_expense_chart") ?></h5>
                    </div>
                    <div class="card-body">
                        <canvas id="gelirGiderChart" height="80"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <!-- EN ÇOK SATAN ÜRÜNLER -->
        <?php if ($stok_islemleri_aktif == '1'): ?>
        <div class="row mb-4">
            <div class="col-12">
                <div class="modern-card text-center" style="padding: 2rem;">
                    <i class="bi bi-bar-chart-line" style="font-size: 2.5rem; color: #3b82f6; margin-bottom: 1rem;"></i>
                    <h5 class="mb-2"><?= __("most_sold_products") ?></h5>
                    <p class="text-muted mb-3"><?= __("detailed_sales_report") ?></p>
                    <a href="en_cok_satan_urunler.php" class="btn btn-primary" style="border-radius: 2px; padding: 0.625rem 1.5rem;">
                        <i class="bi bi-arrow-right-circle me-2"></i><?= __("detailed_sales_report") ?>
                    </a>
                </div>
            </div>
        </div>
        <?php endif; ?>
        <!-- SON GİRİŞLER -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="list-card">
                    <div class="card-header">
                        <h5><i class="bi bi-clock-history me-2"></i><?= __("recent_logins") ?></h5>
                    </div>
                    <div class="card-body p-0">
                        <ul class="list-group list-group-flush">
                            <?php foreach($son_girisler as $giris): ?>
                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                <span style="color: #64748b; font-size: 0.875rem;"><?= formatDateTime($giris['olusturulma_tarihi']) ?></span>
                                <span class="badge-soft-primary" style="padding: 0.375rem 0.75rem; border-radius: 2px; font-size: 0.8125rem;">
                                    <?= temizle($giris['ad_soyad'] ?? $giris['kullanici_adi']) ?>
                                </span>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        


        <div class="row g-4">
            <div class="col-lg-7">
                 <div class="list-card mb-4">
                    <div class="card-header">
                        <h5><i class="bi bi-wallet2 me-2"></i><?= __("account_balances") ?></h5>
                    </div>
                    <div class="card-body">
                         <?php if (empty($hesap_bakiyeleri)): ?>
                             <p class="text-muted" style="padding: 1rem;"><?= __("no_accounts_added") ?></p>
                         <?php else: ?>
                             <ul class="list-group list-group-flush">
                                <?php foreach($hesap_bakiyeleri as $hesap): ?>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    <div>
                                        <i class="bi bi-<?= $hesap['hesap_turu'] == 'banka' ? 'bank' : ($hesap['hesap_turu'] == 'kasa' ? 'cash-stack' : 'credit-card') ?> me-2" style="color: #64748b;"></i>
                                        <a href="hesap_hareketleri.php?hesap_id=<?= $hesap['id'] ?>" class="text-decoration-none stretched-link" style="color: #1e293b; font-weight: 600;">
                                            <?= temizle($hesap['hesap_adi']) ?>
                                        </a>
                                        <small class="text-muted d-block ms-4" style="font-size: 0.8125rem;"><?= __($hesap['hesap_turu']) ?></small>
                                    </div>
                                    <span class="<?= $hesap['bakiye'] >= 0 ? 'bakiye-pozitif' : 'bakiye-negatif' ?>" style="font-size: 1rem;">
                                        <?= formatNumber($hesap['bakiye']) ?> <?= $paraBirimi ?>
                                    </span>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                         <?php endif; ?>
                     </div>
                 </div>

                <div class="list-card">
                     <div class="card-header">
                        <h5><i class="bi bi-clock-history me-2"></i><?= __("recent_account_movements") ?></h5>
                    </div>
                    <div class="card-body p-0">
                         <?php if (empty($son_hesap_hareketleri)): ?>
                             <p class="text-muted p-3"><?= __("no_movements_recorded") ?></p>
                         <?php else: ?>
                         <ul class="list-group list-group-flush">
                            <?php foreach($son_hesap_hareketleri as $hareket): 
                                $icon = '';
                                $color = '';
                                $prefix = '';

                                switch ($hareket['tur']) {
                                    case 'giris':
                                        $icon = 'bi-arrow-down-circle-fill';
                                        $color = 'text-success';
                                        $prefix = '+';
                                        $movement_type = __("income_movement");
                                        break;
                                    case 'cikis':
                                        $icon = 'bi-arrow-up-circle-fill';
                                        $color = 'text-danger';
                                        $prefix = '-';
                                        $movement_type = __("expense_movement");
                                        break;
                                    case 'transfer':
                                        $icon = 'bi-arrow-left-right';
                                        $color = 'text-info';
                                        $movement_type = __("transfer_movement");
                                        break;
                                }
                            ?>
                            <li class="list-group-item px-3 py-3">
                                <div class="d-flex align-items-center">
                                    <div class="me-3">
                                        <i class="bi <?= $icon ?> fs-4 <?= $color ?>"></i>
                                    </div>
                                    <div class="flex-grow-1">
                                        <div class="d-flex justify-content-between">
                                            <p class="mb-0 fw-bold">
                                                <?= temizle($hareket['aciklama']) ?>
                                                <?php if ($hareket['ad_soyad']): ?>
                                                    <small class="text-muted">(<?= temizle($hareket['ad_soyad']) ?>)</small>
                                                <?php endif; ?>
                                            </p>
                                            <p class="mb-0 fw-bold <?= $color ?>">
                                                <?= $prefix ?><?= formatNumber($hareket['tutar']) ?> <?= $paraBirimi ?>
                                            </p>
                                        </div>
                                        <small class="text-muted">
                                            <i class="bi bi-calendar-event"></i> <?= formatDateTime($hareket['tarih']) ?> | 
                                            <i class="bi bi-wallet2"></i> <?= temizle($hareket['hesap_adi']) ?>
                                        </small>
                                    </div>
                                </div>
                            </li>
                            <?php endforeach; ?>
                         </ul>
                        <div class="text-center" style="padding: 1rem; background: #f8fafc; border-top: 1px solid #e2e8f0;">
                            <a href="hesap_hareketleri.php" class="btn btn-outline-primary" style="border-radius: 2px; padding: 0.5rem 1.5rem; font-size: 0.875rem; font-weight: 600;"><?= __("view_all_movements") ?></a>
                        </div>
                         <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="col-lg-5">
                <div class="list-card mb-4">
                     <div class="card-header">
                        <h5><i class="bi bi-calendar-check me-2"></i><?= __("upcoming_due_receivables") ?></h5>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($vadesi_gelen_satislar)): ?>
                            <p class="text-muted p-3"><?= __("no_due_receivables") ?></p>
                        <?php else: ?>
                        <ul class="list-group list-group-flush">
                             <?php foreach($vadesi_gelen_satislar as $borc):
                                 $kalan_gun = $borc['kalan_gun'];
                                 $vade_class = '';
                                 if ($kalan_gun !== null) {
                                     if ($kalan_gun < 0) $vade_class = 'vade-gecmis';
                                     elseif ($kalan_gun <= 7) $vade_class = 'vade-yaklasiyor';
                                 }
                             ?>
                             <li class="list-group-item list-group-item-action <?= $vade_class ?>">
                                <a href="cari_detay.php?id=<?= $borc['cari_id'] ?>" class="text-decoration-none text-dark stretched-link">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1"><?= temizle($borc['ad_soyad']) ?></h6>
                                        <small class="text-muted"><?= formatDate($borc['vade_tarihi']) ?></small>
                                    </div>
                                    <p class="mb-1 small text-muted"><?= temizle($borc['borc_aciklama'] ?: 'Açıklama yok') ?></p>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <small class="text-danger fw-bold"><?= formatNumber($borc['toplam_tutar']) ?> <?= $paraBirimi ?></small>
                                         <?php if ($kalan_gun !== null): ?>
                                            <small class="badge rounded-pill <?= $kalan_gun < 0 ? 'bg-danger' : ($kalan_gun <= 7 ? 'bg-warning text-dark' : 'bg-secondary') ?>">
                                                 <?= $kalan_gun < 0 ? abs($kalan_gun) . ' ' . __("days_overdue", ['days' => abs($kalan_gun)]) : ($kalan_gun == 0 ? __("due_today") : __("days_remaining", ['days' => $kalan_gun])) ?>
                                             </small>
                                        <?php endif; ?>
                                    </div>
                                </a>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="list-card">
                    <div class="card-header">
                        <h5><i class="bi bi-calendar-x me-2"></i><?= __("upcoming_due_payments") ?></h5>
                    </div>
                     <div class="card-body p-0">
                         <?php if (empty($vadesi_gelen_alislar)): ?>
                            <p class="text-muted p-3"><?= __("no_due_payments") ?></p>
                        <?php else: ?>
                        <ul class="list-group list-group-flush">
                             <?php foreach($vadesi_gelen_alislar as $borc):
                                 $kalan_gun = $borc['kalan_gun'];
                                 $vade_class = '';
                                 if ($kalan_gun !== null) {
                                     if ($kalan_gun < 0) $vade_class = 'vade-gecmis';
                                     elseif ($kalan_gun <= 7) $vade_class = 'vade-yaklasiyor';
                                 }
                             ?>
                             <li class="list-group-item list-group-item-action <?= $vade_class ?>">
                                <a href="cari_detay.php?id=<?= $borc['cari_id'] ?>" class="text-decoration-none text-dark stretched-link">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1"><?= temizle($borc['ad_soyad']) ?></h6>
                                        <small class="text-muted"><?= formatDate($borc['vade_tarihi']) ?></small>
                                    </div>
                                    <p class="mb-1 small text-muted"><?= temizle($borc['borc_aciklama'] ?: 'Açıklama yok') ?></p>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <small class="text-success fw-bold"><?= formatNumber($borc['toplam_tutar']) ?> <?= $paraBirimi ?></small>
                                         <?php if ($kalan_gun !== null): ?>
                                            <small class="badge rounded-pill <?= $kalan_gun < 0 ? 'bg-danger' : ($kalan_gun <= 7 ? 'bg-warning text-dark' : 'bg-secondary') ?>">
                                                 <?= $kalan_gun < 0 ? abs($kalan_gun) . ' ' . __("days_overdue", ['days' => abs($kalan_gun)]) : ($kalan_gun == 0 ? __("due_today") : __("days_remaining", ['days' => $kalan_gun])) ?>
                                             </small>
                                        <?php endif; ?>
                                    </div>
                                </a>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
		
	<?php include __DIR__ . '/../includes/footer.php'; ?>
		
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Aylık Gelir-Gider Grafiği
        document.addEventListener('DOMContentLoaded', function() {
            const ctx = document.getElementById('gelirGiderChart').getContext('2d');
            
            // PHP'den gelen verileri JavaScript'e aktar
            const aylikVeriler = <?= json_encode($aylik_veriler) ?>;
            
            // Verileri grafik için hazırla
            const labels = Object.keys(aylikVeriler).map(tarih => {
                const [ay, yil] = tarih.split('.');
                const date = new Date(yil, ay - 1);
                return date.toLocaleString('tr-TR', { month: 'long' });
            });
            
            const gelirData = Object.values(aylikVeriler).map(veri => veri.gelir);
            const giderData = Object.values(aylikVeriler).map(veri => veri.gider);
            
            const myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: '<?= __("income") ?>',
                            data: gelirData,
                            backgroundColor: 'rgba(40, 167, 69, 0.7)',
                            borderColor: 'rgba(40, 167, 69, 1)',
                            borderWidth: 1
                        },
                        {
                            label: '<?= __("expense") ?>',
                            data: giderData,
                            backgroundColor: 'rgba(220, 53, 69, 0.7)',
                            borderColor: 'rgba(220, 53, 69, 1)',
                            borderWidth: 1
                        }
                    ]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return value.toLocaleString('tr-TR') + ' <?= $paraBirimi ?>';
                                }
                            }
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return context.dataset.label + ': ' + context.raw.toLocaleString('tr-TR') + ' <?= $paraBirimi ?>';
                                }
                            }
                        }
                    }
                }
            });
        });
    </script>
</body>
</html>
