<?php
session_start();
require_once 'php/adminconfig.php';

// Enhanced login and role check
if (!isset($_SESSION['admin_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: signin-admin.php');
    exit();
}

// Simple logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header('Location: signin-admin.php');
    exit();
}

// Get overview data
function getOverviewData($conn) {
    $overview = [];
    
    // Get total users
    $stmt = $conn->prepare("SELECT COUNT(*) as total FROM users");
    $stmt->execute();
    $overview['total_users'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Get total payments - Check if payments table exists first
    try {
        $stmt = $conn->prepare("SHOW TABLES LIKE 'payments'");
        $stmt->execute();
        if ($stmt->rowCount() > 0) {
            $stmt = $conn->prepare("SELECT COUNT(*) as total FROM payments");
            $stmt->execute();
            $overview['total_payments'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        } else {
            // If table doesn't exist, fall back to payment_details
            $stmt = $conn->prepare("SELECT COUNT(*) as total FROM payment_details");
            $stmt->execute();
            $overview['total_payments'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        }
    } catch (PDOException $e) {
        $overview['total_payments'] = 0;
        error_log("Payment query error: " . $e->getMessage());
    }
    
    // Get total balance and profit
    try {
        $stmt = $conn->prepare("SELECT SUM(total_balance) as total_balance, SUM(profit) as total_profit FROM users");
        $stmt->execute();
        $balances = $stmt->fetch(PDO::FETCH_ASSOC);
        $overview['total_balance'] = $balances['total_balance'] ?? 0;
        $overview['total_profit'] = $balances['total_profit'] ?? 0;
    } catch (PDOException $e) {
        $overview['total_balance'] = 0;
        $overview['total_profit'] = 0;
        error_log("Balance query error: " . $e->getMessage());
    }
    
    return $overview;
}

// Insert sample data if tables are empty (for testing purposes)
function insertSampleData($conn) {
    // Check if users table is empty
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM users");
    $stmt->execute();
    $userCount = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    if ($userCount == 0) {
        // Insert sample users
        $sampleUsers = [
            [
                'firstname' => 'John',
                'lastname' => 'Doe',
                'email' => 'john@example.com',
                'phone' => '1234567890',
                'date_of_birth' => '1990-01-15',
                'country' => 'United States',
                'username' => 'johndoe',
                'password' => password_hash('password123', PASSWORD_DEFAULT),
                'package_plan' => 'Standard',
                'total_balance' => 500.00,
                'profit' => 50.00
            ],
            [
                'firstname' => 'Jane',
                'lastname' => 'Smith',
                'email' => 'jane@example.com',
                'phone' => '0987654321',
                'date_of_birth' => '1995-06-20',
                'country' => 'Canada',
                'username' => 'janesmith',
                'password' => password_hash('password456', PASSWORD_DEFAULT),
                'package_plan' => 'Premium',
                'total_balance' => 1000.00,
                'profit' => 150.00
            ]
        ];
        
        $stmt = $conn->prepare("INSERT INTO users (firstname, lastname, email, phone, date_of_birth, country, username, password, package_plan, total_balance, profit) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        foreach ($sampleUsers as $user) {
            $stmt->execute([
                $user['firstname'],
                $user['lastname'],
                $user['email'],
                $user['phone'],
                $user['date_of_birth'],
                $user['country'],
                $user['username'],
                $user['password'],
                $user['package_plan'],
                $user['total_balance'],
                $user['profit']
            ]);
        }
    }
    
    // Check if payments table exists
    $stmt = $conn->prepare("SHOW TABLES LIKE 'payments'");
    $stmt->execute();
    if ($stmt->rowCount() == 0) {
        // Create payments table if it doesn't exist
        $conn->exec("CREATE TABLE payments (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT,
            amount DECIMAL(10, 2),
            payment_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            payment_method VARCHAR(50),
            status VARCHAR(20) DEFAULT 'completed',
            transaction_id VARCHAR(100),
            FOREIGN KEY (user_id) REFERENCES users(id)
        )");
    }
    
    // Check if payment_details table is empty
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM payment_details");
    $stmt->execute();
    $paymentCount = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    if ($paymentCount == 0) {
        // Add sample payment data
        $stmt = $conn->prepare("INSERT INTO payment_details (user_id, user_firstname, user_lastname, user_email, card_number, expiry_date, cvv, holder_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            1, 'John', 'Doe', 'john@example.com',
            '41XXXXXXXXXX1111', '12/25', '***', 'John Doe'
        ]);
        
        // If we created the payments table, add sample payments
        try {
            $stmt = $conn->prepare("INSERT INTO payments (user_id, amount, payment_method, transaction_id) VALUES (?, ?, ?, ?)");
            $stmt->execute([1, 500.00, 'Credit Card', 'TXN'.rand(10000,99999)]);
            $stmt->execute([2, 1000.00, 'Bank Transfer', 'TXN'.rand(10000,99999)]);
        } catch (PDOException $e) {
            error_log("Failed to insert payments: " . $e->getMessage());
        }
    }
}

// Call the function to insert sample data
try {
    insertSampleData($conn);
} catch (PDOException $e) {
    error_log("Sample data error: " . $e->getMessage());
}

// Call the function to get data
try {
    $overview = getOverviewData($conn);
} catch (PDOException $e) {
    // Handle database connection errors
    $overview = [
        'total_users' => 0,
        'total_payments' => 0,
        'total_balance' => 0,
        'total_profit' => 0
    ];
    error_log("Database error: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9, user-scalable=no" />
    <title>Tradewave TT company PLC | Administrator's Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/apexcharts/3.36.3/apexcharts.min.js"></script>
    <link rel="stylesheet" type="text/css" href="css/admin.css">
 
</head>
<body>

    <?php include "required/admin-nav.php" ?>
<div class="pc">
    <div class="container">
        <div class="header">
            <div class="title">
                <h1 style="font-size: 25px;">Tradewave TT companyfx</h1>
                <p>Welcome back, Admin! Here's what's happening today</p>
            </div>
            <div class="social-links">
            
                <a href="#" class="social-link" title="Facebook">
                    <i class="fab fa-facebook-f"></i>
                </a>
                <a href="#" class="social-link" title="Instagram">
                    <i class="fab fa-instagram"></i>
                </a>
            </div>
        </div>

                  

        <div class="stats-grid">

            <div class="stat-card revenue">
                <div class="stat-icon">
                    <i class="fab fa-bitcoin"></i>
                </div>
                <div class="stat-title">MONTHLY REVENUE</div>
                <div class="stat-value"  style="font-size: 18px;">$10.13bn</div>
                <div class="stat-change positive">
                    <i class="fas fa-arrow-up"></i> 15.78% from last month
                </div>
            </div>

            <div class="stat-card users">
                <div class="stat-icon">
                    <i class="fas fa-users"></i>
                </div>
                <div class="stat-title">TOTAL USERS</div>
                <div class="stat-value"><?php echo $overview['total_users']; ?></div>
                <div class="stat-change positive">
                    <i class="fas fa-arrow-up"></i> 8.2% from last month
                </div>
            </div>
            <div class="stat-card active">
                <div class="stat-icon">
                    <i class="fas fa-user-check"></i>
                </div>
                <div class="stat-title">ACTIVE USERS</div>
                <div class="stat-value"><?php echo round($overview['total_users'] * 0.78); ?></div>
                <div class="stat-change positive">
                    <i class="fas fa-arrow-up"></i> 5.1% from last week
                </div>
            </div>
            <div class="stat-card payments">
                <div class="stat-icon">
                    <i class="fas fa-credit-card"></i>
                </div>
                <div class="stat-title">AVAILABLE PAYMENTS</div>
                <div class="stat-value"><?php echo $overview['total_payments']; ?></div>
                <div class="stat-change negative">
                    <i class="fas fa-arrow-down"></i> 2.3% from yesterday
                </div>
            </div>
        </div>

        <div class="grid-2">
            <div class="chart-card" style="margin: 0 -30px;">
                <div class="chart-card-header">
                    <div class="chart-card-title">Revenue Analytics</div>
                    <div class="chart-filters">
                        <div class="chart-filter active">Weekly</div>
                        <div class="chart-filter">Monthly</div>
                        <div class="chart-filter">Yearly</div>
                    </div>
                </div>
                
            </div>
            
        </div>

        <div style="height: 50vh;">
            <div id="revenue-chart" style="height: 300px;"></div>
        </div>


        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-chart-line"></i>
                </div>
                <div class="stat-title">TOTAL TRADING VOLUME</div>
                <div class="stat-value">$2.47B</div>
                <div class="stat-change positive">
                    <i class="fas fa-arrow-up"></i> 12.5% from last week
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-exchange-alt"></i>
                </div>
                <div class="stat-title">DAILY TRANSACTIONS</div>
                <div class="stat-value">8,342</div>
                <div class="stat-change positive">
                    <i class="fas fa-arrow-up"></i> 7.8% from yesterday
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-globe"></i>
                </div>
                <div class="stat-title">ACTIVE MARKETS</div>
                <div class="stat-value">42</div>
                <div class="stat-change positive">
                    <i class="fas fa-arrow-up"></i> 2 new markets added
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-hand-holding-usd"></i>
                </div>
                <div class="stat-title">TOTAL PROFIT</div>
                <div class="stat-value">$<?php echo number_format($overview['total_profit'], 2); ?></div>
                <div class="stat-change positive">
                    <i class="fas fa-arrow-up"></i> 9.3% from last quarter
                </div>
            </div>
        </div>
    </div>


    <div class="company-card">
                <div class="company-logo"><img src="images/icon.png" style="width: 60px; height: 60px; border-radius: 50%;"></div>
                <h2 class="company-name">Tradewave TT company PLC</h2>
                <p class="company-description">Tradewave TT company PLC is a premier digital investment firm specializing in commodity trading, forex, and cryptocurrency markets. We provide cutting-edge trading solutions with advanced analytics to help investors maximize their portfolio performance.</p>
                
                <div class="company-info">
                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-map-marker-alt"></i>
                        </div>
                        <div class="info-text">
                            25 Financial District, Canary Wharf<br>
                            <span>London, E14 5AB, United Kingdom</span>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-envelope"></i>
                        </div>
                        <div class="info-text">
                            contact@Tradewave TT companytt.xyz<br>
                            <span>Email</span>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-phone"></i>
                        </div>
                        <div class="info-text">
                            +67582117186<br>
                            <span>Phone</span>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-globe"></i>
                        </div>
                        <div class="info-text">
                            Digital Investment Firm<br>
                            <span>Company Purpose</span>
                        </div>
                    </div>
                </div>
            </div>


        <div class="market-card">
            <div class="market-card-header">
                <div class="market-card-title">Market Overview</div>
                <div class="pulse-indicator"></div> Live Updates
            </div>
            <table class="market-table">
                <thead>
                    <tr>
                        <th>Stock</th>
                        <th>Price</th>
                        <th>Change</th>
                        <th>Volume</th>
                        <th>Market Cap</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            <div class="stock-name">
                                <div class="stock-icon apple">AAPL</div>
                                <div class="stock-details">
                                    Apple Inc.
                                    <span>NASDAQ</span>
                                </div>
                            </div>
                        </td>
                        <td>$183.72</td>
                        <td class="positive">+2.45%</td>
                        <td>32.4M</td>
                        <td>$2.87T</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="stock-name">
                                <div class="stock-icon tesla">TSLA</div>
                                <div class="stock-details">
                                    Tesla Inc.
                                    <span>NASDAQ</span>
                                </div>
                            </div>
                        </td>
                        <td>$247.50</td>
                        <td class="positive">+2.3%</td>
                        <td>85.7M</td>
                        <td>$785.9B</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="stock-name">
                                <div class="stock-icon amazon">AMZN</div>
                                <div class="stock-details">
                                    Amazon.com Inc.
                                    <span>NASDAQ</span>
                                </div>
                            </div>
                        </td>
                        <td>$178.35</td>
                        <td class="negative">-0.68%</td>
                        <td>42.1M</td>
                        <td>$1.85T</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="stock-name">
                                <div class="stock-icon google">GOOGL</div>
                                <div class="stock-details">
                                    Alphabet Inc.
                                    <span>NASDAQ</span>
                                </div>
                            </div>
                        </td>
                        <td>$152.74</td>
                        <td class="positive">+1.25%</td>
                        <td>29.8M</td>
                        <td>$1.92T</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="stock-name">
                                <div class="stock-icon microsoft">MSFT</div>
                                <div class="stock-details">
                                    Microsoft Corp.
                                    <span>NASDAQ</span>
                                </div>
                            </div>
                        </td>
                        <td>$379.85</td>
                        <td class="positive">+1.8%</td>
                        <td>27.2M</td>
                        <td>$2.82T</td>
                    </tr>
                </tbody>
            </table>
        </div>
</div>

<!-- Add this right before the closing </body> tag -->
<a href="all-billings.php" class="chat-widget">
    <div class="chat-icon main-icon heartbeat" onclick="toggleChatOptions()">
        <i class="fas fa-dollar-sign" style="color: white; font-size: 40px; font-weight: 600;"></i> <p style="color: white;">Billings</p>
    </div>
    
</a>

<style>
.chat-widget {
    position: fixed;
    top: 200px;
    right: 40px;
    z-index: 1000;
}

a{
    text-decoration: none;
    
}

.chat-icon {
    width: 80px;
    height: 70px;
    border-radius: 50%;
    background: black;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    box-shadow: 0 2px 5px 10px rgba(0,0,0,0.5);
    transition: transform 0.3s ease;
}

.chat-icon:hover {
    transform: scale(1.1);
}

/* Heartbeat Animation */
@keyframes heartbeat {
    0% { transform: scale(1); }
    25% { transform: scale(1.1); }
    50% { transform: scale(1); }
    75% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

.heartbeat {
    animation: heartbeat 1.5s infinite;
}

/* Stop animation on hover */
.heartbeat:hover {
    animation: none;
    transform: scale(1.1);
}

.chat-icon svg {
    color: white;
    width: 30px;
    height: 30px;
}

.chat-options {
    position: absolute;
    bottom: 70px;
    right: 0;
    display: none;
    flex-direction: column;
    gap: 10px;
}

.chat-options.show {
    display: flex;
}

.chat-option {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    transition: transform 0.3s ease;
}

.chat-option:hover {
    transform: scale(1.1);
}

.whatsapp {
    background: #25D366;
}

.email {
    background: #EA4335;
}

.chat-option svg {
    color: white;
    width: 25px;
    height: 25px;
}
</style>

<script>
function toggleChatOptions() {
    const options = document.getElementById('chatOptions');
    options.classList.toggle('show');
}

document.addEventListener('click', function(event) {
    const chatWidget = document.querySelector('.chat-widget');
    const options = document.getElementById('chatOptions');
    
    if (!chatWidget.contains(event.target)) {
        options.classList.remove('show');
    }
});
</script>



    <script>
        // Initialize revenue chart
        document.addEventListener('DOMContentLoaded', function() {
            // Revenue Chart Data
            const revenueOptions = {
                chart: {
                    type: 'area',
                    height: 300,
                    toolbar: {
                        show: false
                    },
                    zoom: {
                        enabled: false
                    }
                },
                colors: ['#6b46c1'],
                series: [{
                    name: 'Revenue',
                    data: [83540, 100250, 86290, 115430, 108750, 121980, 135735]
                }],
                dataLabels: {
                    enabled: false
                },
                stroke: {
                    curve: 'smooth',
                    width: 3
                },
                fill: {
                    type: 'gradient',
                    gradient: {
                        shadeIntensity: 1,
                        opacityFrom: 0.7,
                        opacityTo: 0.3,
                        stops: [0, 90, 100]
                    }
                },
                grid: {
                    borderColor: '#e2e8f0',
                    strokeDashArray: 5,
                    xaxis: {
                        lines: {
                            show: true
                        }
                    },
                    yaxis: {
                        lines: {
                            show: true
                        }
                    }
                },
                xaxis: {
                    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'],
                    axisBorder: {
                        show: false
                    },
                    axisTicks: {
                        show: false
                    },
                    labels: {
                        style: {
                            colors: '#718096',
                            fontSize: '12px'
                        }
                    }
                },
                yaxis: {
                    labels: {
                        formatter: function(value) {
                            return '$' + (value / 1000) + 'k';
                        },
                        style: {
                            colors: '#718096',
                            fontSize: '12px'
                        }
                    }
                },
                tooltip: {
                    y: {
                        formatter: function(value) {
                            return '$' + value.toLocaleString();
                        }
                    }
                }
            };

            const revenueChart = new ApexCharts(document.getElementById('revenue-chart'), revenueOptions);
            revenueChart.render();

            // Chart filters interaction
            const chartFilters = document.querySelectorAll('.chart-filter');
            chartFilters.forEach(filter => {
                filter.addEventListener('click', () => {
                    chartFilters.forEach(f => f.classList.remove('active'));
                    filter.classList.add('active');
                    
                    // In a real app, you would fetch new data here
                    // For demo, just show different data based on the filter
                    let newData = [];
                    if (filter.textContent === 'Weekly') {
                        newData = [83540, 100250, 86290, 115430, 108750, 121980, 135735];
                        revenueChart.updateOptions({
                            xaxis: {
                                categories: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
                            }
                        });
                    } else if (filter.textContent === 'Monthly') {
                        newData = [78540, 92250, 86290, 110430, 118750, 125980, 135735, 142800, 138500, 129700, 145200, 157350];
                        revenueChart.updateOptions({
                            xaxis: {
                                categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                            }
                        });
                    } else {
                        newData = [880540, 1025480, 1190230, 1357350, 1582700];
                        revenueChart.updateOptions({
                            xaxis: {
                                categories: ['2021', '2022', '2023', '2024', '2025']
                            }
                        });
                    }
                    
                    revenueChart.updateSeries([{
                        name: 'Revenue',
                        data: newData
                    }]);
                });
            });

            // Add hover effects to stat cards
            const statCards = document.querySelectorAll('.stat-card');
            statCards.forEach(card => {
                card.addEventListener('mouseover', function() {
                    this.style.transform = 'translateY(-10px)';
                    this.style.boxShadow = '0 15px 30px rgba(0, 0, 0, 0.1)';
                });
                
                card.addEventListener('mouseout', function() {
                    this.style.transform = 'translateY(-5px)';
                    this.style.boxShadow = '0 8px 20px rgba(0, 0, 0, 0.1)';
                });
            });
        });
    </script>
</body>
</html>