<?php
/**
 * Admin Finans - Detaylı Satış ve Gelir Raporları
 * Konum: /magaza/admin/finans/satislar.php
 */

require_once '../../includes/db.php';
require_once '../../includes/functions.php';
adminCheck();

// --- FİLTRELEME PARAMETRELERİ ---
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01'); // Varsayılan: Bu ayın başı
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d'); // Varsayılan: Bugün
$payment_filter = isset($_GET['payment_method']) ? $_GET['payment_method'] : 'all';
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'successful'; // successful: İptaller hariç

// --- SQL ŞARTLARINI OLUŞTURMA ---
$where_clauses = ["DATE(o.created_at) >= :start_date", "DATE(o.created_at) <= :end_date"];
$params = [
    ':start_date' => $start_date,
    ':end_date' => $end_date
];

if ($payment_filter != 'all') {
    $where_clauses[] = "p.payment_method = :payment_method";
    $params[':payment_method'] = $payment_filter;
}

if ($status_filter == 'successful') {
    $where_clauses[] = "o.status != 'cancelled'";
} elseif ($status_filter != 'all') {
    $where_clauses[] = "o.status = :status";
    $params[':status'] = $status_filter;
}

$where_sql = implode(' AND ', $where_clauses);

// --- VERİLERİ ÇEKME ---
$sql = "
    SELECT o.id as order_id, o.order_number, o.total_amount, o.shipping_amount, o.created_at, o.status,
           u.name, u.surname,
           p.payment_method
    FROM orders o
    JOIN users u ON o.user_id = u.id
    LEFT JOIN payments p ON o.id = p.order_id
    WHERE $where_sql
    ORDER BY o.created_at DESC
";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$satislar = $stmt->fetchAll();

// --- ÖZET İSTATİSTİKLERİ HESAPLAMA ---
$toplam_ciro = 0;
$toplam_kargo_geliri = 0;
$toplam_siparis = count($satislar);
$havale_toplam = 0;
$kk_toplam = 0;

foreach ($satislar as $s) {
    $toplam_ciro += $s['total_amount'];
    $toplam_kargo_geliri += $s['shipping_amount'];
    
    if ($s['payment_method'] == 'bank_transfer') {
        $havale_toplam += $s['total_amount'];
    } elseif ($s['payment_method'] == 'credit_card') {
        $kk_toplam += $s['total_amount'];
    }
}

require_once '../header.php';
?>

<div class="row mb-4 align-items-center text-dark d-print-none">
    <div class="col-md-6">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-1">
                <li class="breadcrumb-item"><a href="index.php" class="text-decoration-none">Finans Dashboard</a></li>
                <li class="breadcrumb-item active fw-bold" aria-current="page">Satış Raporları</li>
            </ol>
        </nav>
        <h2 class="fw-bold mb-0"><i class="bi bi-bar-chart-fill text-dark me-2"></i>Satış ve Gelir Dökümü</h2>
    </div>
    <div class="col-md-6 text-md-end mt-3 mt-md-0">
        <button onclick="window.print()" class="btn btn-outline-danger fw-bold shadow-sm">
            <i class="bi bi-printer me-1"></i> Raporu Yazdır / PDF Al
        </button>
    </div>
</div>

<div class="card shadow-sm border-0 rounded-4 mb-4 d-print-none text-dark bg-light">
    <div class="card-body p-4">
        <form action="" method="GET" class="row g-3 align-items-end">
            <div class="col-md-3">
                <label class="form-label small fw-bold text-muted">Başlangıç Tarihi</label>
                <input type="date" name="start_date" class="form-control border-2 fw-bold" value="<?= htmlspecialchars($start_date) ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label small fw-bold text-muted">Bitiş Tarihi</label>
                <input type="date" name="end_date" class="form-control border-2 fw-bold" value="<?= htmlspecialchars($end_date) ?>" required>
            </div>
            <div class="col-md-2">
                <label class="form-label small fw-bold text-muted">Ödeme Yöntemi</label>
                <select name="payment_method" class="form-select border-2 fw-bold">
                    <option value="all" <?= $payment_filter == 'all' ? 'selected' : '' ?>>Tümü</option>
                    <option value="credit_card" <?= $payment_filter == 'credit_card' ? 'selected' : '' ?>>Kredi Kartı</option>
                    <option value="bank_transfer" <?= $payment_filter == 'bank_transfer' ? 'selected' : '' ?>>Havale / EFT</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small fw-bold text-muted">Sipariş Durumu</label>
                <select name="status" class="form-select border-2 fw-bold">
                    <option value="successful" <?= $status_filter == 'successful' ? 'selected' : '' ?>>İptaller Hariç (Net Ciro)</option>
                    <option value="all" <?= $status_filter == 'all' ? 'selected' : '' ?>>Tüm Durumlar</option>
                    <option value="delivered" <?= $status_filter == 'delivered' ? 'selected' : '' ?>>Sadece Teslim Edilenler</option>
                </select>
            </div>
            <div class="col-md-2 d-grid">
                <button type="submit" class="btn btn-dark fw-bold shadow-sm"><i class="bi bi-funnel-fill me-1"></i> Filtrele</button>
            </div>
        </form>
    </div>
</div>

