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

$sayfa_baslik = __('detailed_stock_reports');

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

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

// Ürünleri getir
$urunler = $db->prepare("SELECT id, urun_adi FROM urunler WHERE aktif = 1 AND sirket_id = ? ORDER BY urun_adi");
$urunler->execute([$aktif_sirket_id]);
$urunler = $urunler->fetchAll();

// Carileri getir
$cariler = $db->prepare("SELECT id, ad_soyad FROM cariler WHERE sirket_id = ? ORDER BY ad_soyad");
$cariler->execute([$aktif_sirket_id]);
$cariler = $cariler->fetchAll();

// Ana rapor verilerini getir
$rapor_verileri = [];

if ($rapor_turu == 'hareket_detay') {
    // Stok hareketleri detay raporu
    $sql = "SELECT 
                    sh.id,
                    sh.tarih,
                    sh.hareket_turu,
                    sh.miktar,
                    sh.birim_fiyat,
                    sh.toplam_tutar,
                    sh.aciklama,
                    u.urun_adi,
                    u.birim,
                    c.ad_soyad as cari_adi,
                    b.tur as islem_turu,
                    b.tarih as fatura_tarihi,
                    CASE 
                        WHEN sh.hareket_turu = 'giris' THEN 'Alış'
                        WHEN sh.hareket_turu = 'cikis' THEN 'Satış'
                        WHEN sh.hareket_turu = 'sayim' THEN 'Sayım'
                        ELSE sh.hareket_turu
                    END as hareket_adi
                FROM stok_hareketleri sh
                LEFT JOIN urunler u ON sh.urun_id = u.id AND u.sirket_id = ?
                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 = ?
                WHERE sh.sirket_id = ? AND sh.tarih BETWEEN ? AND ?";
    $params = [$aktif_sirket_id, $aktif_sirket_id, $aktif_sirket_id, $aktif_sirket_id, $baslangic_tarihi, $bitis_tarihi];
    
    if ($urun_id) {
        $sql .= " AND sh.urun_id = ?";
        $params[] = $urun_id;
    }
    
    if ($cari_id) {
        $sql .= " AND sh.cari_id = ?";
        $params[] = $cari_id;
    }
    
    if ($hareket_turu) {
        $sql .= " AND sh.hareket_turu = ?";
        $params[] = $hareket_turu;
    }
    
    $sql .= " ORDER BY sh.tarih DESC, sh.id DESC";
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $rapor_verileri = $stmt->fetchAll();
    
} elseif ($rapor_turu == 'urun_ozet') {
    // Ürün bazında özet rapor
    $sql = "SELECT 
                    u.id,
                    u.urun_adi,
                    u.birim,
                    SUM(CASE WHEN sh.hareket_turu = 'giris' THEN sh.miktar ELSE 0 END) as toplam_giris,
                    SUM(CASE WHEN sh.hareket_turu = 'cikis' THEN sh.miktar ELSE 0 END) as toplam_cikis,
                    SUM(CASE WHEN sh.hareket_turu = 'giris' THEN sh.toplam_tutar ELSE 0 END) as giris_tutari,
                    SUM(CASE WHEN sh.hareket_turu = 'cikis' THEN sh.toplam_tutar ELSE 0 END) as cikis_tutari,
                    COUNT(sh.id) as hareket_sayisi,
                    ms.miktar as mevcut_stok
                FROM urunler u
                LEFT JOIN stok_hareketleri sh ON u.id = sh.urun_id 
                    AND sh.aktif = 1 
                    AND sh.sirket_id = ?
                    AND sh.tarih BETWEEN ? AND ?
                LEFT JOIN mevcut_stok ms ON u.id = ms.urun_id AND ms.sirket_id = u.sirket_id
                WHERE u.aktif = 1 AND u.sirket_id = ?";
    $params = [$aktif_sirket_id, $baslangic_tarihi, $bitis_tarihi, $aktif_sirket_id];
    
    if ($urun_id) {
        $sql .= " AND u.id = ?";
        $params[] = $urun_id;
    }
    
    $sql .= " GROUP BY u.id, u.urun_adi, u.birim, ms.miktar
              HAVING COUNT(sh.id) > 0 OR ? IS NOT NULL
              ORDER BY u.urun_adi";
    
    $params[] = $urun_id; // HAVING koşulu için
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $rapor_verileri = $stmt->fetchAll();
    
} elseif ($rapor_turu == 'cari_ozet') {
    // Cari bazında özet rapor
    $sql = "SELECT 
                    c.id,
                    c.ad_soyad,
                    SUM(CASE WHEN sh.hareket_turu = 'giris' THEN sh.miktar ELSE 0 END) as toplam_alis_miktar,
                    SUM(CASE WHEN sh.hareket_turu = 'cikis' THEN sh.miktar ELSE 0 END) as toplam_satis_miktar,
                    SUM(CASE WHEN sh.hareket_turu = 'giris' THEN sh.toplam_tutar ELSE 0 END) as toplam_alis_tutar,
                    SUM(CASE WHEN sh.hareket_turu = 'cikis' THEN sh.toplam_tutar ELSE 0 END) as toplam_satis_tutar,
                    COUNT(DISTINCT sh.urun_id) as farkli_urun_sayisi,
                    COUNT(sh.id) as toplam_hareket
                FROM cariler c
                LEFT JOIN stok_hareketleri sh ON c.id = sh.cari_id 
                    AND sh.aktif = 1 
                    AND sh.sirket_id = ?
                    AND sh.tarih BETWEEN ? AND ?
                WHERE c.sirket_id = ?";
    $params = [$aktif_sirket_id, $baslangic_tarihi, $bitis_tarihi, $aktif_sirket_id];
    
    if ($cari_id) {
        $sql .= " AND c.id = ?";
        $params[] = $cari_id;
    }
    
    $sql .= " GROUP BY c.id, c.ad_soyad
              HAVING COUNT(sh.id) > 0 OR ? IS NOT NULL
              ORDER BY toplam_satis_tutar DESC";
    
    $params[] = $cari_id; // HAVING koşulu için
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $rapor_verileri = $stmt->fetchAll();
}

