<?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
    $stmt = $conn->prepare("SELECT COUNT(*) as total FROM payments");
    $stmt->execute();
    $overview['total_payments'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Get total balance and profit
    $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;
    
    return $overview;
}

// Handle AJAX requests
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    $response = ['success' => false];
    
    try {
        switch ($_POST['action']) {
            case 'get_table_data':
                $table = $_POST['table'];
                $allowed_tables = ['users', 'admin', 'payments'];
                
                if (!in_array($table, $allowed_tables)) {
                    throw new Exception('Invalid table');
                }
                
                $stmt = $conn->prepare("SELECT * FROM $table");
                $stmt->execute();
                $response['data'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $response['success'] = true;
                break;
                
            case 'update_record':
                $table = $_POST['table'];
                $id = $_POST['id'];
                $field = $_POST['field'];
                $value = $_POST['value'];
                
                $stmt = $conn->prepare("UPDATE $table SET $field = ? WHERE id = ?");
                $stmt->execute([$value, $id]);
                $response['success'] = true;
                break;

            case 'get_payment_proofs':
                $stmt = $conn->prepare("SELECT id, id_photo FROM users WHERE id_photo IS NOT NULL");
                $stmt->execute();
                $response['data'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $response['success'] = true;
                break;

            case 'delete_payment_proof':
                $id = $_POST['id'];
                $stmt = $conn->prepare("SELECT id_photo FROM users WHERE id = ?");
                $stmt->execute([$id]);
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($result && $result['id_photo']) {
                    $file_path = 'uploads/' . $result['id_photo'];
                    if (file_exists($file_path)) {
                        unlink($file_path);
                    }
                    
                    $stmt = $conn->prepare("UPDATE users SET id_photo = NULL WHERE id = ?");
                    $stmt->execute([$id]);
                    $response['success'] = true;
                }
                break;
        }
    } catch (Exception $e) {
        $response['error'] = $e->getMessage();
    }
    
    echo json_encode($response);
    exit();
}

$overview = getOverviewData($conn);
?>

<!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" />
    <meta name="robots" content="noindex, nofollow">
<link rel="shortcut icon" type="image/png" href="images/icon.png" />
    <title>Admin Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        /* Previous CSS styles remain unchanged */
        
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #34495e;
            --accent-color: #3498db;
            --text-color: #ecf0f1;
            --danger-color: #e74c3c;
            --success-color: #2ecc71;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            background-color: #f5f6fa;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: var(--primary-color);
            padding: 20px;
            color: var(--text-color);
        }

        .main-content {
            flex: 1;
            padding: 20px;
            overflow-x: auto;
        }

        .logo {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 30px;
            text-align: center;
        }

        .nav-button {
            display: block;
            width: 100%;
            padding: 12px 15px;
            margin-bottom: 10px;
            background-color: var(--secondary-color);
            color: var(--text-color);
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
            text-align: left;
        }

        .nav-button:hover {
            background-color: var(--accent-color);
        }

        .nav-button i {
            margin-right: 10px;
        }

        .overview-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .card h3 {
            color: var(--primary-color);
            margin-bottom: 10px;
        }

        .table-container {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: var(--primary-color);
            color: var(--text-color);
        }

        tr:hover {
            background-color: #f5f5f5;
        }

        .editable {
            cursor: pointer;
        }

        .editable:hover {
            background-color: #e3f2fd;
        }

        .edit-input {
            width: 100%;
            padding: 5px;
            border: 1px solid var(--accent-color);
            border-radius: 3px;
        }

        .loading {
            text-align: center;
            padding: 20px;
        }

        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
            }
        }
        .logout-button {
            display: block;
            width: 100%;
            padding: 12px 15px;
            margin-top: 20px;
            background-color: var(--danger-color);
            color: var(--text-color);
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
            text-align: left;
        }

        .logout-button:hover {
            background-color: #c0392b;
        }

        .logout-button i {
            margin-right: 10px;
        }
        .payment-proof-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
    padding: 20px;
}

.payment-proof-card {
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    overflow: hidden;
}

.payment-proof-card img {
    width: 100%;
    height: 200px;
    object-fit: cover;
}

