<?php
// Include the database connection file, which also starts the session.
require_once 'includes/db_connect.php';

// Security Check: If the user is not logged in, redirect them to the login page.
if (!isset($_SESSION["user_id"])) {
    header("location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];

// First, get the logged-in user's level_id from the users table. This is crucial for dynamic pricing.
$user_level_stmt = $conn->prepare("SELECT level_id FROM users WHERE id = ?");
$user_level_stmt->bind_param("i", $user_id);
$user_level_stmt->execute();
$user_level_id = $user_level_stmt->get_result()->fetch_assoc()['level_id'];
$user_level_stmt->close();

// Check for an operator filter from the URL (e.g., packages.php?operator=Robi)
$operator_filter = $_GET['operator'] ?? 'All';

// This is the main SQL query to fetch offers.
// It joins 'offers' with 'offer_commissions' to calculate the final price for the user's specific level.
$sql = "SELECT 
            o.id,
            o.offer_name,
            o.description,
            o.price AS base_price,
            (o.price - IFNULL(oc.discount, 0)) AS final_price
        FROM offers o
        LEFT JOIN offer_commissions oc ON o.id = oc.offer_id AND oc.level_id = ?
        WHERE o.status = 'Active'";

// Prepare parameters for the prepared statement
$params = [$user_level_id];
$types = 'i'; // 'i' for integer (level_id)

// If an operator filter is selected, add it to the SQL query and parameters.
if ($operator_filter !== 'All') {
    $sql .= " AND o.operator = ?";
    $params[] = $operator_filter;
    $types .= 's'; // 's' for string (operator name)
}

$sql .= " ORDER BY o.price ASC";

// Execute the prepared statement
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$offers_result = $stmt->get_result();

// List of operators for the filter buttons
$operators = ['All', 'Grameenphone', 'Robi', 'Banglalink', 'Airtel', 'Teletalk'];
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>প্যাকেজ ও অফার</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        body { background-color: #f4f7f6; font-family: 'Noto Sans Bengali', sans-serif; }
        .operator-filter { display: flex; overflow-x: auto; padding-bottom: 10px; margin-bottom: 20px; white-space: nowrap; -ms-overflow-style: none; scrollbar-width: none; }
        .operator-filter::-webkit-scrollbar { display: none; }
        .operator-filter .btn { flex-shrink: 0; margin-right: 10px; }
        .offer-card { margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); border: none; border-radius: 10px; }
        .offer-card .card-body { padding: 1.5rem; }
        .offer-card .card-title { font-weight: bold; }
        .offer-card .price { font-size: 1.75rem; font-weight: bold; color: #0d6efd; }
    </style>
</head>
<body>
    <div class="container my-4">
        <div class="d-flex align-items-center mb-3">
             <a href="index.php" class="text-dark fs-4 me-3 text-decoration-none"><i class="fas fa-arrow-left"></i></a>
             <h3 class="mb-0">সকল প্যাকেজ ও অফার</h3>
        </div>

        <div class="operator-filter">
            <?php foreach ($operators as $op): ?>
                <a href="packages.php?operator=<?php echo $op; ?>" class="btn btn-<?php echo ($operator_filter == $op) ? 'primary' : 'outline-primary'; ?>"><?php echo $op; ?></a>
            <?php endforeach; ?>
        </div>
        
        <div class="row">
            <?php if ($offers_result->num_rows > 0): ?>
                <?php while($offer = $offers_result->fetch_assoc()): ?>
                    <div class="col-md-6 col-lg-4">
                        <div class="card offer-card">
                            <div class="card-body">
                                <h5 class="card-title"><?php echo htmlspecialchars($offer['offer_name']); ?></h5>
                                <p class="card-text text-muted"><?php echo htmlspecialchars($offer['description']); ?></p>
                                <div class="d-flex justify-content-between align-items-center mt-3">
                                    <div>
                                        <span class="price">৳<?php echo number_format($offer['final_price'], 2); ?></span>
                                        <?php if ($offer['final_price'] < $offer['base_price']): ?>
                                            <del class="text-muted ms-2">৳<?php echo number_format($offer['base_price'], 2); ?></del>
                                        <?php endif; ?>
                                    </div>
                                    <a href="buy_package.php?id=<?php echo $offer['id']; ?>" class="btn btn-success">এখনই কিনুন</a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <p class="text-center text-muted mt-4">এই অপারেটরের জন্য কোনো অফার পাওয়া যায়নি।</p>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>