<?php
require_once __DIR__ . '/../includes/config.php';
yetkili_mi('kullanici'); // Kullanıcı ve üstü erişebilir

$sayfa_baslik = __("stock_detail_analysis");
$aktif_sirket_id = $_SESSION['aktif_sirket_id'] ?? 0;

// Ürün ID'sini al
$urun_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$urun_id) {
    $_SESSION['hata'] = __("invalid_product_id");
    header("Location: urunler.php");
    exit();
}

// Ürün bilgilerini al
try {
    $stmt_urun = $db->prepare("
        SELECT u.*, k.kategori_adi, c.ad_soyad as tedarikci_adi, ms.miktar as mevcut_stok, ms.ortalama_maliyet
        FROM urunler u 
        LEFT JOIN kategoriler k ON u.kategori_id = k.id AND k.sirket_id = ?
        LEFT JOIN cariler c ON u.tedarikci_id = c.id AND c.sirket_id = ?
        LEFT JOIN mevcut_stok ms ON u.id = ms.urun_id AND ms.sirket_id = ?
        WHERE u.id = ? AND u.sirket_id = ?
    ");
    $stmt_urun->execute([$aktif_sirket_id, $aktif_sirket_id, $aktif_sirket_id, $urun_id, $aktif_sirket_id]);
    $urun = $stmt_urun->fetch(PDO::FETCH_ASSOC);
    
    if (!$urun) {
        $_SESSION['hata'] = __("product_not_found");
        header("Location: urunler.php");
        exit();
    }
    
    $sayfa_baslik = __("stock_detail") . ": " . temizle($urun['urun_adi']);
    
    // Depo yönetimi modülünü kontrol et ve depo/raf bilgilerini getir
    require_once __DIR__ . '/../functions/stok_fonksiyonlari.php';
    $depo_yonetimi_aktif = depoYonetimiAktifMi($db, $aktif_sirket_id);
    $urun_depo_raf = [];
    if ($depo_yonetimi_aktif) {
        $urun_depo_raf = depoRafStokGetir($db, $urun_id, $aktif_sirket_id);
    }
} catch (PDOException $e) {
    $_SESSION['hata'] = __("error_loading_product_info");
    header("Location: urunler.php");
    exit();
}

// Filtreleme parametreleri
$cari_id_filter = filter_input(INPUT_GET, 'cari_id', FILTER_VALIDATE_INT);
$hareket_turu_filter = filter_input(INPUT_GET, 'hareket_turu', FILTER_SANITIZE_SPECIAL_CHARS);
$baslangic_tarihi = filter_input(INPUT_GET, 'baslangic_tarihi', FILTER_SANITIZE_SPECIAL_CHARS);
$bitis_tarihi = filter_input(INPUT_GET, 'bitis_tarihi', FILTER_SANITIZE_SPECIAL_CHARS);

// Varsayılan tarih aralığı (son 1 yıl)
if (!$baslangic_tarihi) {
    $baslangic_tarihi = date('Y-m-d', strtotime('-1 year'));
}
if (!$bitis_tarihi) {
    $bitis_tarihi = date('Y-m-d');
}

// Stok hareketlerini al
$params = [$aktif_sirket_id, $aktif_sirket_id, $aktif_sirket_id, $urun_id];
$sql_hareketler = "
    SELECT sh.*, c.ad_soyad as cari_adi, b.tur as fatura_tipi, b.tarih as fatura_tarihi,
           k.ad_soyad as kullanici_adi
    FROM stok_hareketleri sh
    LEFT JOIN cariler c ON sh.cari_id = c.id AND c.sirket_id = ?
    LEFT JOIN borclar b ON sh.borc_id = b.id AND b.sirket_id = ?
    LEFT JOIN kullanicilar k ON sh.kullanici_id = k.id
    WHERE sh.sirket_id = ? AND sh.urun_id = ?
";

if ($cari_id_filter) {
    $sql_hareketler .= " AND sh.cari_id = ?";
    $params[] = $cari_id_filter;
}

if ($hareket_turu_filter) {
    $sql_hareketler .= " AND sh.hareket_turu = ?";
    $params[] = $hareket_turu_filter;
}

if ($baslangic_tarihi) {
    $sql_hareketler .= " AND DATE(sh.tarih) >= ?";
    $params[] = $baslangic_tarihi;
}

if ($bitis_tarihi) {
    $sql_hareketler .= " AND DATE(sh.tarih) <= ?";
    $params[] = $bitis_tarihi;
}

$sql_hareketler .= " ORDER BY sh.tarih DESC";

try {
    $stmt_hareketler = $db->prepare($sql_hareketler);
    $stmt_hareketler->execute($params);
    $stok_hareketleri = $stmt_hareketler->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Stok hareketleri çekilirken hata: " . $e->getMessage());
    $stok_hareketleri = [];
}

// İstatistikleri hesapla
$toplam_giris = 0;
$toplam_cikis = 0;
$toplam_giris_tutar = 0;
$toplam_cikis_tutar = 0;
$toplam_kar_zarar = 0;

foreach ($stok_hareketleri as $hareket) {
    if ($hareket['hareket_turu'] == 'giris') {
        $toplam_giris += $hareket['miktar'];
        $toplam_giris_tutar += $hareket['toplam_tutar'] ?? 0;
    } elseif ($hareket['hareket_turu'] == 'cikis') {
        $toplam_cikis += $hareket['miktar'];
        $toplam_cikis_tutar += $hareket['toplam_tutar'] ?? 0;
    }
}

// Kar/zarar hesaplama (ortalama maliyet üzerinden)
if ($urun['ortalama_maliyet'] > 0) {
    $toplam_kar_zarar = ($toplam_cikis_tutar - ($toplam_cikis * $urun['ortalama_maliyet']));
}

// Cari listesi (filtreleme için)
$stmt_cariler = $db->prepare("SELECT id, ad_soyad FROM cariler WHERE sirket_id = ? ORDER BY ad_soyad");
$stmt_cariler->execute([$aktif_sirket_id]);
$cariler = $stmt_cariler->fetchAll(PDO::FETCH_ASSOC);

// Çoklu para birimi durumunu kontrol et
try {
    $stmt_coklu_pb = $db->prepare("SELECT coklu_para_birimi, para_birimi FROM sirketler WHERE id = ?");
    $stmt_coklu_pb->execute([$aktif_sirket_id]);
    $sirket_ayarlari = $stmt_coklu_pb->fetch(PDO::FETCH_ASSOC);
    $coklu_para_birimi_aktif = (bool) ($sirket_ayarlari['coklu_para_birimi'] ?? 0);
    $sirket_para_birimi = $sirket_ayarlari['para_birimi'] ?? 'TL';
} catch (PDOException $e) {
    $coklu_para_birimi_aktif = 0;
    $sirket_para_birimi = 'TL';
}

$paraBirimi = getParaBirimiSembolu();
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= temizle($sayfa_baslik) ?> - <?= __("stock_management") ?></title>
    <meta name="description" content="<?= temizle($urun['urun_adi']) ?> ürününün detaylı stok analizi, giriş-çıkış hareketleri ve kar/zarar hesaplamaları">
    <meta name="keywords" content="trafo, stok yönetimi, <?= temizle($urun['urun_adi']) ?>, stok analizi, kar zarar hesaplama">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        /* Ürün Bilgi Kartı */
        .product-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            border-radius: 15px 15px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .product-title-section {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .product-icon {
            background: rgba(255, 255, 255, 0.2);
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }
        
        .product-title {
            font-size: 1.8rem;
            font-weight: bold;
            margin: 0;
            line-height: 1.2;
        }
        
        .product-meta {
            margin-top: 0.5rem;
        }
        
        .product-actions {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }
        
        .product-details-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
            padding: 2rem;
            background: #f8f9fa;
        }
        
        .detail-card {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1.5rem;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }
        
        .detail-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .detail-icon {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            width: 50px;
            height: 50px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
        }
        
        .detail-content {
            flex: 1;
        }
        
        .detail-label {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 0.25rem;
            font-weight: 500;
        }
        
        .detail-value {
            font-size: 1.1rem;
            font-weight: 600;
            color: #212529;
        }
        
        /* İstatistik Kartları */
        .stats-icon-wrapper {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto;
            font-size: 1.5rem;
        }
        
        .stats-icon-wrapper.success {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
        }
        
        .stats-icon-wrapper.info {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }
        
        .stats-icon-wrapper.danger {
            background: linear-gradient(135deg, #fc466b 0%, #3f5efb 100%);
            color: white;
        }
        
        .stats-icon-wrapper.warning {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
            color: white;
        }
        
        .stats-icon {
            color: white;
        }
        
        .stats-number {
            margin-bottom: 0.5rem;
        }
        
        .stats-label {
            font-weight: 500;
            margin-bottom: 0.25rem;
        }
        
        .stats-subtitle {
            font-size: 0.8rem;
        }
        
        /* Fiyat Kartları */
        .price-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f3f4;
        }
        
        .price-item:last-child {
            border-bottom: none;
        }
        
        .price-item.highlight {
            background: rgba(0,0,0,0.02);
            margin: 0 -1rem;
            padding: 1rem;
            border-radius: 8px;
        }
        
        .price-label {
            font-weight: 500;
            color: #6c757d;
        }
        
        .price-value {
            font-weight: 600;
            font-size: 1.1rem;
        }
        
        /* Genel Stiller */
        .filter-section {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 20px;
            padding: 2rem;
            margin-bottom: 2rem;
            border: 1px solid #dee2e6;
            box-shadow: 0 4px 6px rgba(0,0,0,0.05);
        }
        
        .filter-header {
            border-bottom: 2px solid #dee2e6;
            padding-bottom: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .filter-header h5 {
            color: #495057;
            font-weight: 600;
        }
        
        .form-label {
            color: #495057;
            font-size: 0.9rem;
        }
        
        .form-select-lg, .form-control-lg {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
        }
        
        .form-select-lg:focus, .form-control-lg:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .btn-lg {
            border-radius: 10px;
            font-weight: 500;
            padding: 0.75rem 1.5rem;
        }
        
        .table-responsive-custom {
            overflow-x: auto;
        }
        
        @media (max-width: 768px) {
            .table-responsive-custom table {
                width: 100%;
                min-width: 800px;
            }
            
            .product-header {
                flex-direction: column;
                text-align: center;
            }
            
            .product-details-grid {
                grid-template-columns: 1fr;
                padding: 1rem;
            }
        }
        
        .badge-hareket {
            font-size: 0.8rem;
            padding: 0.5rem 0.75rem;
        }
        
        /* Sayfa Başlığı */
        .page-header {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 2rem;
            border-radius: 15px;
            border: 1px solid #dee2e6;
        }
        
        .page-title {
            font-size: 2.2rem;
            font-weight: 700;
            color: #212529;
            margin: 0;
            line-height: 1.2;
        }
        
        .page-subtitle {
            font-size: 1.1rem;
            margin-top: 0.5rem;
        }
        
        .page-actions {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }
        
        @media (max-width: 768px) {
            .page-header .d-flex {
                flex-direction: column;
                text-align: center;
                gap: 1rem;
            }
            
            .page-title {
                font-size: 1.8rem;
            }
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <div class="container mt-4">
        <div class="page-header mb-4">
            <div class="d-flex justify-content-between align-items-center">
                <div class="page-title-section">
                    <h2 class="page-title">
                        <i class="bi bi-box-seam text-primary me-3"></i>
                        <?= temizle($sayfa_baslik) ?>
                    </h2>
                    <p class="page-subtitle text-muted mb-0">
                        Ürün detayları, stok hareketleri ve finansal analiz
						<span class="badge bg-primary me-2">ID: #<?= $urun_id ?></span>
                                <span class="badge bg-secondary me-2"><?= temizle($urun['kategori_adi'] ?? __('uncategorized')) ?></span>
                                <span class="badge bg-info"><?= temizle($urun['birim']) ?></span>
                            
                    </p>
                </div>
                <div class="page-actions">
                    <a href="urunler.php" class="btn btn-outline-secondary me-2">
                        <i class="bi bi-arrow-left me-1"></i> <?= __('product_list') ?>
                    </a>
                    <a href="stok_hareketleri.php" class="btn btn-outline-primary">
                        <i class="bi bi-list-ul me-1"></i> <?= __('all_movements') ?>
                    </a>
                </div>
            </div>
        </div>

        <?php if (isset($_SESSION['mesaj'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?= $_SESSION['mesaj'] ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['mesaj']); ?>
        <?php endif; ?>

        <?php if (isset($_SESSION['hata'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?= $_SESSION['hata'] ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['hata']); ?>
        <?php endif; ?>

     

        <!-- İstatistik Kartları -->
        <div class="row mb-4">
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body text-center p-4">
                        <div class="stats-icon-wrapper success mb-3">
                            <i class="bi bi-box-seam stats-icon"></i>
                        </div>
                        <div class="stats-number text-success fw-bold fs-3"><?= number_format($urun['mevcut_stok'] ?? 0, 2) ?></div>
                        <div class="stats-label text-muted"><?= __('current_stock') ?></div>
                        <div class="stats-subtitle small text-muted"><?= __('current_quantity') ?></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body text-center p-4">
                        <div class="stats-icon-wrapper info mb-3">
                            <i class="bi bi-arrow-down-circle stats-icon"></i>
                        </div>
                        <div class="stats-number text-info fw-bold fs-3"><?= number_format($toplam_giris, 2) ?></div>
                        <div class="stats-label text-muted"><?= __('total_entry') ?></div>
                        <div class="stats-subtitle small text-muted"><?= __('all_time') ?></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body text-center p-4">
                        <div class="stats-icon-wrapper danger mb-3">
                            <i class="bi bi-arrow-up-circle stats-icon"></i>
                        </div>
                        <div class="stats-number text-danger fw-bold fs-3"><?= number_format($toplam_cikis, 2) ?></div>
                        <div class="stats-label text-muted"><?= __('total_exit') ?></div>
                        <div class="stats-subtitle small text-muted"><?= __('all_time') ?></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body text-center p-4">
                        <div class="stats-icon-wrapper <?= $toplam_kar_zarar >= 0 ? 'success' : 'danger' ?> mb-3">
                            <i class="bi bi-graph-up-arrow stats-icon"></i>
                        </div>
                        <div class="stats-number <?= $toplam_kar_zarar >= 0 ? 'text-success' : 'text-danger' ?> fw-bold fs-3"><?= number_format($toplam_kar_zarar, 2) ?></div>
                        <div class="stats-label text-muted"><?= __('profit_loss') ?></div>
                        <div class="stats-subtitle small text-muted"><?= $paraBirimi ?> <?= __('in_currency') ?></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Depo ve Raf Bilgileri -->
        <?php if ($depo_yonetimi_aktif && !empty($urun_depo_raf)): ?>
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-0 py-3">
                <h5 class="mb-0">
                    <i class="bi bi-building me-2 text-primary"></i><?= __('warehouse_shelf_distribution') ?>
                </h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th><?= __('warehouse') ?></th>
                                <th><?= __('shelf') ?></th>
                                <th class="text-end"><?= __('stock') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($urun_depo_raf as $item): ?>
                            <tr>
                                <td>
                                    <?php if ($item['depo_adi']): ?>
                                        <i class="bi bi-building me-1 text-primary"></i>
                                        <strong><?= temizle($item['depo_adi']) ?></strong>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($item['raf_adi']): ?>
                                        <i class="bi bi-bookshelf me-1 text-info"></i>
                                        <strong><?= temizle($item['raf_adi']) ?></strong>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end">
                                    <span class="badge bg-success fs-6">
                                        <?= number_format($item['miktar'], 2, ',', '.') ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Fiyat ve Stok Bilgileri -->
        <div class="row mb-4">
            <div class="col-lg-4 col-md-6 mb-3">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-success bg-gradient text-white border-0">
                        <div class="d-flex align-items-center">
                            <i class="bi bi-currency-dollar me-2"></i>
                            <h6 class="mb-0"><?= __('purchase_prices') ?></h6>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="price-item">
                            <div class="price-label"><?= __('purchase_price') ?> 1</div>
                            <div class="price-value text-success"><?= number_format($urun['alis_fiyati'], 2) ?> <?= $paraBirimi ?></div>
                        </div>
                        <?php if ($urun['alis_fiyati2'] > 0): ?>
                        <div class="price-item">
                            <div class="price-label"><?= __('purchase_price_2') ?></div>
                            <div class="price-value text-success"><?= number_format($urun['alis_fiyati2'], 2) ?> <?= $paraBirimi ?></div>
                        </div>
                        <?php endif; ?>
                        <hr class="my-3">
                        <div class="price-item highlight">
                            <div class="price-label"><?= __('average_cost') ?></div>
                            <div class="price-value text-success fw-bold"><?= number_format($urun['ortalama_maliyet'] ?? 0, 2) ?> <?= $paraBirimi ?></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 col-md-6 mb-3">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-primary bg-gradient text-white border-0">
                        <div class="d-flex align-items-center">
                            <i class="bi bi-tag me-2"></i>
                            <h6 class="mb-0"><?= __('sales_prices') ?></h6>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="price-item">
                            <div class="price-label"><?= __('sale_price') ?> 1</div>
                            <div class="price-value text-primary"><?= number_format($urun['satis_fiyati'], 2) ?> <?= $paraBirimi ?></div>
                        </div>
                        <?php if ($urun['satis_fiyati2'] > 0): ?>
                        <div class="price-item">
                            <div class="price-label"><?= __('sale_price_2') ?></div>
                            <div class="price-value text-primary"><?= number_format($urun['satis_fiyati2'], 2) ?> <?= $paraBirimi ?></div>
                        </div>
                        <?php endif; ?>
                        <hr class="my-3">
                        <div class="price-item highlight">
                            <div class="price-label"><?= __('profit_margin_1') ?></div>
                            <div class="price-value text-primary fw-bold"><?= $urun['alis_fiyati'] > 0 ? number_format((($urun['satis_fiyati'] - $urun['alis_fiyati']) / $urun['alis_fiyati']) * 100, 1) : 0 ?>%</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 col-md-6 mb-3">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-warning bg-gradient text-dark border-0">
                        <div class="d-flex align-items-center">
                            <i class="bi bi-graph-up me-2"></i>
                            <h6 class="mb-0"><?= __('stock_status') ?></h6>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="price-item">
                            <div class="price-label"><?= __('critical_stock') ?>:</div>
                            <div class="price-value"><?= number_format($urun['kritik_stok'], 0) ?></div>
                        </div>
                        <div class="price-item">
                            <div class="price-label"><?= __('stock_value') ?>:</div>
                            <div class="price-value text-info"><?= number_format(($urun['mevcut_stok'] ?? 0) * ($urun['ortalama_maliyet'] ?? 0), 2) ?> <?= $paraBirimi ?></div>
                        </div>
                        <hr class="my-3">
                      </div>
                </div>
            </div>
        </div>

        <!-- Filtreleme Bölümü -->
        <div class="filter-section">
            <div class="filter-header">
                <h5 class="mb-0">
                    <i class="bi bi-funnel-fill text-primary me-2"></i>
                    <?= __('filter_options') ?>
                </h5>
                <p class="text-muted mb-0 small"><?= __('filter_description') ?></p>
            </div>
            <form method="get" class="row g-3 mt-3">
                <input type="hidden" name="id" value="<?= $urun_id ?>">
                
                <div class="col-lg-3 col-md-6">
                    <label for="cari_id" class="form-label fw-bold">
                        <i class="bi bi-people me-1"></i> <?= __('customer_supplier') ?>
                    </label>
                    <select class="form-select form-select-lg" id="cari_id" name="cari_id">
                        <option value=""><?= __('all') ?></option>
                        <?php foreach ($cariler as $cari): ?>
                            <option value="<?= $cari['id'] ?>" <?= $cari_id_filter == $cari['id'] ? 'selected' : '' ?>>
                                <?= temizle($cari['ad_soyad']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-lg-2 col-md-6">
                    <label for="hareket_turu" class="form-label fw-bold">
                        <i class="bi bi-arrow-left-right me-1"></i> <?= __('movement_type') ?>
                    </label>
                    <select class="form-select form-select-lg" id="hareket_turu" name="hareket_turu">
                        <option value=""><?= __('all') ?></option>
                        <option value="giris" <?= $hareket_turu_filter == 'giris' ? 'selected' : '' ?>><?= __('entry') ?></option>
                        <option value="cikis" <?= $hareket_turu_filter == 'cikis' ? 'selected' : '' ?>><?= __('exit') ?></option>
                        <option value="sayim" <?= $hareket_turu_filter == 'sayim' ? 'selected' : '' ?>><?= __('inventory') ?></option>
                        <option value="transfer" <?= $hareket_turu_filter == 'transfer' ? 'selected' : '' ?>><?= __('transfer') ?></option>
                    </select>
                </div>
                
                <div class="col-lg-2 col-md-6">
                    <label for="baslangic_tarihi" class="form-label fw-bold">
                        <i class="bi bi-calendar-event me-1"></i> <?= __('start_date') ?>
                    </label>
                    <input type="date" class="form-control form-control-lg" id="baslangic_tarihi" name="baslangic_tarihi" value="<?= $baslangic_tarihi ?>">
                </div>
                
                <div class="col-lg-2 col-md-6">
                    <label for="bitis_tarihi" class="form-label fw-bold">
                        <i class="bi bi-calendar-check me-1"></i> <?= __('end_date') ?>
                    </label>
                    <input type="date" class="form-control form-control-lg" id="bitis_tarihi" name="bitis_tarihi" value="<?= $bitis_tarihi ?>">
                </div>
                
                <div class="col-lg-3 col-md-12 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary btn-lg me-2 flex-fill">
                        <i class="bi bi-search me-1"></i> <?= __('filter') ?>
                    </button>
                    <a href="?id=<?= $urun_id ?>" class="btn btn-outline-secondary btn-lg">
                        <i class="bi bi-arrow-clockwise"></i>
                    </a>
                </div>
            </form>
        </div>

        <!-- Stok Hareketleri Tablosu -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-list-ul"></i> <?= __("stock_movements") ?> (<?= count($stok_hareketleri) ?> <?= __("records") ?>)</h5>
                <div>
                    <span class="badge bg-success"><?= __("entry") ?>: <?= number_format($toplam_giris, 2) ?></span>
                    <span class="badge bg-danger ms-2"><?= __("exit") ?>: <?= number_format($toplam_cikis, 2) ?></span>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive table-responsive-custom">
                    <table class="table table-hover table-striped mb-0">
                        <thead class="table-light">
                            <tr>
                                <th><?= __('date') ?></th>
                                <th><?= __('movement_type') ?></th>
                                <th><?= __('amount') ?></th>
                                <th><?= __('unit_price') ?></th>
                                <th><?= __('total_amount') ?></th>
                                <th><?= __('customer_supplier') ?></th>
                                <th><?= __('invoice_info') ?></th>
                                <th><?= __('description') ?></th>
                                <th><?= __('user') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($stok_hareketleri)): ?>
                                <tr>
                                    <td colspan="9" class="text-center py-4">
                                        <i class="bi bi-inbox text-muted" style="font-size: 2rem;"></i>
                                        <div class="text-muted mt-2"><?= __('no_movements_found') ?></div>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($stok_hareketleri as $hareket): ?>
                                    <tr class="<?= ($hareket['hareket_turu'] == 'giris') ? 'table-success' : 'table-danger' ?>">
                                        <td>
                                            <div class="fw-bold"><?= date('d.m.Y', strtotime($hareket['tarih'])) ?></div>
                                            <small class="text-muted"><?= date('H:i', strtotime($hareket['tarih'])) ?></small>
                                        </td>
                                        <td>
                                            <?php 
                                            $hareket_icon = '';
                                            $hareket_class = '';
                                            $hareket_text = '';
                                            
                                            switch($hareket['hareket_turu']) {
                                                case 'giris':
                                                    $hareket_icon = 'bi-arrow-down-left';
                                                    $hareket_class = 'bg-success';
                                                    $hareket_text = __('entry');
                                                    break;
                                                case 'cikis':
                                                    $hareket_icon = 'bi-arrow-up-right';
                                                    $hareket_class = 'bg-danger';
                                                    $hareket_text = __('exit');
                                                    break;
                                                case 'sayim':
                                                    $hareket_icon = 'bi-clipboard-check';
                                                    $hareket_class = 'bg-info';
                                                    $hareket_text = __('inventory');
                                                    break;
                                                case 'transfer':
                                                    $hareket_icon = 'bi-arrow-left-right';
                                                    $hareket_class = 'bg-warning';
                                                    $hareket_text = __('transfer');
                                                    break;
                                            }
                                            ?>
                                            <span class="badge <?= $hareket_class ?> badge-hareket">
                                                <i class="bi <?= $hareket_icon ?>"></i> <?= $hareket_text ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="fw-bold"><?= number_format($hareket['miktar'], 2) ?></span>
                                            <small class="text-muted d-block"><?= temizle($urun['birim']) ?></small>
                                        </td>
                                        <td>
                                            <?php if ($hareket['birim_fiyat']): ?>
                                                <span class="fw-bold"><?= number_format($hareket['birim_fiyat'], 2) ?></span>
                                                <small class="text-muted d-block"><?= $paraBirimi ?></small>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($hareket['toplam_tutar']): ?>
                                                <span class="fw-bold"><?= number_format($hareket['toplam_tutar'], 2) ?></span>
                                                <small class="text-muted d-block"><?= $paraBirimi ?></small>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($hareket['cari_adi']): ?>
                                                <span class="fw-bold"><?= temizle($hareket['cari_adi']) ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($hareket['borc_id']): ?>
                                                <div class="d-flex flex-column">
                                                    <span class="badge bg-primary">#<?= $hareket['borc_id'] ?></span>
                                                    <small class="text-muted">
                                                        <?= ucfirst($hareket['fatura_tipi'] ?? __('unknown')) ?>
                                                    </small>
                                                    <?php if ($hareket['fatura_tarihi']): ?>
                                                        <small class="text-muted">
                                                            <?= date('d.m.Y', strtotime($hareket['fatura_tarihi'])) ?>
                                                        </small>
                                                    <?php endif; ?>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($hareket['aciklama']): ?>
                                                <span title="<?= temizle($hareket['aciklama']) ?>">
                                                    <?= strlen($hareket['aciklama']) > 30 ? substr(temizle($hareket['aciklama']), 0, 30) . '...' : temizle($hareket['aciklama']) ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($hareket['kullanici_adi']): ?>
                                                <span class="fw-bold"><?= temizle($hareket['kullanici_adi']) ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- <?= __("summary_information") ?> -->
        <div class="row mt-4">
            <div class="col-md-6">
                <div class="card border-info">
                    <div class="card-header bg-info text-white">
                        <i class="bi bi-calculator"></i> <?= __('financial_summary') ?>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between mb-2">
                            <span><?= __('total_purchase_amount') ?>:</span>
                            <strong class="text-success"><?= number_format($toplam_giris_tutar, 2) ?> <?= $paraBirimi ?></strong>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span><?= __('total_sales_amount') ?>:</span>
                            <strong class="text-primary"><?= number_format($toplam_cikis_tutar, 2) ?> <?= $paraBirimi ?></strong>
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between mb-2">
                            <span><?= __('current_stock_value') ?>:</span>
                            <strong class="text-info"><?= number_format(($urun['mevcut_stok'] ?? 0) * ($urun['ortalama_maliyet'] ?? 0), 2) ?> <?= $paraBirimi ?></strong>
                        </div>
                        <div class="d-flex justify-content-between">
                            <span><?= __('total_profit_loss') ?>:</span>
                            <strong class="<?= $toplam_kar_zarar >= 0 ? 'text-success' : 'text-danger' ?>">
                                <?= number_format($toplam_kar_zarar, 2) ?> <?= $paraBirimi ?>
                            </strong>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card border-warning">
                    <div class="card-header bg-warning text-dark">
                        <i class="bi bi-graph-up-arrow"></i> <?= __('performance_analysis') ?>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between mb-2">
                            <span><?= __('stock_turnover_rate') ?>:</span>
                            <strong class="text-warning">
                                <?= $urun['mevcut_stok'] > 0 ? number_format($toplam_cikis / $urun['mevcut_stok'], 2) : 0 ?>
                            </strong>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span><?= __('average_entry_price') ?>:</span>
                            <strong class="text-info">
                                <?= $toplam_giris > 0 ? number_format($toplam_giris_tutar / $toplam_giris, 2) : 0 ?> <?= $paraBirimi ?>
                            </strong>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span><?= __('average_exit_price') ?>:</span>
                            <strong class="text-primary">
                                <?= $toplam_cikis > 0 ? number_format($toplam_cikis_tutar / $toplam_cikis, 2) : 0 ?> <?= $paraBirimi ?>
                            </strong>
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between">
                            <span><?= __('profit_margin') ?>:</span>
                            <strong class="<?= ($toplam_giris_tutar > 0 && $toplam_cikis_tutar > 0) ? 'text-success' : 'text-muted' ?>">
                                <?php 
                                if ($toplam_giris_tutar > 0 && $toplam_cikis_tutar > 0) {
                                    $kar_marji = (($toplam_cikis_tutar - $toplam_giris_tutar) / $toplam_giris_tutar) * 100;
                                    echo number_format($kar_marji, 1) . '%';
                                } else {
                                    echo '-';
                                }
                                ?>
                            </strong>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Tarih filtrelerini otomatik güncelle
        document.addEventListener('DOMContentLoaded', function() {
            // Filtreleme formunu otomatik gönder
            const filterForm = document.querySelector('form[method="get"]');
            const filterInputs = filterForm.querySelectorAll('select, input[type="date"]');
            
            filterInputs.forEach(input => {
                input.addEventListener('change', function() {
                    filterForm.submit();
                });
            });
        });
    </script>
    
    <?php include __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>