// Özet istatistikler
$ozet_istatistikler = [];
if (!empty($rapor_verileri) && $rapor_turu == 'hareket_detay') {
    $toplam_giris = 0;
    $toplam_cikis = 0;
    $toplam_giris_tutar = 0;
    $toplam_cikis_tutar = 0;
    
    foreach ($rapor_verileri as $hareket) {
        if ($hareket['hareket_turu'] == 'giris') {
            $toplam_giris += $hareket['miktar'];
            $toplam_giris_tutar += $hareket['toplam_tutar'];
        } elseif ($hareket['hareket_turu'] == 'cikis') {
            $toplam_cikis += $hareket['miktar'];
            $toplam_cikis_tutar += $hareket['toplam_tutar'];
        }
    }
    
    $ozet_istatistikler = [
        'toplam_giris' => $toplam_giris,
        'toplam_cikis' => $toplam_cikis,
        'toplam_giris_tutar' => $toplam_giris_tutar,
        'toplam_cikis_tutar' => $toplam_cikis_tutar,
        'net_hareket' => $toplam_giris - $toplam_cikis,
        'net_tutar' => $toplam_cikis_tutar - $toplam_giris_tutar // Kar (satış - alış)
    ];
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Odjoo Yönetim - <?= temizle($sayfa_baslik) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .table-responsive {
            border-radius: 0.375rem;
        }
        .stat-card {
            transition: transform 0.2s;
        }
        .stat-card:hover {
            transform: translateY(-2px);
        }
        @media print {
            .no-print { display: none !important; }
            .table { font-size: 12px; }
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

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

                <!-- Filtreleme Formu -->
                <div class="card mb-4 no-print">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-funnel me-2"></i><?= __('report_filters') ?></h5>
                    </div>
                    <div class="card-body">
                        <form method="get" class="row g-3">
                            <div class="col-md-3">
                                <label for="rapor_turu" class="form-label"><?= __('report_type') ?></label>
                                <select class="form-select" id="rapor_turu" name="rapor_turu">
                                    <option value="hareket_detay" <?= $rapor_turu == 'hareket_detay' ? 'selected' : '' ?>><?= __('movement_details') ?></option>
                                    <option value="urun_ozet" <?= $rapor_turu == 'urun_ozet' ? 'selected' : '' ?>><?= __('product_summary') ?></option>
                                    <option value="cari_ozet" <?= $rapor_turu == 'cari_ozet' ? 'selected' : '' ?>><?= __('customer_supplier_summary') ?></option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="urun_id" class="form-label"><?= __('product') ?></label>
                                <select class="form-select" id="urun_id" name="urun_id">
                                    <option value=""><?= __('all_products') ?></option>
                                    <?php foreach ($urunler as $urun): ?>
                                        <option value="<?= $urun['id'] ?>" <?= $urun_id == $urun['id'] ? 'selected' : '' ?>>
                                            <?= temizle($urun['urun_adi']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="cari_id" class="form-label"><?= __('customer_supplier') ?></label>
                                <select class="form-select" id="cari_id" name="cari_id">
                                    <option value="">Tümü</option>
                                    <?php foreach ($cariler as $cari): ?>
                                        <option value="<?= $cari['id'] ?>" <?= $cari_id == $cari['id'] ? 'selected' : '' ?>>
                                            <?= temizle($cari['ad_soyad']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="hareket_turu" class="form-label"><?= __('transaction_type') ?></label>
                                <select class="form-select" id="hareket_turu" name="hareket_turu">
                                    <option value="">Tümü</option>
                                    <option value="giris" <?= $hareket_turu == 'giris' ? 'selected' : '' ?>><?= __('entry_purchase') ?></option>
                                    <option value="cikis" <?= $hareket_turu == 'cikis' ? 'selected' : '' ?>><?= __('exit_sale') ?></option>
                                    <option value="sayim" <?= $hareket_turu == 'sayim' ? 'selected' : '' ?>><?= __('inventory_count') ?></option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="baslangic_tarihi" class="form-label"><?= __('start_date') ?></label>
                                <input type="date" class="form-control" id="baslangic_tarihi" name="baslangic_tarihi" 
                                       value="<?= htmlspecialchars($baslangic_tarihi) ?>">
                            </div>
                            <div class="col-md-4">
                                <label for="bitis_tarihi" class="form-label"><?= __('end_date') ?></label>
                                <input type="date" class="form-control" id="bitis_tarihi" name="bitis_tarihi" 
                                       value="<?= htmlspecialchars($bitis_tarihi) ?>">
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary me-2">
                                    <i class="bi bi-search"></i> <?= __('get_report') ?>
                                </button>
                                <a href="stok_raporlari.php" class="btn btn-outline-secondary">
                                    <i class="bi bi-arrow-clockwise"></i> <?= __('reset') ?>
                                </a>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Özet İstatistikler -->
                <?php if (!empty($ozet_istatistikler)): ?>
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card stat-card bg-success text-white">
                            <div class="card-body text-center">
                                <h4><?= number_format($ozet_istatistikler['toplam_giris'], 2, ',', '.') ?></h4>
                                <small>Toplam Giriş</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card bg-danger text-white">
                            <div class="card-body text-center">
                                <h4><?= number_format($ozet_istatistikler['toplam_cikis'], 2, ',', '.') ?></h4>
                                <small>Toplam Çıkış</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card bg-info text-white">
                            <div class="card-body text-center">
                                <h4><?= number_format($ozet_istatistikler['net_hareket'], 2, ',', '.') ?></h4>
                                <small>Net Hareket</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card bg-<?= $ozet_istatistikler['net_tutar'] >= 0 ? 'success' : 'warning' ?> text-white">
                            <div class="card-body text-center">
                                <h4><?= number_format($ozet_istatistikler['net_tutar'], 2, ',', '.') . ' ' . getParaBirimiSembolu() ?></h4>
                                <small>Net Kar/Zarar</small>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Rapor Tablosu -->
                <div class="card">
                    <div class="card-header bg-light">
                        <h5 class="mb-0">
                            <i class="bi bi-table me-2"></i>
                            <?php
                            switch ($rapor_turu) {
                                case 'hareket_detay': echo __('stock_movement_details'); break;
                                case 'urun_ozet': echo __('product_summary_report'); break;
                                case 'cari_ozet': echo __('customer_supplier_summary'); break;
                            }
                            ?>
                            <span class="badge bg-secondary"><?= count($rapor_verileri) ?></span>
                        </h5>
                        <small class="text-muted">
                            <?= __('date_range') ?>: <?= date('d.m.Y', strtotime($baslangic_tarihi)) ?> - <?= date('d.m.Y', strtotime($bitis_tarihi)) ?>
                        </small>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($rapor_verileri)): ?>
                            <div class="text-center p-4">
                                <i class="bi bi-inbox display-1 text-muted"></i>
                                <p class="text-muted mt-2"><?= __('no_data_found') ?></p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <?php if ($rapor_turu == 'hareket_detay'): ?>
                                    <!-- Hareket Detayları Tablosu -->
                                    <table class="table table-hover mb-0">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Tarih</th>
                                                <th>Ürün</th>
                                                <th>Hareket</th>
                                                <th>Müşteri/Tedarikçi</th>
                                                <th class="text-end">Miktar</th>
                                                <th class="text-end">Birim Fiyat</th>
                                                <th class="text-end">Toplam Tutar</th>
                                                <th>Açıklama</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($rapor_verileri as $hareket): ?>
                                                <tr>
                                                    <td><?= date('d.m.Y H:i', strtotime($hareket['tarih'])) ?></td>
                                                    <td>
                                                        <strong><?= temizle($hareket['urun_adi']) ?></strong>
                                                        <br><small class="text-muted"><?= temizle($hareket['birim']) ?></small>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-<?= $hareket['hareket_turu'] == 'giris' ? 'success' : ($hareket['hareket_turu'] == 'cikis' ? 'danger' : 'info') ?>">
                                                            <?= temizle($hareket['hareket_adi']) ?>
                                                        </span>
                                                    </td>
                                                    <td><?= temizle($hareket['cari_adi'] ?? '-') ?></td>
                                                    <td class="text-end"><?= number_format($hareket['miktar'], 2, ',', '.') ?></td>
                                                    <td class="text-end">
                                                        <?= $hareket['birim_fiyat'] ? number_format($hareket['birim_fiyat'], 2, ',', '.') . ' ' . getParaBirimiSembolu() : '-' ?>
                                                    </td>
                                                    <td class="text-end">
                                                        <?= $hareket['toplam_tutar'] ? number_format($hareket['toplam_tutar'], 2, ',', '.') . ' ' . getParaBirimiSembolu() : '-' ?>
                                                    </td>
                                                    <td><?= temizle($hareket['aciklama'] ?? '-') ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                    
                                <?php elseif ($rapor_turu == 'urun_ozet'): ?>
                                    <!-- Ürün Özet Tablosu -->
                                    <table class="table table-hover mb-0">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Ürün Adı</th>
                                                <th>Birim</th>
                                                <th class="text-end">Toplam Giriş</th>
                                                <th class="text-end">Toplam Çıkış</th>
                                                <th class="text-end">Giriş Tutarı</th>
                                                <th class="text-end">Çıkış Tutarı</th>
                                                <th class="text-end">Mevcut Stok</th>
                                                <th class="text-center">Hareket Sayısı</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($rapor_verileri as $urun): ?>
                                                <tr>
                                                    <td><strong><?= temizle($urun['urun_adi']) ?></strong></td>
                                                    <td><?= temizle($urun['birim']) ?></td>
                                                    <td class="text-end text-success"><?= number_format($urun['toplam_giris'], 2, ',', '.') ?></td>
                                                    <td class="text-end text-danger"><?= number_format($urun['toplam_cikis'], 2, ',', '.') ?></td>
                                                    <td class="text-end"><?= number_format($urun['giris_tutari'], 2, ',', '.') . ' ' . getParaBirimiSembolu() ?></td>
                                                    <td class="text-end"><?= number_format($urun['cikis_tutari'], 2, ',', '.') . ' ' . getParaBirimiSembolu() ?></td>
                                                    <td class="text-end"><strong><?= number_format($urun['mevcut_stok'] ?? 0, 2, ',', '.') ?></strong></td>
                                                    <td class="text-center"><?= $urun['hareket_sayisi'] ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                    
                                <?php elseif ($rapor_turu == 'cari_ozet'): ?>
                                    <!-- Cari Özet Tablosu -->
                                    <table class="table table-hover mb-0">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Müşteri/Tedarikçi</th>
                                                <th class="text-end">Alış Miktarı</th>
                                                <th class="text-end">Satış Miktarı</th>
                                                <th class="text-end">Alış Tutarı</th>
                                                <th class="text-end">Satış Tutarı</th>
                                                <th class="text-center">Farklı Ürün</th>
                                                <th class="text-center">Toplam Hareket</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($rapor_verileri as $cari): ?>
                                                <tr>
                                                    <td><strong><?= temizle($cari['ad_soyad']) ?></strong></td>
                                                    <td class="text-end text-info"><?= number_format($cari['toplam_alis_miktar'], 2, ',', '.') ?></td>
                                                    <td class="text-end text-primary"><?= number_format($cari['toplam_satis_miktar'], 2, ',', '.') ?></td>
                                                    <td class="text-end"><?= number_format($cari['toplam_alis_tutar'], 2, ',', '.') . ' ' . getParaBirimiSembolu() ?></td>
                                                    <td class="text-end"><?= number_format($cari['toplam_satis_tutar'], 2, ',', '.') . ' ' . getParaBirimiSembolu() ?></td>
                                                    <td class="text-center"><?= $cari['farkli_urun_sayisi'] ?></td>
                                                    <td class="text-center"><?= $cari['toplam_hareket'] ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

