<?php
/**
 * Kullanıcı Paneli - Stok Alarmlarım (Gelince Haber Ver)
 * Konum: /magaza/kullanici/stok-alarmlari.php
 */

require_once '../includes/db.php';
require_once '../includes/functions.php';

$kok_dizin = "/magaza/";

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

// Alarm İptal İşlemi
if (isset($_GET['iptal']) && is_numeric($_GET['iptal'])) {
    $alert_id = (int)$_GET['iptal'];
    // Sadece kullanıcının kendi alarmını silebilmesi için user_id kontrolü yapıyoruz
    $del = $db->prepare("DELETE FROM stock_alerts WHERE id = ? AND user_id = ?");
    $del->execute([$alert_id, $user_id]);
    
    header("Location: stok-alarmlari.php?msg=deleted");
    exit;
}

// Kullanıcının Beklediği Ürünleri Çek
$sql = "SELECT sa.id as alert_id, sa.created_at, 
               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 main_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 = :user_id AND sa.status = 0
        ORDER BY sa.created_at DESC";

$stmt = $db->prepare($sql);
$stmt->execute([':user_id' => $user_id]);
$alarmlar = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

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

        <div class="col-lg-9">
            
            <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
                <div>
                    <h2 class="h4 fw-bold mb-0 text-primary">
                        <i class="bi bi-bell-fill me-2"></i>Stok Alarmlarım
                    </h2>
                    <p class="text-muted small mt-1 mb-0">"Gelince Haber Ver" dediğiniz denemeler ve güncel stok durumları.</p>
                </div>
            </div>

            <?php if(isset($_GET['msg']) && $_GET['msg'] == '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> Bildirim talebiniz başarıyla iptal edildi.
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            <?php endif; ?>

            <div class="row g-4">
                <?php if (count($alarmlar) > 0): ?>
                    <?php foreach ($alarmlar as $item): 
                        // Eğer kullanıcı sayfaya girdiğinde ürün stoğa girmişse onu uyaralım
                        $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['main_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['created_at'])) ?></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="stok-alarmlari.php?iptal=<?= $item['alert_id'] ?>" class="btn btn-outline-danger btn-sm rounded-pill px-3" onclick="return confirm('Bu ürün için bildirim 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">
                            <i class="bi bi-bell-slash 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>
</main>

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