<?php 
include('config.php');
include('function.php');
include('countrycodes.php');

date_default_timezone_set('UTC'); // tetap UTC
$today = gmdate('Y-m-d');
$yesterday = gmdate('Y-m-d', strtotime('-1 day'));

define('GX_PATH', realpath(__DIR__.'/'));
define('GX_LIB', GX_PATH.'/lib/');

require 'autoload.php';
$page = 'dashboard';

// Login check
if (isset($_POST['loginpass']) && $_POST['password'] != "") {
    if ($_POST['password'] == $passWd) {
        $_SESSION['loggedIn'] = true;
    } else {
        $loginError = "Password Salah!";
    }
} 

if (!isset($_SESSION['loggedIn'])) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=1024, initial-scale=1, user-scalable=no">
        <title>Login - Dashboard Report</title>
        <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <style>
            html, body {
                min-width: 1024px;
                width: 100%;
            }

            body {
                font-family: 'Inter', sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
                overflow-x: auto;
            }
            .login-card {
                background: rgba(255, 255, 255, 0.95);
                backdrop-filter: blur(10px);
                border-radius: 20px;
                box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
                border: 1px solid rgba(255, 255, 255, 0.2);
            }
            .login-header {
                background: linear-gradient(135deg, #6366f1, #8b5cf6);
                color: white;
                border-radius: 20px 20px 0 0;
                padding: 2rem;
                text-align: center;
            }
            .form-control {
                border-radius: 12px;
                border: 2px solid #e2e8f0;
                padding: 0.75rem 1rem;
                transition: all 0.3s ease;
            }
            .form-control:focus {
                border-color: #6366f1;
                box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
            }
            .btn-login {
                background: linear-gradient(135deg, #6366f1, #8b5cf6);
                border: none;
                border-radius: 12px;
                padding: 0.75rem 2rem;
                font-weight: 600;
                transition: all 0.3s ease;
            }
            .btn-login:hover {
                transform: translateY(-2px);
                box-shadow: 0 10px 25px rgba(99, 102, 241, 0.3);
            }

            /* Force Desktop View - Disable responsive behavior */
            @media (max-width: 768px) {
                html, body {
                    min-width: 1024px;
                }
                .container {
                    min-width: 1024px;
                }
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-md-4">
                    <div class="login-card">
                        <div class="login-header">
                            <i class="fas fa-shield-alt fa-3x mb-3"></i>
                            <h4 class="mb-0">Dashboard Login</h4>
                            <p class="mb-0 opacity-75">Enter your password to continue</p>
                        </div>
                        <div class="p-4">
                            <?php if (isset($loginError)) { ?>
                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                    <i class="fas fa-exclamation-circle me-2"></i>
                                    <?= $loginError; ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            <?php } ?>
                            
                            <form action="" method="post">
                                <div class="mb-4">
                                    <label for="password" class="form-label fw-semibold">Password</label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-end-0">
                                            <i class="fas fa-lock text-muted"></i>
                                        </span>
                                        <input type="password" name="password" id="password" class="form-control border-start-0" 
                                               placeholder="Enter your password" required autofocus>
                                    </div>
                                </div>
                                <button type="submit" name="loginpass" class="btn btn-login text-white w-100">
                                    <i class="fas fa-sign-in-alt me-2"></i>
                                    Login to Dashboard
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>
    <?php
    exit;
}

// Main dashboard content
include('dashboard_header.php');

new Db();

echo "<h1>🔥LANDAK TEAM🔥</h1>";

// Get date filter
if (isset($_GET['date'])) {
    if ($_GET['date'] == 'today') {
        $date = date('Y-m-d');
    } elseif ($_GET['date'] == 'yesterday') {
        $date = date('Y-m-d', strtotime("yesterday"));
    }
} else {
    $date = date('Y-m-d');
}

// Get data
$conversions = Db::result("SELECT * FROM `conversions` WHERE DATE(`date`) = '{$date}' ORDER BY `id` DESC");
$lastipq = Db::result("SELECT `id` FROM `hitstat` ORDER BY `id` DESC LIMIT 1");
$lastip_id = (Db::$num_rows > 0) ? $lastipq[0]->id : 0;
$lastq = Db::result("SELECT `id` FROM `conversions` ORDER BY `id` DESC LIMIT 1");
$last_id = (isset($lastq[0])) ? $lastq[0]->id : 0;

// Calculate statistics
$totalEarning = 0;
$totalConversions = 0;
$networkStats = [];

if (!isset($conversions['error']) && !empty($conversions)) {
    foreach ($conversions as $conversion) {
        $totalEarning += $conversion->payout;
        $totalConversions++;
        
        if (!isset($networkStats[$conversion->network])) {
            $networkStats[$conversion->network] = ['count' => 0, 'earning' => 0];
        }
        $networkStats[$conversion->network]['count']++;
        $networkStats[$conversion->network]['earning'] += $conversion->payout;
    }
}

// Get today's stats
$todayStats = Db::result("SELECT COUNT(*) as count, SUM(payout) as earning FROM `conversions` WHERE DATE(`date`) = '$today'");
$todayCount = $todayStats[0]->count ?? 0;
$todayEarning = $todayStats[0]->earning ?? 0;

// Get yesterday's stats for comparison
$yesterdayStats = Db::result("SELECT COUNT(*) as count, SUM(payout) as earning FROM `conversions` WHERE DATE(`date`) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)");
$yesterdayCount = $yesterdayStats[0]->count ?? 0;
$yesterdayEarning = $yesterdayStats[0]->earning ?? 0;

// Calculate percentage changes
$conversionChange = $yesterdayCount > 0 ? (($todayCount - $yesterdayCount) / $yesterdayCount) * 100 : 0;
$earningChange = $yesterdayEarning > 0 ? (($todayEarning - $yesterdayEarning) / $yesterdayEarning) * 100 : 0;

// Get unique countries
$uniqueCountries = Db::result("SELECT DISTINCT country FROM `conversions` WHERE `date` LIKE '%{$date}%'");
$countryCount = count($uniqueCountries);

// Get hits data
$hitsToday = Db::result("SELECT COUNT(*) as count FROM `hitstat` WHERE DATE(`date`) = CURDATE()");
$hitsCount = $hitsToday[0]->count ?? 0;
?>

<!-- Quick Filters -->
<div class="content-card mb-4">
    <div class="card-header">
        <h5 class="card-title mb-0">
            <i class="fas fa-filter me-2"></i>
            Quick Filters
        </h5>
    </div>
    <div class="card-body">
        <div class="search-filters">
            <div class="search-input">
                <input type="text" id="globalSearch" class="form-control" placeholder="🔍 Search conversions..." />
            </div>
            <select class="form-control" id="dateFilter" style="max-width: 200px;">
                <option value="">Select Date</option>
                <option value="today" <?= (isset($_GET['date']) && $_GET['date'] == 'today') ? 'selected' : ''; ?>>Today</option>
                <option value="yesterday" <?= (isset($_GET['date']) && $_GET['date'] == 'yesterday') ? 'selected' : ''; ?>>Yesterday</option>
            </select>
            <button class="btn btn-primary" onclick="toggleAutoRefresh()">
                <i class="fas fa-sync-alt me-1"></i>
                Auto Refresh
            </button>
        </div>
    </div>
</div>

<!-- Conversions Table -->
<div class="content-card">
    <div class="card-header">
        <h5 class="card-title mb-0">
            <i class="fas fa-table me-2"></i>
            Live Conversions - <?= date('d M Y', strtotime($date)); ?>
        </h5>
        <div class="d-flex align-items-center gap-2">
            <span class="badge badge-success pulse">Live</span>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="dataTable" class="modern-table">
                <thead>
                    <tr>
                        <th>User ID</th>
                        <th class="text-center">Network</th>
                        <th class="text-center">Traffic</th>
                        <th class="text-center">Country</th>
                        <th class="text-center">Amount</th>
                        <th class="text-center">Time</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                if (!isset($conversions['error']) && !empty($conversions)) {

                    // Hitung total payout per user ID
                    $userTotalPayout = [];
                    foreach ($conversions as $c) {
                        if (!isset($userTotalPayout[$c->subid])) {
                            $userTotalPayout[$c->subid] = 0;
                        }
                        $userTotalPayout[$c->subid] += $c->payout;
                    }

                    // Cari user ID dengan total payout tertinggi
                    $maxTotalPayout = 0;
                    $topUserId = '';
                    foreach ($userTotalPayout as $userId => $total) {
                        if ($total > $maxTotalPayout) {
                            $maxTotalPayout = $total;
                            $topUserId = $userId;
                        }
                    }

                    foreach ($conversions as $conversion) {
                        $payout = number_format($conversion->payout, 2);
                        $country = strtolower($conversion->country);

                        // Traffic icon
                        $os = "<span class='text-muted'>-</span>";
                        if (in_array($conversion->os, ["web", "desktop", "Windows"])) {
                            $os = "<i class='fas fa-desktop text-primary'></i>";
                        } elseif (in_array($conversion->os, ["WAP", "android", "Android", "ios", "iOS"])) {
                            $os = "<i class='fas fa-mobile-alt text-success'></i>";
                        } elseif ($conversion->os == "tablet") {
                            $os = "<i class='fas fa-tablet-alt text-info'></i>";
                        }

                        // User ID display dengan RGB bergerak jika user ID memiliki total payout tertinggi
                        if ($conversion->subid == $topUserId) {
                            $userDisplay = "<span class='rgb-moving'><i class='fas fa-user me-1'></i>{$conversion->subid}</span>";
                            $userDisplay .= " <i class='fas fa-crown text-warning' title='Highest Total Payout'></i>";
                        } else {
                            $userDisplay = "<i class='fas fa-user me-1'></i>{$conversion->subid}";
                        }

                        // Network logo
$logo = "assets/network/{$conversion->network}.png";

if (!file_exists($logo)) {
    $logo = "assets/network/trafee.png";
}

$networkLogo = "<img src='{$logo}' alt='{$conversion->network}' height='24'>";

                        echo "<tr class='searchable-row'>
                            <td>
                                <a href='statsID.php?id={$conversion->subid}' class='text-decoration-none'>
                                    {$userDisplay}
                                </a>
                            </td>
                            <td class='text-center'>{$networkLogo}</td>
                            <td class='text-center'>{$os}</td>
                            <td class='text-center'>
                                <span class='flag-icon flag-icon-{$country} me-1'></span>
                                " . strtoupper($country) . "
                            </td>
                            <td class='text-center text-success fw-bold'>$" . $payout . "</td>
                            <td class='text-center text-white small'>" . date('H:i:s', strtotime($conversion->date)) . "</td>
                        </tr>";
                    }
                } else {
                    echo "<tr><td colspan='6' class='text-center text-muted py-4'>
                            <i class='fas fa-inbox fa-2x mb-2 d-block'></i>
                            No conversions found for this date
                          </td></tr>";
                }
                ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="4" class="text-end fw-bold">Total Payout:</td>
                        <td colspan="2" class="text-success fw-bold">$<?= number_format($totalEarning, 2); ?></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

<!-- Hidden inputs for real-time updates -->
<input type="hidden" id="lastip_id" value="<?= $lastip_id; ?>">
<input type="hidden" id="last_id" value="<?= $last_id; ?>">

<script>
// Date filter functionality
document.getElementById('dateFilter').addEventListener('change', function() {
    const date = this.value;
    if (date) {
        window.location.href = '?date=' + date;
    }
});

// Real-time counter animation
function animateValue(element, start, end, duration) {
    const range = end - start;
    let current = start;
    const increment = end > start ? 1 : -1;
    const stepTime = Math.abs(Math.floor(duration / range));
    
    const timer = setInterval(() => {
        current += increment;
        element.textContent = current.toLocaleString();
        if (current == end) {
            clearInterval(timer);
        }
    }, stepTime);
}

// Initialize animations on page load
document.addEventListener('DOMContentLoaded', function() {
    const statValues = document.querySelectorAll('.stat-value');
    statValues.forEach(element => {
        const finalValue = parseInt(element.textContent.replace(/[,$]/g, ''));
        if (!isNaN(finalValue)) {
            element.textContent = '0';
            setTimeout(() => {
                animateValue(element, 0, finalValue, 1000);
            }, 300);
        }
    });
});
</script>

<?php include('dashboard_footer.php'); ?>
