<?php
/**
 * Admin Finans - Dekont ve Havale Onay Merkezi
 * Konum: /magaza/admin/finans/dekontlar.php
 */

require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../../includes/subscription_helper.php'; // Abonelik motorunu dahil ettik
adminCheck();

$mesaj = '';

// --- DEKONT ONAYLAMA İŞLEMİ ---
if (isset($_POST['approve_payment']) && isset($_POST['order_id'])) {
    $order_id = (int)$_POST['order_id'];
    
    try {
        $db->beginTransaction();

        // 1. Ödemeyi onaylandı olarak işaretle
        $db->prepare("UPDATE payments SET status = 'approved' WHERE order_id = ?")->execute([$order_id]);

        // 2. Siparişi Hazırlanıyor (processing) durumuna çek
        $db->prepare("UPDATE orders SET status = 'processing' WHERE id = ?")->execute([$order_id]);

        // Bildirim atmak için sipariş sahibi bilgisini ve sipariş numarasını çekelim
        $u_stmt = $db->prepare("SELECT user_id, order_number FROM orders WHERE id = ?");
        $u_stmt->execute([$order_id]);
        $order_info = $u_stmt->fetch();
        $current_user_id = $order_info['user_id'] ?? 0;
        $current_order_no = $order_info['order_number'] ?? '';

        // 3. ABONELİK TETİKLEYİCİ: Eğer siparişte abonelik varsa takvimini kur
        $st_items = $db->prepare("SELECT oi.product_id, p.type, p.duration_days FROM order_items oi JOIN products p ON oi.product_id = p.id WHERE oi.order_id = ?");
        $st_items->execute([$order_id]);
        $order_items_list = $st_items->fetchAll();

        foreach ($order_items_list as $item) {
            if ($item['type'] == 'subscription') {
                $check_sub = $db->prepare("SELECT id FROM subscriptions WHERE user_id = ? AND product_id = ? AND status = 'active'");
                $check_sub->execute([$current_user_id, $item['product_id']]);

                if ($check_sub->rowCount() == 0) {
                    $start_date = date('Y-m-d');
                    $days = $item['duration_days'] ?: 30;
                    $end_date = date('Y-m-d', strtotime("+$days days"));

                    $ins_sub = $db->prepare("INSERT INTO subscriptions (user_id, package_id, product_id, status, start_date, end_date) VALUES (?, 0, ?, 'active', ?, ?)");
                    $ins_sub->execute([$current_user_id, $item['product_id'], $start_date, $end_date]);
                    $new_sub_id = $db->lastInsertId();

                    createSubscriptionSchedule($db, $new_sub_id); // Lojistik takvim oluşturulur
                }
            }
        }

        $db->commit();
        
        // BİLDİRİM TETİKLEYİCİ
        if($current_user_id > 0) {
            siteBildirimGonder($current_user_id, "Ödeme Onaylandı", "#{$current_order_no} numaralı siparişinize ait havale/EFT ödemesi onaylandı. Siparişiniz hazırlanıyor.", "siparis-detay.php?id={$order_id}", "bi-wallet2 text-success");
        }

        $mesaj = "<div class='alert alert-success shadow-sm alert-dismissible fade show'><i class='bi bi-check-circle-fill me-2'></i> Ödeme başarıyla onaylandı ve sipariş lojistik merkezine iletildi.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
    } catch (Exception $e) {
        $db->rollBack();
        $mesaj = "<div class='alert alert-danger shadow-sm'>Onaylama Hatası: " . $e->getMessage() . "</div>";
    }
}

