<?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();
}

// Handle transaction status updates via AJAX
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    try {
        $transaction_id = (int)$_POST['transaction_id'];
        $action = $_POST['action'];
        
        // First, get the transaction details to determine the type and amount
        $stmt = $conn->prepare("SELECT transaction_type, transaction_amount, user_id FROM transactions WHERE id = ?");
        $stmt->execute([$transaction_id]);
        $transaction = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$transaction) {
            throw new Exception('Transaction not found');
        }
        
        $transaction_type = $transaction['transaction_type'];
        $transaction_amount = $transaction['transaction_amount'];
        $user_id = $transaction['user_id'];
        
        if ($action === 'approve') {
            $new_status = 'successful';
            
            // If approving a DEPOSIT, ADD to user's balance
            if ($transaction_type === 'deposit') {
                $update_balance_stmt = $conn->prepare("UPDATE users SET total_balance = total_balance + ? WHERE id = ?");
                $update_balance_stmt->execute([$transaction_amount, $user_id]);
            }
            // If approving a WITHDRAWAL, do NOT touch the balance (just change status)
            
        } elseif ($action === 'decline') {
            $new_status = 'failed';
            
            // If declining a WITHDRAWAL, ADD the amount back to user's balance
            if ($transaction_type === 'withdrawal') {
                $update_balance_stmt = $conn->prepare("UPDATE users SET total_balance = total_balance + ? WHERE id = ?");
                $update_balance_stmt->execute([$transaction_amount, $user_id]);
            }
            // If declining a DEPOSIT, do NOT touch the balance (nothing happens)
            
        } else {
            throw new Exception('Invalid action');
        }
        
        // Update the transaction status
        $stmt = $conn->prepare("UPDATE transactions SET transaction_status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
        $stmt->execute([$new_status, $transaction_id]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Transaction status updated successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Transaction not found']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit();
}

// Fetch all transactions with user information
try {
    $stmt = $conn->prepare("
        SELECT t.*, u.firstname, u.lastname, u.email 
        FROM transactions t 
        LEFT JOIN users u ON t.user_id = u.id 
        ORDER BY t.created_at DESC
    ");
    $stmt->execute();
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error_message = "Error fetching transactions: " . $e->getMessage();
    $transactions = [];
}

// Get transaction statistics
try {
    $stats_stmt = $conn->prepare("
        SELECT 
            COUNT(*) as total_transactions,
            SUM(CASE WHEN transaction_status = 'pending' THEN 1 ELSE 0 END) as pending_count,
            SUM(CASE WHEN transaction_status = 'successful' THEN 1 ELSE 0 END) as successful_count,
            SUM(CASE WHEN transaction_status = 'failed' THEN 1 ELSE 0 END) as failed_count,
            SUM(CASE WHEN transaction_status = 'successful' THEN transaction_amount ELSE 0 END) as total_successful_amount
        FROM transactions
    ");
    $stats_stmt->execute();
    $stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $stats = ['total_transactions' => 0, 'pending_count' => 0, 'successful_count' => 0, 'failed_count' => 0, 'total_successful_amount' => 0];
}
?>

<!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>Transaction Authorization - Admin Panel</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="css/transactions.css">
    <link rel="stylesheet" type="text/css" href="css/admin.css">

</head>
<body>
    <div class="loading" id="loading">
        <div class="loading-spinner"></div>
    </div>

    <?php include "required/admin-nav.php" ?>

    <div class="pc" style="padding: 20px;">
        <div class="headder">
            <div class="header-top">
                <div class="header-title">
                    <i class="fas fa-check-circle"></i>
                    <h1>Transaction Authorization</h1>
                </div>
                <a href="logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i>
                    Logout
                </a>
            </div>

            <div class="statss-grid">
                <div class="statss-cardd total">
                    <i class="fas fa-chart-line"></i>
                    <div>
                         <div class="statss-number"><?php echo number_format($stats['total_transactions']); ?></div>
                         <div class="statss-label">Total Transactions</div>
                    </div>
                </div>

                <div class="statss-cardd pending">
                    <i class="fas fa-clock"></i>

                    <div>
                    <div class="statss-number"><?php echo number_format($stats['pending_count']); ?></div>
                    <div class="statss-label">Pending</div>
                    </div>
                </div>

                <div class="statss-cardd successful">
                    <i class="fas fa-check"></i>

                    <div>
                    <div class="statss-number"><?php echo number_format($stats['successful_count']); ?></div>
                    <div class="statss-label">Successful</div>
                   </div>
                </div>

                <div class="statss-cardd failed">
                    <i class="fas fa-times"></i>

                    <div>
                    <div class="statss-number"><?php echo number_format($stats['failed_count']); ?></div>
                    <div class="statss-label">Failed</div>
                    </div>

                </div>
            </div>
        </div>

        <div class="transactions-container">
            <div class="transactions-header">
                <h2 class="transactions-title">All Transactions</h2>
                <div class="filter-buttons">
                    <button class="filter-btn active" onclick="filterTransactions('all')">All</button>
                    <button class="filter-btn" onclick="filterTransactions('pending')">Pending</button>
                    <button class="filter-btn" onclick="filterTransactions('successful')">Successful</button>
                    <button class="filter-btn" onclick="filterTransactions('failed')">Failed</button>
                </div>
            </div>

            <div class="table-wrapper">
                <table class="transactions-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>User</th>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>Method</th>
                            <th>Reference</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="transactionsTableBody">
                        <?php foreach ($transactions as $transaction): ?>
                        <tr class="transaction-row" data-status="<?php echo $transaction['transaction_status']; ?>">
                            <td><?php echo htmlspecialchars($transaction['id']); ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($transaction['user_name']); ?></strong><br>
                                <small><?php echo htmlspecialchars($transaction['email'] ?? 'N/A'); ?></small>
                            </td>
                            <td>
                                <div class="transaction-type">
                                    <span class="type-icon type-<?php echo str_replace([' ', '_'], '-', $transaction['transaction_type']); ?>">
                                        <i class="fas fa-<?php 
                                            echo match($transaction['transaction_type']) {
                                                'deposit' => 'plus',
                                                'withdrawal' => 'minus',
                                                'transfer money' => 'exchange-alt',
                                                'link wallet' => 'link',
                                                'money received' => 'arrow-down',
                                                default => 'dollar-sign'
                                            };
                                        ?>"></i>
                                    </span>
                                    <?php echo ucfirst(str_replace('_', ' ', $transaction['transaction_type'])); ?>
                                </div>
                            </td>
                            <td class="amount">
                                <?php echo $transaction['currency']; ?> <?php echo number_format($transaction['transaction_amount'], 2); ?>
                            </td>
                            <td><?php echo htmlspecialchars($transaction['transaction_method'] ?? 'N/A'); ?></td>
                            <td>
                                <small><?php echo htmlspecialchars($transaction['reference_number']); ?></small>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $transaction['transaction_status']; ?>">
                                    <?php echo ucfirst($transaction['transaction_status']); ?>
                                </span>
                            </td>
                            <td>
                                <?php echo date('M d, Y H:i', strtotime($transaction['transaction_date'])); ?>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <?php if ($transaction['transaction_status'] === 'pending'): ?>
                                        <button class="action-btn approve-btn" onclick="updateTransactionStatus(<?php echo $transaction['id']; ?>, 'approve')">
                                            <i class="fas fa-check"></i> Approve
                                        </button>
                                        <button class="action-btn decline-btn" onclick="updateTransactionStatus(<?php echo $transaction['id']; ?>, 'decline')">
                                            <i class="fas fa-times"></i> Decline
                                        </button>
                                    <?php else: ?>
                                        <span class="status-badge status-<?php echo $transaction['transaction_status']; ?>">
                                            <?php echo ucfirst($transaction['transaction_status']); ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        function showLoading() {
            document.getElementById('loading').style.display = 'flex';
        }

        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
        }

        function showNotification(message, type = 'success') {
            const notification = document.createElement('div');
            notification.className = `notification ${type}`;
            notification.textContent = message;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.classList.add('show');
            }, 100);
            
            setTimeout(() => {
                notification.classList.remove('show');
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 300);
            }, 3000);
        }

        async function updateTransactionStatus(transactionId, action) {
            showLoading();
            
            try {
                const formData = new FormData();
                formData.append('transaction_id', transactionId);
                formData.append('action', action);
                
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showNotification(result.message, 'success');
                    // Reload the page to reflect changes
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    showNotification(result.message, 'error');
                }
            } catch (error) {
                showNotification('An error occurred while updating the transaction', 'error');
                console.error('Error:', error);
            } finally {
                hideLoading();
            }
        }

        function filterTransactions(status) {
            const rows = document.querySelectorAll('.transaction-row');
            const buttons = document.querySelectorAll('.filter-btn');
            
            // Update active button
            buttons.forEach(btn => btn.classList.remove('active'));
            event.target.classList.add('active');
            
            // Filter rows
            rows.forEach(row => {
                if (status === 'all' || row.dataset.status === status) {
                    row.style.display = '';
                    setTimeout(() => {
                        row.style.opacity = '1';
                        row.style.transform = 'scale(1)';
                    }, 50);
                } else {
                    row.style.opacity = '0';
                    row.style.transform = 'scale(0.95)';
                    setTimeout(() => {
                        row.style.display = 'none';
                    }, 300);
                }
            });
        }

        // Add hover effects and animations
        document.addEventListener('DOMContentLoaded', function() {
            const rows = document.querySelectorAll('.transaction-row');
            
            rows.forEach(row => {
                row.addEventListener('mouseenter', function() {
                    this.style.transform = 'scale(1.02)';
                    this.style.zIndex = '5';
                });
                
                row.addEventListener('mouseleave', function() {
                    this.style.transform = 'scale(1)';
                    this.style.zIndex = '1';
                });
            });
        });
    </script>
</body>
</html>