<?php
/**
 * Konum: /magaza/kullanici/fiyat-alarmlarim.php
 * İşlev: Kullanıcının fiyat takibi yaptığı ürünleri listeleme
 */
require_once '../includes/db.php';
require_once '../includes/functions.php';

// Oturum kontrolü
if (!isset($_SESSION['user_id'])) { 
    header("Location: ../giris.php"); 
    exit; 
}

$user_id = (int)$_SESSION['user_id'];

// Fiyat alarmı kurulan ürünleri ve detaylarını çek
$stmt = $db->prepare("
    SELECT pa.id as alert_id, pa.alert_price, pa.created_at as alert_date, 
           p.id as product_id, p.name, p.slug, p.price, p.discount_price, p.stock_quantity,
           b.name as brand_name,
           COALESCE(
               (SELECT image_path FROM product_images WHERE product_id = p.id AND is_main = 1 LIMIT 1),
               b.default_cover,
               'assets/img/no-image.jpg'
           ) as image
    FROM price_alerts pa
    JOIN products p ON pa.product_id = p.id
    LEFT JOIN brands b ON p.brand_id = b.id
    WHERE pa.user_id = ? AND pa.status = 0
    ORDER BY pa.created_at DESC
");
$stmt->execute([$user_id]);
$alarmlar = $stmt->fetchAll(PDO::FETCH_ASSOC);

$page_title = "Fiyat Alarmlarım";
require_once '../header.php';
?>

<main class="container py-5 text-dark">
    <div class="row">
        <div class="col-lg-3 mb-4">
            <?php require_once 'sidebar.php'; ?>
        </div>

        <div class="col-lg-9">
            <div class="card shadow-sm border-0 rounded-4 p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h4 class="fw-bold mb-0">
                        <i class="bi bi-bell-fill text-warning me-2"></i>Fiyat Alarmlarım
                    </h4>
                    <span class="badge bg-light text-dark border"><?= count($alarmlar) ?> Takip</span>
                </div>
                
                <?php if(empty($alarmlar)): ?>
                    <div class="text-center py-5">
                        <div class="bg-light d-inline-flex align-items-center justify-content-center rounded-circle mb-4" style="width: 100px; height: 100px;">
                            <i class="bi bi-bell-slash text-muted" style="font-size: 3rem;"></i>
                        </div>
                        <h5 class="text-muted fw-bold">Henüz fiyat alarmı kurmadınız.</h5>
                        <p class="text-muted small">İlgilendiğiniz ürünlerin fiyatı düştüğünde haber almak için ürün sayfasındaki zil ikonuna tıklayabilirsiniz.</p>
                        <a href="../index.php" class="btn btn-primary mt-2 rounded-pill px-4 fw-bold shadow-sm">Ürünleri İncele</a>
                    </div>
                <?php else: ?>
                    <div class="alert alert-info border-0 shadow-sm mb-4 small">
                        <i class="bi bi-info-circle-fill me-2"></i> Ürünlerin fiyatı, alarm kurduğunuz fiyatın altına düştüğünde size bildirim göndereceğiz.
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light small">
                                <tr>
                                    <th colspan="2" class="ps-3">Ürün Bilgisi</th>
                                    <th class="text-center">Alarm Fiyatı</th>
                                    <th class="text-center">Güncel Fiyat</th>
                                    <th class="text-end pe-3">İşlem</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($alarmlar as $a): 
                                    $guncel_fiyat = $a['discount_price'] > 0 ? $a['discount_price'] : $a['price'];
                                    $indirim_var_mi = $guncel_fiyat < $a['alert_price'];
                                ?>
                                    <tr id="alert-row-<?= $a['product_id'] ?>">
                                        <td style="width: 80px;">
                                            <img src="../<?= htmlspecialchars($a['image']) ?>" class="img-fluid rounded border bg-light" style="max-height: 70px; width: 60px; object-fit: contain;">
                                        </td>
                                        <td>
                                            <small class="text-muted d-block fw-bold text-uppercase" style="font-size: 0.65rem;"><?= htmlspecialchars($a['brand_name']) ?></small>
                                            <a href="../urun-detay.php?slug=<?= $a['slug'] ?>" class="text-dark text-decoration-none fw-bold small d-block mb-1">
                                                <?= htmlspecialchars($a['name']) ?>
                                            </a>
                                            <span class="text-muted small" style="font-size: 0.75rem;">
                                                <i class="bi bi-clock me-1"></i> <?= date('d.m.Y', strtotime($a['alert_date'])) ?>
                                            </span>
                                        </td>
                                        <td class="text-center">
                                            <span class="fw-bold text-muted"><?= number_format($a['alert_price'], 2, ',', '.') ?> ₺</span>
                                        </td>
                                        <td class="text-center">
                                            <span class="fw-black fs-5 <?= $indirim_var_mi ? 'text-success animate__animated animate__pulse animate__infinite' : 'text-primary' ?>">
                                                <?= number_format($guncel_fiyat, 2, ',', '.') ?> ₺
                                            </span>
                                            <?php if($indirim_var_mi): ?>
                                                <div class="small text-success fw-bold" style="font-size: 0.7rem;">
                                                    <i class="bi bi-caret-down-fill"></i> Fiyat Düştü!
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end pe-3">
                                            <div class="btn-group shadow-sm border rounded-pill overflow-hidden">
                                                <a href="https://www.onlineall.net/magaza/urun-detay.php?slug=<?= $a['slug'] ?>" class="btn btn-sm btn-white text-primary fw-bold" title="Görüntüle">
                                                    <i class="bi bi-eye"></i>
                                                </a>
                                                <button type="button" class="btn btn-sm btn-white text-danger remove-alert" data-pid="<?= $a['product_id'] ?>" title="Alarmı Sil">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>

<script>
document.querySelectorAll('.remove-alert').forEach(btn => {
    btn.addEventListener('click', function() {
        let pid = this.getAttribute('data-pid');
        
        Swal.fire({
            title: 'Emin misiniz?',
            text: "Fiyat alarmı kalıcı olarak silinecektir.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Evet, Sil',
            cancelButtonText: 'İptal'
        }).then((result) => {
            if (result.isConfirmed) {
                let fd = new FormData();
                fd.append('action', 'toggle_alert');
                fd.append('product_id', pid);

                fetch('../ajax-user-actions.php', { method: 'POST', body: fd })
                .then(res => res.json())
                .then(data => {
                    if(data.status === 'success') {
                        location.reload();
                    }
                });
            }
        });
    });
});
</script>

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