<?php
/**
 * Admin Finans - E-Fatura Takip ve Yükleme Merkezi
 * Konum: /magaza/admin/finans/faturalar.php
 */

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

$mesaj = '';

// --- FATURA YÜKLEME İŞLEMİ ---
if (isset($_POST['upload_invoice']) && isset($_FILES['invoice_file']) && isset($_POST['order_id'])) {
    $order_id = (int)$_POST['order_id'];
    $dosya = $_FILES['invoice_file'];
    $uzanti = strtolower(pathinfo($dosya['name'], PATHINFO_EXTENSION));
    
    if ($uzanti !== 'pdf') {
        $mesaj = "<div class='alert alert-danger shadow-sm'>Hata: Sadece PDF formatında fatura yükleyebilirsiniz.</div>";
    } elseif ($dosya['size'] > 5 * 1024 * 1024) {
        $mesaj = "<div class='alert alert-danger shadow-sm'>Hata: Fatura dosya boyutu 5MB'dan büyük olamaz.</div>";
    } else {
        $yukleme_dizini = "../../uploads/invoices/";
        if (!is_dir($yukleme_dizini)) mkdir($yukleme_dizini, 0777, true);
        
        $yeni_ad = "fatura_" . $order_id . "_" . time() . ".pdf";
        $hedef_yol = $yukleme_dizini . $yeni_ad;

        if (move_uploaded_file($dosya['tmp_name'], $hedef_yol)) {
            $db_yolu = "uploads/invoices/" . $yeni_ad;
            $db->prepare("UPDATE orders SET invoice_path = ? WHERE id = ?")->execute([$db_yolu, $order_id]);
            $mesaj = "<div class='alert alert-success shadow-sm alert-dismissible fade show'><i class='bi bi-check-circle-fill me-2'></i> Fatura başarıyla sisteme yüklendi ve müşteriye açıldı.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
            
            // BİLDİRİM TETİKLEYİCİ: E-Fatura Yüklendi
            $u_stmt = $db->prepare("SELECT user_id, order_number FROM orders WHERE id = ?");
            $u_stmt->execute([$order_id]);
            $order_info = $u_stmt->fetch();
            
            if ($order_info && $order_info['user_id'] > 0) {
                siteBildirimGonder($order_info['user_id'], "E-Faturanız Hazır", "#{$order_info['order_number']} numaralı siparişinize ait e-fatura sisteme yüklendi.", "siparis-detay.php?id={$order_id}", "bi-receipt");
            }

        } else {
            $mesaj = "<div class='alert alert-danger shadow-sm'>Hata: Dosya yüklenirken bir sorun oluştu.</div>";
        }
    }
}

// --- FATURA SİLME İŞLEMİ ---
if (isset($_POST['delete_invoice']) && isset($_POST['order_id'])) {
    $order_id = (int)$_POST['order_id'];
    
    $s_fatura = $db->prepare("SELECT invoice_path FROM orders WHERE id = ?");
    $s_fatura->execute([$order_id]);
    $eski_fatura = $s_fatura->fetchColumn();

    if ($eski_fatura && file_exists("../../" . $eski_fatura)) {
        unlink("../../" . $eski_fatura);
    }
    
    $db->prepare("UPDATE orders SET invoice_path = NULL WHERE id = ?")->execute([$order_id]);
    $mesaj = "<div class='alert alert-secondary shadow-sm alert-dismissible fade show'><i class='bi bi-trash me-2'></i> Fatura dosyası sistemden silindi. Yenisini yükleyebilirsiniz.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
}

// --- VERİLERİ ÇEK ---