// --- VERİLERİ ÇEK ---
// Bekleyen Dekontlar
$bekleyen_sorgu = $db->query("
    SELECT o.id as order_id, o.order_number, o.total_amount, o.created_at,
           u.name, u.surname, u.phone,
           p.receipt_file_path, p.status as payment_status
    FROM orders o
    JOIN payments p ON o.id = p.order_id
    JOIN users u ON o.user_id = u.id
    WHERE p.payment_method = 'bank_transfer' AND p.status = 'pending'
    ORDER BY o.created_at ASC
")->fetchAll();

// Son Onaylanan 20 Dekont (Geçmişi görebilmek için)
$onaylanan_sorgu = $db->query("
    SELECT o.id as order_id, o.order_number, o.total_amount,
           u.name, u.surname,
           p.receipt_file_path, p.created_at as approved_at
    FROM orders o
    JOIN payments p ON o.id = p.order_id
    JOIN users u ON o.user_id = u.id
    WHERE p.payment_method = 'bank_transfer' AND p.status = 'approved'
    ORDER BY p.id DESC LIMIT 20
")->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">Dekont Merkezi</li>
            </ol>
        </nav>
        <h2 class="fw-bold mb-0"><i class="bi bi-bank text-warning me-2"></i>Dekont ve Havale Onayı</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="dekontTabs" 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-hourglass-split me-1"></i> Onay Bekleyenler (<?= count($bekleyen_sorgu) ?>)
                </button>
            </li>
            <li class="nav-item ms-2" role="presentation">
                <button class="nav-link fw-bold shadow-sm" id="onaylanan-tab" data-bs-toggle="tab" data-bs-target="#onaylanan" type="button" role="tab">
                    <i class="bi bi-check2-all me-1"></i> Son Onaylananlar
                </button>
            </li>
        </ul>
    </div>
    
    <div class="card-body p-0">
        <div class="tab-content" id="dekontTabsContent">
            
            <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</th>
                                <th>Müşteri</th>
                                <th>Sipariş Tarihi</th>
                                <th>Tutar</th>
                                <th>Dekont</th>
                                <th class="text-end pe-4">İşlem</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (count($bekleyen_sorgu) > 0): ?>
                                <?php foreach ($bekleyen_sorgu as $b): ?>
                                <tr>
                                    <td class="ps-4 fw-bold">
                                        <a href="../siparisler/detay.php?id=<?= $b['order_id'] ?>" class="text-primary text-decoration-none">
                                            #<?= htmlspecialchars($b['order_number']) ?>
                                        </a>
                                    </td>
                                    <td>
                                        <div class="fw-bold text-dark"><?= htmlspecialchars($b['name'] . ' ' . $b['surname']) ?></div>
                                        <div class="small text-muted"><?= htmlspecialchars($b['phone']) ?></div>
                                    </td>
                                    <td class="text-muted small"><?= date('d.m.Y H:i', strtotime($b['created_at'])) ?></td>
                                    <td class="fw-bold text-danger fs-6"><?= number_format($b['total_amount'], 2, ',', '.') ?> ₺</td>
                                    <td>
                                        <?php if ($b['receipt_file_path']): ?>
                                            <a href="../../<?= htmlspecialchars($b['receipt_file_path']) ?>" target="_blank" class="btn btn-sm btn-outline-info fw-bold px-3 rounded-pill shadow-sm">
                                                <i class="bi bi-eye-fill me-1"></i> İncele
                                            </a>
                                        <?php else: ?>
                                            <span class="badge bg-light text-secondary border py-2"><i class="bi bi-clock"></i> Henüz Yüklenmedi</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end pe-4">
                                        <form action="" method="POST" class="d-inline-block">
                                            <input type="hidden" name="order_id" value="<?= $b['order_id'] ?>">
                                            <button type="submit" name="approve_payment" class="btn btn-success fw-bold shadow-sm" onclick="return confirm('#<?= $b['order_number'] ?> nolu siparişin ödemesini onaylıyor musunuz? Sipariş lojistik aşamasına geçecektir.')" <?= empty($b['receipt_file_path']) ? 'title="Müşteri dekont yüklememiş, bankanızı kontrol edin!"' : '' ?>>
                                                <i class="bi bi-check-circle me-1"></i> Onayla
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" 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! Onay bekleyen dekont yok.</h5>
                                        <p class="small">Tüm işlemler kontrol edilmiş durumda.</p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="tab-pane fade" id="onaylanan" 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>Dekont Dosyası</th>
                                <th class="text-end pe-4">Durum</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (count($onaylanan_sorgu) > 0): ?>
                                <?php foreach ($onaylanan_sorgu as $o): ?>
                                <tr>
                                    <td class="ps-4 fw-bold">
                                        <a href="../siparisler/detay.php?id=<?= $o['order_id'] ?>" class="text-secondary text-decoration-none">
                                            #<?= htmlspecialchars($o['order_number']) ?>
                                        </a>
                                    </td>
                                    <td class="fw-bold text-dark"><?= htmlspecialchars($o['name'] . ' ' . $o['surname']) ?></td>
                                    <td class="fw-bold text-success"><?= number_format($o['total_amount'], 2, ',', '.') ?> ₺</td>
                                    <td>
                                        <?php if ($o['receipt_file_path']): ?>
                                            <a href="../../<?= htmlspecialchars($o['receipt_file_path']) ?>" target="_blank" class="text-primary text-decoration-none small fw-bold"><i class="bi bi-link-45deg"></i> Dosyayı Aç</a>
                                        <?php else: ?>
                                            <span class="text-muted small italic">Sisteme yüklenmemiş</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end pe-4">
                                        <span class="badge bg-success rounded-pill px-3 py-2"><i class="bi bi-check-all"></i> Onaylanmış</span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="5" class="text-center py-4 text-muted">Geçmiş işlem bulunamadı.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

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

<style>
    /* Aktif sekme stili */
    #dekontTabs .nav-link.active { 
        background-color: #ffc107 !important; 
        color: #000 !important; 
        border-color: #ffc107 !important; 
    }
    
    /* Pasif sekme stili (Görünmeme sorununu çözen kısım) */
    #dekontTabs .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 */
    #dekontTabs .nav-link:hover { 
        background-color: #e9ecef !important; 
    }
</style>

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