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

// Proje ana dizinini belirle
$kok_dizin = "/magaza/";

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

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

// STOK ALARMI İPTAL İŞLEMİ (Fiyat alarmı AJAX ile siliniyor, Stok alarmını GET ile siliyoruz)
if (isset($_GET['iptal_stok']) && is_numeric($_GET['iptal_stok'])) {
    $alert_id = (int)$_GET['iptal_stok'];
    $del = $db->prepare("DELETE FROM stock_alerts WHERE id = ? AND user_id = ?");
    $del->execute([$alert_id, $user_id]);
    
    header("Location: fiyat-alarmlarim.php?msg=stok_deleted");
    exit;
}

// 1. FİYAT ALARMLARINI ÇEK
$stmt_price = $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_price->execute([$user_id]);
$fiyat_alarmlari = $stmt_price->fetchAll(PDO::FETCH_ASSOC);

// 2. STOK ALARMLARINI ÇEK
$stmt_stock = $db->prepare("
    SELECT sa.id as alert_id, sa.created_at as alert_date, 
           p.id as product_id, p.name, p.slug, p.price, p.stock_quantity, p.status as p_status,
           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 stock_alerts sa
    JOIN products p ON sa.product_id = p.id
    LEFT JOIN brands b ON p.brand_id = b.id
    WHERE sa.user_id = ? AND sa.status = 0
    ORDER BY sa.created_at DESC
");
$stmt_stock->execute([$user_id]);
$stok_alarmlari = $stmt_stock->fetchAll(PDO::FETCH_ASSOC);

$page_title = "Alarmlarım ve Bildirimlerim";
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="d-flex justify-content-between align-items-center mb-4">
                <h2 class="h4 fw-bold mb-0 text-primary">
                    <i class="bi bi-bell-fill me-2"></i>Alarmlarım
                </h2>
            </div>

            <?php if(isset($_GET['msg']) && $_GET['msg'] == 'stok_deleted'): ?>
                <div class="alert alert-success alert-dismissible fade show shadow-sm rounded-4" role="alert">
                    <i class="bi bi-check-circle-fill me-2"></i> Stok bildirim talebiniz başarıyla iptal edildi.
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <ul class="nav nav-pills mb-4 bg-white p-2 rounded-pill shadow-sm border" id="alarmTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active rounded-pill fw-bold px-4" id="fiyat-tab" data-bs-toggle="tab" data-bs-target="#fiyat" type="button" role="tab">
                        <i class="bi bi-tag-fill me-1"></i> Fiyat Alarmları 
                        <span class="badge bg-light text-primary ms-1 rounded-pill"><?= count($fiyat_alarmlari) ?></span>
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link rounded-pill fw-bold px-4" id="stok-tab" data-bs-toggle="tab" data-bs-target="#stok" type="button" role="tab">
                        <i class="bi bi-box-seam-fill me-1"></i> Stok Alarmları
                        <span class="badge bg-light text-primary ms-1 rounded-pill"><?= count($stok_alarmlari) ?></span>
                    </button>
                </li>
            </ul>

            <div class="tab-content" id="alarmTabsContent">
                
                <div class="tab-pane fade show active" id="fiyat" role="tabpanel">
                    <div class="card shadow-sm border-0 rounded-4 p-4">
                        <?php if(empty($fiyat_alarmlari)): ?>
                            <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="<?= $kok_dizin ?>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 rounded-4">
                                <i class="bi bi-info-circle-fill me-2"></i> Ürünlerin fiyatı, alarm kurduğunuz fiyatın altına düştüğünde size e-posta ile 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($fiyat_alarmlari 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="<?= $kok_dizin ?><?= 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="<?= $kok_dizin ?>urun/<?= $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="<?= $kok_dizin ?>urun/<?= $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-price-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 class="tab-pane fade" id="stok" role="tabpanel">
                    <div class="row g-4">
                        <?php if (count($stok_alarmlari) > 0): ?>
                            <?php foreach ($stok_alarmlari as $item): 
                                $stokta_var = ($item['stock_quantity'] > 0 && $item['p_status'] == 1);
                            ?>
                                <div class="col-md-6 col-xl-4">
                                    <div class="card border-0 shadow-sm rounded-4 h-100 overflow-hidden">
                                        
                                        <div class="bg-light text-center p-3 border-bottom position-relative" style="height: 180px;">
                                            <a href="<?= $kok_dizin ?>urun/<?= $item['slug'] ?>">
                                                <img src="<?= $kok_dizin ?><?= htmlspecialchars($item['image']) ?>" class="img-fluid h-100" style="object-fit: contain; <?= !$stokta_var ? 'filter: grayscale(80%); opacity: 0.8;' : '' ?>" alt="Ürün Görseli">
                                            </a>
                                            <?php if($stokta_var): ?>
                                                <span class="position-absolute top-0 end-0 badge bg-success m-2 shadow-sm"><i class="bi bi-check-circle me-1"></i>Stokta</span>
                                            <?php else: ?>
                                                <span class="position-absolute top-0 end-0 badge bg-warning text-dark m-2 shadow-sm"><i class="bi bi-hourglass-split me-1"></i>Bekleniyor</span>
                                            <?php endif; ?>
                                        </div>

                                        <div class="card-body p-4 d-flex flex-column">
                                            <div class="text-muted small mb-1 fw-bold"><?= htmlspecialchars($item['brand_name'] ?? 'Genel') ?></div>
                                            <h6 class="fw-bold text-dark mb-2 lh-base" style="min-height: 40px;">
                                                <a href="<?= $kok_dizin ?>urun/<?= $item['slug'] ?>" class="text-dark text-decoration-none">
                                                    <?= htmlspecialchars($item['name']) ?>
                                                </a>
                                            </h6>
                                            
                                            <div class="mb-3 mt-auto">
                                                <span class="text-muted small d-block"><i class="bi bi-clock me-1"></i> Talep: <?= date('d.m.Y', strtotime($item['alert_date'])) ?></span>
                                                <div class="fs-5 fw-bold text-primary mt-1"><?= number_format($item['price'], 2, ',', '.') ?> ₺</div>
                                            </div>

                                            <div class="d-flex gap-2">
                                                <?php if($stokta_var): ?>
                                                    <a href="<?= $kok_dizin ?>urun/<?= $item['slug'] ?>" class="btn btn-success btn-sm w-100 rounded-pill fw-bold shadow-sm">
                                                        <i class="bi bi-cart-plus me-1"></i> Hemen Al
                                                    </a>
                                                <?php else: ?>
                                                    <button class="btn btn-outline-secondary btn-sm w-100 rounded-pill fw-bold" disabled>
                                                        <i class="bi bi-truck me-1"></i> Tedarik Aşamasında
                                                    </button>
                                                <?php endif; ?>
                                                
                                                <a href="fiyat-alarmlarim.php?iptal_stok=<?= $item['alert_id'] ?>" class="btn btn-outline-danger btn-sm rounded-pill px-3" onclick="return confirm('Bu ürün için stok bildirimi almaktan vazgeçmek istediğinize emin misiniz?');" title="Alarmı İptal Et">
                                                    <i class="bi bi-trash"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="col-12">
                                <div class="text-center py-5 bg-white rounded-4 shadow-sm border p-4">
                                    <i class="bi bi-box-seam text-muted opacity-25" style="font-size: 4rem;"></i>
                                    <h5 class="fw-bold mt-3 text-dark">Stok Alarmınız Bulunmuyor.</h5>
                                    <p class="text-muted">Tükendiğini gördüğünüz ürünlerde "Gelince Haber Ver" butonuna tıklayarak stokları buradan takip edebilirsiniz.</p>
                                    <a href="<?= $kok_dizin ?>deneme-sinav-takvimi.php" class="btn btn-primary rounded-pill mt-2 px-4 fw-bold">Takvimi İncele</a>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

            </div>

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

<script>
document.addEventListener("DOMContentLoaded", function() {
    
    // Fiyat Alarmı Silme İşlemi (AJAX)
    document.querySelectorAll('.remove-price-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();
                        }
                    });
                }
            });
        });
    });

    // Eğer URL'de stok iptal mesajı varsa, sayfayı yüklendiğinde direkt "Stok Alarmları" sekmesini aç
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('msg') === 'stok_deleted') {
        let stokTab = new bootstrap.Tab(document.querySelector('#stok-tab'));
        stokTab.show();
    }

});
</script>

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