.payment-proof-actions {
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.delete-proof-btn {
    background-color: var(--danger-color);
    color: white;
    border: none;
    padding: 5px 10px;
    border-radius: 3px;
    cursor: pointer;
}

.delete-proof-btn:hover {
    background-color: #c0392b;
}

a {
    text-decoration: none;
    font-weight: 600;
    color: blue;
}

    </style>
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <div class="logo">
                <i class="fas fa-chart-line"></i> Admin Dashboard
            </div>
            <button class="nav-button" data-table="overview">
                <i class="fas fa-home"></i> Overview
            </button>
            <button class="nav-button" data-table="users">
                <i class="fas fa-users"></i> Users
            </button>
            <button class="nav-button" data-table="payment_proofs">
                <i class="fas fa-images"></i> No Data
            </button>
            <button class="nav-button" data-table="payments">
                <i class="fas fa-credit-card"></i> Payments
            </button>
            <button class="nav-button" data-table="admin">
                <i class="fas fa-user-shield"></i> Admins
            </button>
            <a class="nav-button" href="uploaded-adm.php" style="text-decoration: none; font-weight: 600;"><i class="fas fa-images"></i> View payment proof</a>
            <a href="?action=logout" class="logout-button" style="text-decoration: none; font-weight: 600;">
                <i class="fas fa-sign-out-alt"></i> Logout
            </a>
        </div>

        <div class="main-content">
            <div id="overview-section" class="overview-cards">
                <div class="card">
                    <h3>Total Users</h3>
                    <p><?php echo $overview['total_users']; ?></p>
                </div>
                
                <div class="card">
                    <h3>Total Balance</h3>
                    <p><?php echo number_format($overview['total_balance'], 2); ?> USD</p>
                </div>
                
                <div class="card">
                    <div class="company-info bg-gray-800 rounded-lg p-6 shadow-lg">
    <h2 class="text-xl font-bold mb-4 text-white">Company Information</h2>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div class="space-y-3">
            <div style="display: flex; justify-content: space-between; padding: 10px 20px; border-radius: 15px; background: #e0e0e0; margin-bottom: 10px;">
                <span class="font-semibold text-gray-300">Name:</span>
                <span class="text-white">Tradewave</span>
            </div>
            <div style="display: flex; justify-content: space-between; padding: 10px 20px; border-radius: 15px; background: #e0e0e0; margin-bottom: 10px;">
                <span class="font-semibold text-gray-300">Web:</span>
                <a href="https://finance.tradewavefx.xyz" class="text-blue-400 hover:text-blue-300 hover:underline" target="_blank">https://finance.tradewavefx.xyz</a>
            </div>
            <div style="display: flex; justify-content: space-between; padding: 10px 20px; border-radius: 15px; background: #e0e0e0; margin-bottom: 10px;">
                <span class="font-semibold text-gray-300">Email:</span>
                <a href="mailto:support@tradewavefx.xyz" class="text-blue-400 hover:text-blue-300 hover:underline">support@tradewavefx.xyz</a>
            </div>
            <div style="display: flex; justify-content: space-between; padding: 10px 20px; border-radius: 15px; background: #e0e0e0; margin-bottom: 10px;">
                <span class="font-semibold text-gray-300">Phone:</span>
                <span class="text-white">+67582117186</span>
            </div>
        </div>
        <div class="space-y-3">
            
            <div style="display: flex; justify-content: space-between; padding: 10px 20px; border-radius: 15px; background: #e0e0e0; margin-bottom: 10px;">
                <span class="font-semibold text-gray-300">WhatsApp:</span>
                <a href="https://wa.link/6na04q" class="text-blue-400 hover:text-blue-300 hover:underline" target="_blank">Connect on WhatsApp</a>
            </div>
            <div style="display: flex; justify-content: space-between; padding: 10px 20px; border-radius: 15px; background: #e0e0e0; margin-bottom: 10px;">
                <span class="font-semibold text-gray-300">Facebook:</span>
                <a href="https://www.facebook.com/share/z9umbxrsSMNhFpah/?mibextid=LQQj4d" class="text-blue-400 hover:text-blue-300 hover:underline" target="_blank">Visit Facebook Page</a>
            </div>
            <div style="display: flex; justify-content: space-between; padding: 10px 20px; border-radius: 15px; background: #e0e0e0; margin-bottom: 10px;">
                <span class="font-semibold text-gray-300">Address:</span>
                <span class="text-white">Tradewave capital plc, 7 Bell Yard, London, WC2A 2JR, United Kingdom.</span>
            </div>
        </div>
    </div>
</div>
                </div>
            </div>

            <div id="table-section" class="table-container">
                <!-- Table content will be loaded here -->
            </div>
        </div>
    </div>

    <script>
document.addEventListener('DOMContentLoaded', function() {
    const tableSection = document.getElementById('table-section');
    const overviewSection = document.getElementById('overview-section');
    
    // Handle navigation
    document.querySelectorAll('.nav-button').forEach(button => {
        button.addEventListener('click', function() {
            const table = this.dataset.table;
            
            if (table === 'overview') {
                overviewSection.style.display = 'grid';
                tableSection.style.display = 'none';
            } else if (table === 'payment_proofs') {
                overviewSection.style.display = 'none';
                tableSection.style.display = 'block';
                loadPaymentProofs();
            } else {
                overviewSection.style.display = 'none';
                tableSection.style.display = 'block';
                loadTableData(table);
            }
        });
    });
    
    // Load table data
    function loadTableData(table) {
        tableSection.innerHTML = '<div class="loading">Loading...</div>';
        
        fetch('', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=get_table_data&table=${table}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data.length > 0) {
                const columns = Object.keys(data.data[0]);
                let html = `<table>
                    <thead>
                        <tr>
                            ${columns.map(col => `<th>${col}</th>`).join('')}
                        </tr>
                    </thead>
                    <tbody>`;
                
                data.data.forEach(row => {
                    html += '<tr>';
                    columns.forEach(col => {
                        if (col === 'id' || col === 'password' || col === 'profile_photo' || col === 'payment_proof') {
                            html += `<td>${row[col]}</td>`;
                        } else {
                            html += `<td class="editable" data-table="${table}" data-id="${row.id}" data-field="${col}">${row[col]}</td>`;
                        }
                    });
                    html += '</tr>';
                });
                
                html += '</tbody></table>';
                tableSection.innerHTML = html;
                
                // Add click handlers for editable cells
                document.querySelectorAll('.editable').forEach(cell => {
                    cell.addEventListener('click', makeEditable);
                });
            } else {
                tableSection.innerHTML = '<p>No data available</p>';
            }
        })
        .catch(error => {
            tableSection.innerHTML = '<p>Error loading data</p>';
        });
    }
    
    // Make cells editable
    function makeEditable(e) {
        const cell = e.target;
        const currentValue = cell.textContent;
        
        const input = document.createElement('input');
        input.type = 'text';
        input.value = currentValue;
        input.className = 'edit-input';
        
        cell.textContent = '';
        cell.appendChild(input);
        input.focus();
        
        input.addEventListener('blur', function() {
            updateValue(cell, input.value);
        });
        
        input.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                updateValue(cell, input.value);
            }
        });
    }
    
    // Update value
    function updateValue(cell, newValue) {
        const table = cell.dataset.table;
        const id = cell.dataset.id;
        const field = cell.dataset.field;
        
        fetch('', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=update_record&table=${table}&id=${id}&field=${field}&value=${encodeURIComponent(newValue)}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                cell.textContent = newValue;
            } else {
                cell.textContent = cell.dataset.originalValue;
                alert('Error updating value');
            }
        })
        .catch(error => {
            cell.textContent = cell.dataset.originalValue;
            alert('Error updating value');
        });
    }
    
    // Load payment proofs
    function loadPaymentProofs() {
        tableSection.innerHTML = '<div class="loading">Loading...</div>';
        
        fetch('', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=get_payment_proofs'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data.length > 0) {
                let html = '<div class="payment-proof-grid">';
                
                data.data.forEach(item => {
                    html += `
                        <div class="payment-proof-card">
                            <img src="uploads/${item.id_photo}" alt="Payment Proof">
                            <div class="payment-proof-actions">
                                <span>ID: ${item.id}</span>
                                <button class="delete-proof-btn" data-id="${item.id}">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            </div>
                        </div>
                    `;
                });
                
                html += '</div>';
                tableSection.innerHTML = html;
                
                // Add click handlers for delete buttons
                document.querySelectorAll('.delete-proof-btn').forEach(button => {
                    button.addEventListener('click', deletePaymentProof);
                });
            } else {
                tableSection.innerHTML = '<p>No payment proofs available</p>';
            }
        })
        .catch(error => {
            tableSection.innerHTML = '<p>Error loading payment proofs</p>';
        });
    }
    
    // Delete payment proof
    function deletePaymentProof(e) {
        if (!confirm('Are you sure you want to delete this payment proof?')) {
            return;
        }
        
        const id = e.target.closest('.delete-proof-btn').dataset.id;
        
        fetch('', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `action=delete_payment_proof&id=${id}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadPaymentProofs();
            } else {
                alert('Error deleting payment proof');
            }
        })
        .catch(error => {
            alert('Error deleting payment proof');
        });
    }
    
    // Initialize dashboard with overview
    document.querySelector('[data-table="overview"]').click();
});
    </script>
</body>
</html>