<div class="row g-4 mb-4 text-dark">
    <div class="col-sm-6 col-lg-3">
        <div class="card shadow-sm border-0 rounded-4 h-100 border-start border-4 border-success">
            <div class="card-body p-3">
                <small class="text-muted fw-bold d-block mb-1">FİLTRELENEN TOPLAM CİRO</small>
                <h3 class="fw-bold text-success mb-0"><?= number_format($toplam_ciro, 2, ',', '.') ?> ₺</h3>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-lg-3">
        <div class="card shadow-sm border-0 rounded-4 h-100 border-start border-4 border-primary">
            <div class="card-body p-3">
                <small class="text-muted fw-bold d-block mb-1">SİPARİŞ ADEDİ</small>
                <h3 class="fw-bold text-primary mb-0"><?= $toplam_siparis ?> <small class="fs-6 fw-normal text-muted">Adet</small></h3>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-lg-3">
        <div class="card shadow-sm border-0 rounded-4 h-100 border-start border-4 border-info">
            <div class="card-body p-3">
                <small class="text-muted fw-bold d-block mb-1">KREDİ KARTI TAHSİLAT</small>
                <h3 class="fw-bold text-info mb-0"><?= number_format($kk_toplam, 2, ',', '.') ?> ₺</h3>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-lg-3">
        <div class="card shadow-sm border-0 rounded-4 h-100 border-start border-4 border-warning">
            <div class="card-body p-3">
                <small class="text-muted fw-bold d-block mb-1 text-dark">HAVALE / EFT TAHSİLAT</small>
                <h3 class="fw-bold text-dark mb-0"><?= number_format($havale_toplam, 2, ',', '.') ?> ₺</h3>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm border-0 rounded-4 overflow-hidden text-dark mb-5">
    <div class="card-header bg-white py-3 border-bottom d-flex justify-content-between align-items-center">
        <h6 class="mb-0 fw-bold"><i class="bi bi-table text-secondary me-2"></i>Satış Detay Tablosu (<?= date('d.m.Y', strtotime($start_date)) ?> - <?= date('d.m.Y', strtotime($end_date)) ?>)</h6>
        <span class="badge bg-light text-dark border">Gösterilen Kayıt: <?= $toplam_siparis ?></span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0 table-striped">
                <thead class="table-dark">
                    <tr>
                        <th class="ps-4 py-3">Tarih</th>
                        <th>Sipariş No</th>
                        <th>Müşteri</th>
                        <th>Durum</th>
                        <th>Ödeme Yöntemi</th>
                        <th class="text-end">Kargo Tutarı</th>
                        <th class="text-end pe-4">Toplam Tutar</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($satislar) > 0): ?>
                        <?php foreach ($satislar as $s): ?>
                        <tr>
                            <td class="ps-4 text-muted small fw-bold"><?= date('d.m.Y H:i', strtotime($s['created_at'])) ?></td>
                            <td class="fw-bold">
                                <a href="../siparisler/detay.php?id=<?= $s['order_id'] ?>" class="text-decoration-none">
                                    #<?= htmlspecialchars($s['order_number']) ?>
                                </a>
                            </td>
                            <td class="fw-bold text-dark"><?= htmlspecialchars($s['name'] . ' ' . $s['surname']) ?></td>
                            <td>
                                <?php 
                                    // İNGİLİZCE DURUMLARI TÜRKÇEYE ÇEVİRİYORUZ
                                    $durum_cevirileri = [
                                        'pending' => '<span class="badge bg-warning text-dark"><i class="bi bi-hourglass-split me-1"></i>Bekliyor</span>',
                                        'processing' => '<span class="badge bg-info text-dark"><i class="bi bi-box-seam me-1"></i>Hazırlanıyor</span>',
                                        'shipped' => '<span class="badge bg-primary text-white"><i class="bi bi-truck me-1"></i>Kargoda</span>',
                                        'delivered' => '<span class="badge bg-success text-white"><i class="bi bi-check2-all me-1"></i>Teslim Edildi</span>',
                                        'cancelled' => '<span class="badge bg-danger text-white"><i class="bi bi-x-circle me-1"></i>İptal Edildi</span>',
                                        'refunded' => '<span class="badge bg-secondary text-white"><i class="bi bi-arrow-counterclockwise me-1"></i>İade Edildi</span>'
                                    ];
                                    echo $durum_cevirileri[$s['status']] ?? '<span class="badge bg-secondary">'.htmlspecialchars($s['status']).'</span>';
                                ?>
                            </td>
                            <td>
                                <?php if($s['payment_method'] == 'credit_card'): ?>
                                    <span class="badge bg-light text-primary border"><i class="bi bi-credit-card me-1"></i>Kredi Kartı</span>
                                <?php elseif($s['payment_method'] == 'bank_transfer'): ?>
                                    <span class="badge bg-light text-dark border"><i class="bi bi-bank me-1"></i>Havale/EFT</span>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-end small text-muted"><?= $s['shipping_amount'] > 0 ? '+ ' . number_format($s['shipping_amount'], 2, ',', '.') . ' ₺' : 'Ücretsiz' ?></td>
                            <td class="text-end pe-4 fw-bold text-success fs-6"><?= number_format($s['total_amount'], 2, ',', '.') ?> ₺</td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="text-center py-5 text-muted">
                                <i class="bi bi-calendar-x fs-1 d-block mb-3"></i>
                                Seçilen tarih aralığında satış verisi bulunamadı.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
                <tfoot class="table-light border-top">
                    <tr>
                        <td colspan="6" class="text-end fw-bold py-3 text-uppercase">Genel Toplam:</td>
                        <td class="text-end pe-4 fw-bold text-success fs-5 py-3"><?= number_format($toplam_ciro, 2, ',', '.') ?> ₺</td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

<style>
    @media print {
        body { background: #fff; }
        .sidebar, .navbar, .d-print-none { display: none !important; }
        .container, .container-fluid { width: 100% !important; max-width: 100% !important; padding: 0 !important; }
        .card { border: none !important; box-shadow: none !important; }
        .table-dark { background-color: #f8f9fa !important; color: #000 !important; }
        .table-dark th { color: #000 !important; border-bottom: 2px solid #000; }
    }
</style>

<?php require_once '../footer.php'; ?>