// 1. Fatura Bekleyenler (İptal/Beklemede olmayan ve faturası olmayanlar)
$bekleyen_sorgu = $db->query("
    SELECT o.id as order_id, o.order_number, o.total_amount, o.created_at, o.status,
           u.name, u.surname,
           b_addr.title as b_title, b_addr.full_address as b_full_address, b_addr.district as b_district, b_addr.city as b_city,
           s_addr.full_address as s_full_address, s_addr.district as s_district, s_addr.city as s_city
    FROM orders o
    JOIN users u ON o.user_id = u.id
    LEFT JOIN user_addresses b_addr ON o.billing_address_id = b_addr.id
    LEFT JOIN user_addresses s_addr ON o.shipping_address_id = s_addr.id
    WHERE (o.invoice_path IS NULL OR o.invoice_path = '') 
      AND o.status IN ('processing', 'shipped', 'delivered')
    ORDER BY o.created_at DESC
")->fetchAll();

// 2. Faturası Kesilenler (Arşiv)
$kesilen_sorgu = $db->query("
    SELECT o.id as order_id, o.order_number, o.total_amount, o.created_at, o.invoice_path,
           u.name, u.surname
    FROM orders o
    JOIN users u ON o.user_id = u.id
    WHERE o.invoice_path IS NOT NULL AND o.invoice_path != ''
    ORDER BY o.id DESC LIMIT 50
")->fetchAll();

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

<div class="row mb-4 align-items-center text-dark">
    <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">Fatura Merkezi</li>
            </ol>
        </nav>
        <h2 class="fw-bold mb-0"><i class="bi bi-receipt-cutoff text-info me-2"></i>E-Fatura Operasyonu</h2>
    </div>
</div>

<?= $mesaj ?>

<div class="card shadow-sm border-0 rounded-4 overflow-hidden text-dark mb-4">
    <div class="card-header bg-white py-3 border-bottom">
        <ul class="nav nav-pills card-header-pills" id="faturaTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active fw-bold shadow-sm" id="bekleyen-tab" data-bs-toggle="tab" data-bs-target="#bekleyen" type="button" role="tab">
                    <i class="bi bi-clock-history me-1"></i> Fatura Bekleyenler (<?= count($bekleyen_sorgu) ?>)
                </button>
            </li>
            <li class="nav-item ms-2" role="presentation">
                <button class="nav-link fw-bold shadow-sm" id="kesilen-tab" data-bs-toggle="tab" data-bs-target="#kesilen" type="button" role="tab">
                    <i class="bi bi-check-all me-1"></i> Faturası Kesilenler (Arşiv)
                </button>
            </li>
        </ul>
    </div>
    
    <div class="card-body p-0">
        <div class="tab-content" id="faturaTabsContent">
            
            <div class="tab-pane fade show active" id="bekleyen" role="tabpanel">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-4 py-3">Sipariş No / Tarih</th>
                                <th>Müşteri</th>
                                <th>Tutar</th>
                                <th>Fatura Bilgileri</th>
                                <th class="text-end pe-4">PDF Yükle</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (count($bekleyen_sorgu) > 0): ?>
                                <?php foreach ($bekleyen_sorgu as $b): ?>
                                <tr>
                                    <td class="ps-4">
                                        <a href="../siparisler/detay.php?id=<?= $b['order_id'] ?>" class="fw-bold text-primary text-decoration-none d-block">
                                            #<?= htmlspecialchars($b['order_number']) ?>
                                        </a>
                                        <small class="text-muted"><?= date('d.m.Y H:i', strtotime($b['created_at'])) ?></small>
                                    </td>
                                    <td>
                                        <div class="fw-bold text-dark mb-1"><?= htmlspecialchars($b['name'] . ' ' . $b['surname']) ?></div>
                                        <?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[$b['status']] ?? '<span class="badge bg-secondary">'.htmlspecialchars($b['status']).'</span>';
                                        ?>
                                    </td>
                                    <td class="fw-bold text-danger fs-6"><?= number_format($b['total_amount'], 2, ',', '.') ?> ₺</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-secondary fw-bold rounded-pill px-3" type="button" data-bs-toggle="collapse" data-bs-target="#faturaBilgi_<?= $b['order_id'] ?>" aria-expanded="false">
                                            <i class="bi bi-card-text me-1"></i> Bilgileri Gör
                                        </button>
                                        
                                        <div class="collapse mt-2" id="faturaBilgi_<?= $b['order_id'] ?>">
                                            <div class="card card-body bg-light p-2 small border-0 shadow-sm" style="min-width: 250px;">
                                                <?php if($b['b_full_address']): ?>
                                                    <strong class="text-dark d-block border-bottom pb-1 mb-1"><?= htmlspecialchars($b['b_title']) ?></strong>
                                                    <span class="d-block mb-1 text-muted"><?= nl2br(htmlspecialchars($b['b_full_address'])) ?></span>
                                                    <span class="badge bg-white text-dark border"><?= htmlspecialchars($b['b_district'] . ' / ' . $b['b_city']) ?></span>
                                                <?php else: ?>
                                                    <strong class="text-dark d-block border-bottom pb-1 mb-1">Teslimat Adresine Kesilecek</strong>
                                                    <span class="d-block mb-1 text-muted"><?= nl2br(htmlspecialchars($b['s_full_address'])) ?></span>
                                                    <span class="badge bg-white text-dark border"><?= htmlspecialchars($b['s_district'] . ' / ' . $b['s_city']) ?></span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="text-end pe-4">
                                        <form action="" method="POST" enctype="multipart/form-data" class="d-flex justify-content-end gap-2 align-items-center">
                                            <input type="hidden" name="order_id" value="<?= $b['order_id'] ?>">
                                            <input type="file" name="invoice_file" class="form-control form-control-sm border-2" accept=".pdf" required style="max-width: 180px;" title="PDF Fatura Seçin">
                                            <button type="submit" name="upload_invoice" class="btn btn-sm btn-info text-dark fw-bold shadow-sm" title="Sisteme Yükle">
                                                <i class="bi bi-cloud-arrow-up-fill"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5" class="text-center py-5 text-muted">
                                        <i class="bi bi-check-circle text-success fs-1 d-block mb-3"></i>
                                        <h5 class="fw-bold">Harika! Fatura bekleyen sipariş yok.</h5>
                                        <p class="small">Onaylanmış tüm siparişlerin e-faturaları sisteme işlenmiş.</p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="tab-pane fade" id="kesilen" role="tabpanel">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-4 py-3">Sipariş No</th>
                                <th>Müşteri</th>
                                <th>Tutar</th>
                                <th>Fatura Dosyası</th>
                                <th class="text-end pe-4">İşlem</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (count($kesilen_sorgu) > 0): ?>
                                <?php foreach ($kesilen_sorgu as $k): ?>
                                <tr>
                                    <td class="ps-4 fw-bold">
                                        <a href="../siparisler/detay.php?id=<?= $k['order_id'] ?>" class="text-secondary text-decoration-none">
                                            #<?= htmlspecialchars($k['order_number']) ?>
                                        </a>
                                    </td>
                                    <td class="fw-bold text-dark"><?= htmlspecialchars($k['name'] . ' ' . $k['surname']) ?></td>
                                    <td class="fw-bold text-success"><?= number_format($k['total_amount'], 2, ',', '.') ?> ₺</td>
                                    <td>
                                        <a href="../../<?= htmlspecialchars($k['invoice_path']) ?>" target="_blank" class="btn btn-sm btn-outline-info fw-bold rounded-pill px-3 shadow-sm">
                                            <i class="bi bi-eye-fill me-1"></i> PDF Göster
                                        </a>
                                    </td>
                                    <td class="text-end pe-4">
                                        <form action="" method="POST" class="d-inline-block">
                                            <input type="hidden" name="order_id" value="<?= $k['order_id'] ?>">
                                            <button type="submit" name="delete_invoice" class="btn btn-sm btn-outline-danger fw-bold" onclick="return confirm('#<?= $k['order_number'] ?> nolu siparişin faturasını silmek istediğinize emin misiniz?')" title="Faturayı Sil">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="5" class="text-center py-4 text-muted">Geçmiş fatura kaydı bulunamadı.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </div>
</div>

<style>
    /* Aktif sekme stili */
    #faturaTabs .nav-link.active { 
        background-color: #0dcaf0 !important; 
        color: #000 !important; 
        border-color: #0dcaf0 !important; 
    }
    
    /* Pasif sekme stili (Görünmeme sorununu çözen kısım) */
    #faturaTabs .nav-link { 
        background-color: #f8f9fa !important; /* Açık gri arka plan */
        color: #000 !important; /* Kesin siyah yazı */
        border: 1px solid #dee2e6 !important; 
    }
    
    /* Pasif sekme üzerine gelindiğinde */
    #faturaTabs .nav-link:hover { 
        background-color: #e9ecef !important; 
    }
</style>

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