<?php
session_start();
$db_path = file_exists('includes/db.php') ? 'includes/db.php' : '../includes/db.php';
if (file_exists($db_path)) {
    require $db_path;
} else {
    $conn = new mysqli('localhost', 'root', '', 'bajipari');
}

// Check Login
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$uid = $_SESSION['user_id'];
$settings_query = $conn->query("SELECT * FROM settings WHERE id=1");
$settings = $settings_query ? $settings_query->fetch_assoc() : [];
$site_name = 'Ruposhi88';

// --- PROMO CODE LOGIC START ---
$alert_msg = "";
$alert_type = ""; // success or error

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['apply_promo'])) {
    $code = $conn->real_escape_string(trim($_POST['promo_code']));

    if (!empty($code)) {
        // 1. Check if Code Exists & Active
        $chk_code = $conn->query("SELECT * FROM promo_codes WHERE code='$code' AND status='active'");
        
        if ($chk_code->num_rows > 0) {
            $promo = $chk_code->fetch_assoc();
            $promo_id = $promo['id'];
            $reward = $promo['reward'];

            // 2. Check if User Already Used This Code
            $chk_usage = $conn->query("SELECT id FROM promo_usage WHERE user_id=$uid AND promo_id=$promo_id");

            if ($chk_usage->num_rows == 0) {
                // 3. Start Transaction (Add Balance & Record Usage)
                $conn->begin_transaction();
                try {
                    // Update User Balance
                    $conn->query("UPDATE users SET balance = balance + $reward WHERE id=$uid");
                    
                    // Record Usage
                    $conn->query("INSERT INTO promo_usage (user_id, promo_id) VALUES ($uid, $promo_id)");
                    
                    // Optional: Record in Transaction History
                    $desc = "Promo Code: " . $code;
                    $conn->query("INSERT INTO transactions_fake (user_id, type, amount, method, status, created_at) VALUES ($uid, 'bonus', $reward, '$desc', 'approved', NOW())");

                    $conn->commit();
                    $alert_msg = "সফল হয়েছে! ৳" . $reward . " আপনার ব্যালেন্সে যোগ করা হয়েছে।";
                    $alert_type = "success";
                } catch (Exception $e) {
                    $conn->rollback();
                    $alert_msg = "ত্রুটি হয়েছে, আবার চেষ্টা করুন।";
                    $alert_type = "error";
                }
            } else {
                $alert_msg = "আপনি ইতিমধ্যে এই প্রমো কোডটি ব্যবহার করেছেন।";
                $alert_type = "error";
            }
        } else {
            $alert_msg = "Invalid Promo Code (ভুল কোড)";
            $alert_type = "error";
        }
    } else {
        $alert_msg = "অনুগ্রহ করে একটি কোড লিখুন।";
        $alert_type = "error";
    }
}
// --- PROMO CODE LOGIC END ---

