<?php
/**
 * Pluscash Offerwall - Fixed Width Responsive Version
 * Targeted for: Pluscash
 */

// 1. Capture Parameters
$apiKey   = $_GET['api-key'] ?? '';
$rate     = floatval($_GET['rate'] ?? 1); 
$username = $_GET['username'] ?? 'guest';

// IP & Geo Detection
$userIp = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
$userCountry = 'EG'; // Default

if ($userIp !== '::1' && $userIp !== '127.0.0.1') {
    $ipInfo = json_decode(@file_get_contents("http://ip-api.com/json/{$userIp}"), true);
    if (!empty($ipInfo['countryCode'])) {
        $userCountry = strtoupper($ipInfo['countryCode']);
    }
}

// Device Detection
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
$myDevice = 'desktop';
if (strpos($ua, 'android') !== false) { $myDevice = 'android'; }
elseif (strpos($ua, 'iphone') !== false || strpos($ua, 'ipad') !== false) { $myDevice = 'ios'; }

// 2. Data Fetching
$url = 'https://api.eflow.team/v1/affiliates/offersrunnable';
$finalOffers = [];

if ($apiKey) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-Eflow-API-Key: $apiKey", "Content-Type: application/json"]);
    $response = curl_exec($ch);
    $data = json_decode($response, true);
    $rawOffers = $data['offers'] ?? [];

    foreach ($rawOffers as $offer) {
        $rules = $offer['relationship']['ruleset'] ?? [];
        
        // Country Filter logic
        $targetCountries = array_column($rules['countries'] ?? [], 'country_code');
        if (!empty($targetCountries) && !in_array($userCountry, $targetCountries)) {
            continue; 
        }

        // Device/Platform Filter logic
        $targetPlatforms = array_map('strtolower', array_column($rules['platforms'] ?? [], 'label'));
        $targetDevices   = array_map('strtolower', array_column($rules['device_types'] ?? [], 'label'));
        
        $isDeviceMatch = false;
        if (empty($targetPlatforms) && empty($targetDevices)) {
            $isDeviceMatch = true;
        } else {
            if (in_array($myDevice, $targetPlatforms)) $isDeviceMatch = true;
            if ($myDevice !== 'desktop' && in_array('mobile', $targetDevices)) $isDeviceMatch = true;
            if ($myDevice === 'desktop' && in_array('pc', $targetDevices)) $isDeviceMatch = true;
        }

        if (!$isDeviceMatch) continue;

        // Payout Mapping
        $payouts = $offer['relationship']['payouts']['entries'] ?? [];
        $totalReward = 0;
        $missions = [];
        foreach ($payouts as $p) {
            $amt = round(($p['payout_amount'] ?? 0) * $rate);
            if ($amt > 0) {
                $totalReward += $amt;
                $missions[] = ['name' => $p['entry_name'], 'reward' => $amt];
            }
        }

        // Tracking Link: username appended after slash
        $baseLink = $offer['tracking_url'] ?? '';
        if (substr($baseLink, -1) !== '/') $baseLink .= '/';

        $finalOffers[] = [
            'name'   => $offer['name'],
            'icon'   => $offer['thumbnail_url'],
            'url'    => $baseLink . urlencode($username),
            'reward' => $totalReward,
            'tasks'  => $missions
        ];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Offers | GoldTasker</title>
    <style>
        :root {
            --primary: #7047eb;
            --bg: #f4f7fa;
            --card: #ffffff;
            --text-dark: #1a1c21;
            --text-muted: #6e7687;
            --gold: #ffa800;
        }

        * { 
            box-sizing: border-box; 
            margin: 0; 
            padding: 0; 
            -webkit-tap-highlight-color: transparent; 
        }

        body { 
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; 
            background: var(--bg); 
            color: var(--text-dark); 
            overflow-x: hidden; /* Prevent horizontal scroll */
            width: 100%;
        }

        /* Navbar */
        .navbar {
            background: #fff; 
            padding: 15px 20px; 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            position: sticky; 
            top: 0; 
            z-index: 100; 
            border-bottom: 1px solid #eef2f6;
            width: 100%;
        }
        .navbar h1 { font-size: 1.1rem; font-weight: 800; }
        .badge { 
            font-size: 10px; font-weight: 800; padding: 4px 10px; 
            border-radius: 50px; background: #f1edff; color: var(--primary); 
            text-transform: uppercase;
        }

        /* Main Container - Fixed width for responsiveness */
        .container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 16px;
            display: grid;
            grid-template-columns: 1fr; /* Single column for mobile */
            gap: 12px;
        }

        /* Responsive Grid Breakpoints */
        @media (min-width: 768px) {
            .container { grid-template-columns: repeat(2, 1fr); }
        }
        @media (min-width: 1024px) {
            .container { grid-template-columns: repeat(3, 1fr); }
        }

        /* Card Fixes */
        .offer-card { 
            background: var(--card); 
            border-radius: 20px; 
            padding: 16px; 
            display: flex; 
            align-items: center; 
            box-shadow: 0 4px 10px rgba(0,0,0,0.03);
            cursor: pointer; 
            transition: transform 0.2s;
            width: 100%;
            overflow: hidden; /* Contain elements */
        }
        .offer-card:active { transform: scale(0.98); }
        
        .offer-icon { 
            width: 56px; height: 56px; 
            border-radius: 14px; 
            object-fit: cover; 
            flex-shrink: 0; /* Stop icon from squishing */
            margin-right: 14px; 
            background: #f0f0f0; 
        }
        
        .offer-details { 
            flex: 1; 
            min-width: 0; /* CRITICAL: Allows text truncation inside flexbox */
        }
        .offer-name { 
            font-size: 14px; 
            font-weight: 700; 
            margin-bottom: 4px; 
            white-space: nowrap; 
            overflow: hidden; 
            text-overflow: ellipsis; /* Prevents long names from breaking layout */
        }
        .offer-tag { font-size: 9px; font-weight: 800; color: var(--primary); text-transform: uppercase; }

        .offer-payout { 
            text-align: right; 
            flex-shrink: 0;
            padding-left: 10px;
        }
        .reward-amt { color: var(--gold); font-weight: 800; font-size: 15px; }

        /* Modal Overlay */
        #modal-overlay { 
            display: none; position: fixed; inset: 0; 
            background: rgba(0,0,0,0.6); z-index: 1000; 
            align-items: flex-end; justify-content: center; backdrop-filter: blur(5px);
        }
        .modal { 
            background: #fff; width: 100%; max-width: 500px; 
            border-radius: 28px 28px 0 0; padding: 24px; 
            animation: slideUp 0.3s ease-out;
        }
        .task-item { display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #f3f4f6; font-size: 13px; }
        .btn { display: block; width: 100%; background: var(--primary); color: #fff; text-align: center; text-decoration: none; padding: 16px; border-radius: 16px; font-weight: 800; margin-top: 20px; }

        @keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
        @media (min-width: 768px) {
            #modal-overlay { align-items: center; padding: 20px; }
            .modal { border-radius: 24px; max-width: 400px; }
        }
    </style>
</head>
<body>

    <nav class="navbar">
        <h1>GoldTasker Offers</h1>
        <div style="display:flex; gap:6px;">
            <div class="badge"><?= $userCountry ?></div>
            <div class="badge"><?= $myDevice ?></div>
        </div>
    </nav>

    <main class="container">
        <?php if (empty($finalOffers)): ?>
            <div style="grid-column: 1 / -1; text-align: center; padding: 60px 20px; color: var(--text-muted);">
                No compatible offers found for your location.
            </div>
        <?php else: ?>
            <?php foreach ($finalOffers as $o): ?>
                <div class="offer-card" onclick='openModal(<?= json_encode($o) ?>)'>
                    <img src="<?= $o['icon'] ?>" class="offer-icon">
                    <div class="offer-details">
                        <div class="offer-name"><?= htmlspecialchars($o['name']) ?></div>
                        <span class="offer-tag">Free</span>
                    </div>
                    <div class="offer-payout">
                        <div class="reward-amt"><?= number_format($o['reward']) ?> 🪙</div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </main>

    <div id="modal-overlay" onclick="if(event.target === this) closeModal()">
        <div class="modal">
            <div style="display:flex; gap:15px; margin-bottom:20px;">
                <img id="m-icon" style="width:64px; height:64px; border-radius:14px; object-fit:cover;">
                <div>
                    <div id="m-name" style="font-weight: 800; font-size: 18px; margin-bottom: 5px;"></div>
                    <span class="offer-tag">Install & Earn</span>
                </div>
            </div>
            <div id="m-list"></div>
            <a id="m-link" href="#" target="_blank" class="btn">Start Earning</a>
        </div>
    </div>

    <script>
        function openModal(o) {
            document.getElementById('m-icon').src = o.icon;
            document.getElementById('m-name').innerText = o.name;
            document.getElementById('m-link').href = o.url;
            const list = document.getElementById('m-list');
            list.innerHTML = '';
            o.tasks.forEach(t => {
                list.innerHTML += `<div class="task-item"><span>${t.name}</span><span style="color:var(--gold); font-weight:800;">+${t.reward.toLocaleString()}</span></div>`;
            });
            document.getElementById('modal-overlay').style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }
        function closeModal() {
            document.getElementById('modal-overlay').style.display = 'none';
            document.body.style.overflow = 'auto';
        }
    </script>
</body>
</html>