// Filter Logic
$cat = isset($_GET['cat']) ? $_GET['cat'] : 'all';
$sql = "SELECT * FROM promotions WHERE status='active'";
if ($cat != 'all') {
    $cat_safe = $conn->real_escape_string($cat);
    $sql .= " AND category='$cat_safe'";
}
$sql .= " ORDER BY is_new DESC, id DESC";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>প্রমোশন - <?php echo $site_name; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        body { 
            font-family: 'Hind Siliguri', sans-serif; 
            background-color: #111827;
            color: #fff; 
            padding-bottom: 90px; 
        }
        .header-bg { background-color: #1F2937; border-bottom: 1px solid rgba(255,255,255,0.05); }
        .tab-scroll::-webkit-scrollbar { display: none; }
        .tab-btn {
            background-color: #374151; color: #9CA3AF; padding: 6px 16px;
            font-size: 13px; font-weight: 500; border-radius: 4px;
            white-space: nowrap; margin-right: 8px; transition: all 0.3s;
        }
        .tab-btn.active { background-color: #F59E0B; color: black; font-weight: bold; }
        
        .promo-card {
            border-radius: 8px; overflow: hidden; margin-bottom: 15px;
            position: relative; background: #1F2937; border: 1px solid rgba(255,255,255,0.05);
        }
        .promo-img-container { position: relative; height: 150px; }
        .promo-img { width: 100%; height: 100%; object-fit: cover; }
        .badge-new {
            position: absolute; top: 10px; left: 0; background: #F59E0B;
            color: black; font-size: 10px; font-weight: bold; padding: 2px 8px;
            border-top-right-radius: 4px; border-bottom-right-radius: 4px; z-index: 10;
        }
        .card-content { padding: 12px; }
        .promo-title { font-size: 15px; font-weight: bold; color: white; margin-bottom: 4px; }
        .promo-subtitle { font-size: 12px; color: #9CA3AF; margin-bottom: 8px; }
        .promo-meta { font-size: 11px; color: #6B7280; display: flex; align-items: center; gap: 5px; margin-bottom: 12px; }
        .btn-detail {
            background: linear-gradient(to bottom, #FDE047, #EAB308); color: black;
            width: 100%; padding: 8px 0; border-radius: 4px; font-size: 13px;
            font-weight: bold; text-align: center; border: none; cursor: pointer;
        }
        .details-box {
            background: #111827; padding: 15px; font-size: 13px; color: #D1D5DB;
            border-top: 1px solid rgba(255,255,255,0.1);
        }
        /* Custom Alert */
        .custom-alert {
            padding: 10px; border-radius: 6px; margin: 10px 12px; font-size: 13px; font-weight: bold; text-align: center;
        }
        .alert-success { background-color: #065F46; color: #D1FAE5; border: 1px solid #059669; }
        .alert-error { background-color: #7F1D1D; color: #FECACA; border: 1px solid #DC2626; }
    </style>
</head>
<body>

    <header class="header-bg flex items-center justify-between px-4 py-4 sticky top-0 z-50 shadow-md">
        <div class="flex items-center gap-4">
            <a href="dashboard.php" class="text-xl text-white"><i class="fas fa-chevron-left"></i></a>
            <h1 class="text-lg font-bold">Promotion</h1>
        </div>
        <a href="#" class="text-white"><i class="fas fa-times"></i></a>
    </header>

    <div class="px-4 py-3 bg-[#1F2937] sticky top-[60px] z-40 overflow-x-auto tab-scroll flex border-b border-gray-700">
        <a href="?cat=all" class="tab-btn <?php echo $cat=='all'?'active':''; ?>">ALL</a>
        <a href="?cat=welcome" class="tab-btn <?php echo $cat=='welcome'?'active':''; ?>">Welcome Offer</a>
        <a href="?cat=slots" class="tab-btn <?php echo $cat=='slots'?'active':''; ?>">Slots</a>
        <a href="?cat=live" class="tab-btn <?php echo $cat=='live'?'active':''; ?>">Live Casino</a>
        <a href="?cat=sports" class="tab-btn <?php echo $cat=='sports'?'active':''; ?>">Sports</a>
    </div>

    <?php if(!empty($alert_msg)): ?>
        <div class="custom-alert <?php echo $alert_type == 'success' ? 'alert-success' : 'alert-error'; ?>">
            <?php echo $alert_msg; ?>
        </div>
    <?php endif; ?>

    <form method="POST" class="px-3 mt-3 flex gap-2">
        <input type="text" name="promo_code" placeholder="Promo Code" class="bg-[#1F2937] text-white text-sm px-3 py-2 rounded border border-gray-700 w-full outline-none focus:border-[#EAB308]">
        <button type="submit" name="apply_promo" class="bg-[#EAB308] text-black font-bold px-6 rounded text-sm hover:bg-[#CA8A04] transition">Add</button>
    </form>

    <div class="px-3 space-y-4 mt-4">
        
        <?php if($result && $result->num_rows > 0): ?>
            <?php while($row = $result->fetch_assoc()): ?>
            <div class="promo-card">
                
                <div class="promo-img-container">
                    <?php if($row['is_new']): ?>
                        <div class="badge-new">NEW</div>
                    <?php endif; ?>
                    <?php 
                        $img_src = !empty($row['image_path']) ? "../" . $row['image_path'] : "https://placehold.co/600x250/1F2937/FFFFFF?text=PROMO";
                    ?>
                    <img src="<?php echo $img_src; ?>" class="promo-img">
                </div>
                
                <div class="card-content">
                    <h3 class="promo-title"><?php echo $row['title']; ?></h3>
                    <p class="promo-subtitle"><?php echo $row['subtitle'] ?? 'Exclusive Offer'; ?></p>
                    
                    <div class="promo-meta">
                        <i class="far fa-clock"></i>
                        <span>
                            <?php echo date('d/m/Y', strtotime($row['start_date'])); ?> 
                            - 
                            <?php echo date('d/m/Y', strtotime($row['end_date'])); ?>
                        </span>
                    </div>

                    <button onclick="toggleDetails(<?php echo $row['id']; ?>)" class="btn-detail">
                        Detail
                    </button>
                </div>

                <div id="details-<?php echo $row['id']; ?>" class="hidden details-box">
                    <p class="mb-2 leading-relaxed whitespace-pre-line"><?php echo $row['description']; ?></p>
                    
                    <div class="flex justify-between mt-3 text-xs text-gray-400 border-t border-white/10 pt-2">
                        <span>Bonus: <span class="text-yellow-400 font-bold"><?php echo $row['bonus_amount']; ?></span></span>
                        <span>Turnover: x<?php echo $row['turnover_req'] ?? '1'; ?></span>
                    </div>
                </div>

            </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="text-center py-20 opacity-50">
                <i class="fas fa-gift text-5xl mb-3 text-gray-600"></i>
                <p>No promotions available</p>
            </div>
        <?php endif; ?>

    </div>

    <div class="fixed bottom-0 w-full h-[70px] bg-[#111827] border-t border-white/10 z-50 flex justify-between px-2 items-center text-gray-400">
        <a href="dashboard.php" class="flex flex-col items-center justify-center w-1/5 h-full hover:text-white">
            <i class="fas fa-home text-xl mb-1"></i>
            <span class="text-[10px]">Home</span>
        </a>
        <a href="promotions.php" class="flex flex-col items-center justify-center w-1/5 h-full text-white">
            <i class="fas fa-gift text-xl mb-1 text-[#EAB308]"></i>
            <span class="text-[10px] text-[#EAB308]">Promotions</span>
        </a>
        
        <div class="w-1/5 h-full relative flex justify-center">
            <a href="deposit.php" class="absolute -top-6 w-14 h-14 bg-[#111827] rounded-full border-t border-white/10 flex items-center justify-center">
                <div class="w-11 h-11 bg-gradient-to-br from-[#FDE047] to-[#EAB308] rounded-full flex items-center justify-center text-black text-xl shadow-lg">
                    <i class="fas fa-wallet"></i>
                </div>
            </a>
            <span class="absolute bottom-2 text-[10px]">Deposit</span>
        </div>

        <a href="account.php" class="flex flex-col items-center justify-center w-1/5 h-full hover:text-white">
            <i class="fas fa-user text-xl mb-1"></i>
            <span class="text-[10px]">Account</span>
        </a>
    </div>

    <script>
        function toggleDetails(id) {
            const details = document.getElementById('details-' + id);
            details.classList.toggle('hidden');
        }
        
        // Hide Alert after 3 seconds
        setTimeout(function() {
            const alertBox = document.querySelector('.custom-alert');
            if(alertBox) alertBox.style.display = 'none';
        }, 4000);
    </script>

</body>
</html>