<?php
session_start();
require_once 'config/database.php';
require_once __DIR__ . '/lib/EmailService.php';
require_once __DIR__ . '/lib/EmailTemplates.php';
use TrustBnk\Admin\Lib\EmailService;
use TrustBnk\Admin\Lib\EmailTemplates;

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$database = new Database();
$conn = $database->getConnection();

// Handle transaction status updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $transaction_id = $_POST['transaction_id'];
    
    if ($_POST['action'] === 'update_status') {
        $new_status = $_POST['status'];
        $stmt = $conn->prepare("UPDATE transactions SET status = ? WHERE id = ?");
        $stmt->execute([$new_status, $transaction_id]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "Transaction status updated successfully!";

            // Send alert if completed
            if ($new_status === 'Completed') {
                $txStmt = $conn->prepare("SELECT t.*, u.firstname, u.lastname, u.email, u.balance, u.account_number FROM transactions t LEFT JOIN users u ON t.user_id = u.id WHERE t.id = ?");
                $txStmt->execute([$transaction_id]);
                $tx = $txStmt->fetch();
                if ($tx && !empty($tx['email'])) {
                    $general = $conn->query("SELECT * FROM general_settings WHERE id = 1")->fetch() ?: ['site_name' => 'TrustBank', 'logo_path' => null];
                    $direction = (strtolower($tx['transaction_type']) === 'deposit') ? 'credit' : 'debit';
                    $available = (float)($tx['balance'] ?? 0);
                    [$subject, $html] = EmailTemplates::transactionAlert(
                        $general,
                        $tx,
                        $direction,
                        (float)$tx['amount'],
                        (string)$tx['reference_number'],
                        (string)($tx['description'] ?? ''),
                        date('Y-m-d H:i', strtotime($tx['created_at'])),
                        $available
                    );
                    $emailService = new EmailService($conn);
                    $emailService->sendEmail($tx['email'], trim(($tx['firstname'] ?? '') . ' ' . ($tx['lastname'] ?? '')), $subject, $html, 'Transaction Alert', (int)$tx['user_id'], (int)($_SESSION['admin_id'] ?? 0));
                }
            }
        } else {
            $error_message = "Failed to update transaction status.";
        }
    } elseif ($_POST['action'] === 'delete_transaction') {
        $stmt = $conn->prepare("DELETE FROM transactions WHERE id = ?");
        $stmt->execute([$transaction_id]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "Transaction deleted successfully!";
        } else {
            $error_message = "Failed to delete transaction.";
        }
    }
}

// Get search and filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$type_filter = isset($_GET['type']) ? $_GET['type'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Build query with filters
$where_conditions = [];
$params = [];

if (!empty($search)) {
    $where_conditions[] = "(u.account_number LIKE ? OR u.username LIKE ? OR reference_number LIKE ? OR description LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
}

if (!empty($status_filter)) {
    $where_conditions[] = "status = ?";
    $params[] = $status_filter;
}

if (!empty($type_filter)) {
    $where_conditions[] = "transaction_type = ?";
    $params[] = $type_filter;
}

if (!empty($date_from)) {
    $where_conditions[] = "created_at >= ?";
    $params[] = $date_from . ' 00:00:00';
}

if (!empty($date_to)) {
    $where_conditions[] = "created_at <= ?";
    $params[] = $date_to . ' 23:59:59';
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total count for pagination
$count_sql = "SELECT COUNT(*) as total FROM transactions $where_clause";
$stmt = $conn->prepare($count_sql);
$stmt->execute($params);
$total_transactions = $stmt->fetch()['total'];
$total_pages = ceil($total_transactions / $per_page);

// Get transactions with pagination
$sql = "SELECT t.*, 
               u.firstname, u.lastname, u.account_number, u.username
        FROM transactions t
        LEFT JOIN users u ON t.user_id = u.id
        $where_clause 
        ORDER BY t.created_at DESC LIMIT $per_page OFFSET $offset";

$stmt = $conn->prepare($sql);
$stmt->execute($params);
$transactions = $stmt->fetchAll();

// Get unique statuses for filters
$statuses = $conn->query("SELECT DISTINCT status FROM transactions ORDER BY status")->fetchAll();

// Get transaction statistics
$stats_sql = "SELECT 
    COUNT(*) as total_transactions,
    SUM(CASE WHEN status = 'Completed' THEN 1 ELSE 0 END) as completed,
    SUM(CASE WHEN status = 'Pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'Failed' THEN 1 ELSE 0 END) as failed,
    SUM(CASE WHEN status = 'Completed' THEN amount ELSE 0 END) as total_amount
FROM transactions";
$stats_stmt = $conn->query($stats_sql);
$stats = $stats_stmt->fetch();

$database->closeConnection();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TrustBeam Credit - Manage Transactions</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>
    <div class="admin-container">
        <!-- Header -->
        <header class="admin-header">
            <div class="header-left">
                <h1 class="logo">TrustBeam Credit</h1>
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="search-bar">
                    <i class="fas fa-search"></i>
                    <input type="text" placeholder="Search transactions...">
                </div>
            </div>
            <div class="header-right">
                <div class="admin-profile">
                    <span>Welcome, <?php echo htmlspecialchars($_SESSION['admin_username']); ?></span>
                    <div class="profile-dropdown">
                        <i class="fas fa-user"></i>
                        <div class="dropdown-content">
                            <a href="profile.php">Profile</a>
                            <a href="logout.php">Logout</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- Sidebar -->
        <aside class="admin-sidebar" id="sidebar">
            <div class="sidebar-header">
                <h3>Admin Manager</h3>
                <p>Admin</p>
            </div>
            <nav class="sidebar-nav">
                <ul>
                    <li>
                        <a href="index.php">
                            <i class="fas fa-home"></i>
                            <span>Dashboard</span>
                        </a>
                    </li>
                    <li>
                        <a href="users.php">
                            <i class="fas fa-users"></i>
                            <span>Manage Users</span>
                        </a>
                    </li>
                    <li>
                        <a href="create-user.php">
                            <i class="fas fa-user-plus"></i>
                            <span>Create New User</span>
                        </a>
                    </li>
                    <li>
                        <a href="applications.php">
                            <i class="fas fa-user-friends"></i>
                            <span>New User Application(s)</span>
                        </a>
                    </li>
                    <li class="active">
                        <a href="transactions.php">
                            <i class="fas fa-exchange-alt"></i>
                            <span>Transfer Transactions</span>
                        </a>
                    </li>
                    <li>
                        <a href="deposits.php">
                            <i class="fas fa-arrow-down"></i>
                            <span>Users Deposits</span>
                        </a>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-cog"></i>
                            <span>Loan Applications</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="loans.php">View All</a></li>
                            <li><a href="loans.php?status=pending">Pending</a></li>
                            <li><a href="loans.php?status=approved">Approved</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-credit-card"></i>
                            <span>Virtual Cards</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="cards.php">Manage Cards</a></li>
                            <li><a href="cards.php?status=active">Active</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-file-invoice-dollar"></i>
                            <span>IRS Refunds</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="refunds.php">View All</a></li>
                            <li><a href="refunds.php?status=pending">Pending</a></li>
                        </ul>
                    </li>
                    <li>
                        <a href="email.php">
                            <i class="fas fa-envelope"></i>
                            <span>Email Services</span>
                        </a>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-user-shield"></i>
                            <span>Administrator(s)</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="admins.php">View All</a></li>
                            <li><a href="create-admin.php">Add New</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-cog"></i>
                            <span>Settings</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="settings.php">General</a></li>
                            <li><a href="security.php">Security</a></li>
                        </ul>
                    </li>
                </ul>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="admin-main">
            <div class="page-header">
                <h2>Manage Transactions</h2>
                <nav class="breadcrumb">
                    <a href="index.php">Dashboard</a> / Manage Transactions
                </nav>
            </div>

            <?php if (isset($success_message)): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i>
                    <?php echo htmlspecialchars($success_message); ?>
                </div>
            <?php endif; ?>

            <?php if (isset($error_message)): ?>
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars($error_message); ?>
                </div>
            <?php endif; ?>

            <!-- Transaction Statistics -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-exchange-alt"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['total_transactions']); ?></h3>
                        <p>Total Transactions</p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['completed']); ?></h3>
                        <p>Completed</p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['pending']); ?></h3>
                        <p>Pending</p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                    <div class="stat-content">
                        <h3>$<?php echo number_format($stats['total_amount'], 2); ?></h3>
                        <p>Total Amount</p>
                    </div>
                </div>
            </div>

            <!-- Filters and Search -->
            <div class="filters-section">
                <form method="GET" class="filters-form">
                    <div class="filter-row">
                        <div class="filter-group">
                            <label for="search">Search Transactions</label>
                                                         <input type="text" id="search" name="search" 
                                    value="<?php echo htmlspecialchars($search); ?>"
                                    placeholder="Search by account number, username, reference, or description">
                        </div>
                        
                        <div class="filter-group">
                            <label for="status">Status</label>
                            <select id="status" name="status">
                                <option value="">All Statuses</option>
                                <?php foreach ($statuses as $status): ?>
                                    <option value="<?php echo htmlspecialchars($status['status']); ?>"
                                            <?php echo $status_filter === $status['status'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($status['status']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                                                 <div class="filter-group">
                             <label for="type">Transaction Type</label>
                             <select id="type" name="type">
                                 <option value="">All Types</option>
                                 <option value="Deposit" <?php echo $type_filter === 'Deposit' ? 'selected' : ''; ?>>Deposit</option>
                                 <option value="Withdrawal" <?php echo $type_filter === 'Withdrawal' ? 'selected' : ''; ?>>Withdrawal</option>
                                 <option value="Transfer" <?php echo $type_filter === 'Transfer' ? 'selected' : ''; ?>>Transfer</option>
                                 <option value="Loan" <?php echo $type_filter === 'Loan' ? 'selected' : ''; ?>>Loan</option>
                                 <option value="Refund" <?php echo $type_filter === 'Refund' ? 'selected' : ''; ?>>Refund</option>
                             </select>
                         </div>
                        
                        <div class="filter-group">
                            <label for="date_from">Date From</label>
                            <input type="date" id="date_from" name="date_from" 
                                   value="<?php echo htmlspecialchars($date_from); ?>">
                        </div>
                        
                        <div class="filter-group">
                            <label for="date_to">Date To</label>
                            <input type="date" id="date_to" name="date_to" 
                                   value="<?php echo htmlspecialchars($date_to); ?>">
                        </div>
                        
                        <div class="filter-actions">
                            <button type="submit" class="btn-primary">
                                <i class="fas fa-search"></i>
                                Filter
                            </button>
                            <a href="transactions.php" class="btn-secondary">
                                <i class="fas fa-undo"></i>
                                Clear
                            </a>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Transactions Table -->
            <div class="table-container">
                <div class="table-header">
                    <h3>Transactions (<?php echo number_format($total_transactions); ?> total)</h3>
                    <div class="header-actions">
                        <button class="btn-secondary" onclick="exportTransactions()">
                            <i class="fas fa-download"></i>
                            Export
                        </button>
                        <button class="btn-primary" onclick="createTransaction()">
                            <i class="fas fa-plus"></i>
                            New Transaction
                        </button>
                    </div>
                </div>

                <?php if (empty($transactions)): ?>
                    <div class="no-data">
                        <i class="fas fa-exchange-alt"></i>
                        <p>No transactions found matching your criteria.</p>
                        <a href="transactions.php" class="btn-secondary">View All Transactions</a>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="transactions-table">
                            <thead>
                                                        <tr>
                            <th>Transaction Details</th>
                            <th>User</th>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($transactions as $transaction): ?>
                                    <tr>
                                        <td class="transaction-details">
                                            <div class="transaction-info">
                                                <h4><?php echo htmlspecialchars($transaction['reference_number']); ?></h4>
                                                <p class="transaction-desc"><?php echo htmlspecialchars(substr($transaction['description'], 0, 50)) . (strlen($transaction['description']) > 50 ? '...' : ''); ?></p>
                                            </div>
                                        </td>
                                        
                                        <td class="user-info">
                                            <div class="account-info">
                                                <strong>Account:</strong> <?php echo htmlspecialchars($transaction['account_number'] ?? 'N/A'); ?>
                                            </div>
                                            <div class="user-name">
                                                <?php if ($transaction['firstname']): ?>
                                                    <?php echo htmlspecialchars($transaction['firstname'] . ' ' . $transaction['lastname']); ?>
                                                <?php else: ?>
                                                    <span class="external">User ID: <?php echo $transaction['user_id']; ?></span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        
                                        <td class="transaction-type">
                                            <span class="type-badge"><?php echo htmlspecialchars($transaction['transaction_type']); ?></span>
                                        </td>
                                        
                                        <td class="amount-cell">
                                            <div class="amount">$<?php echo number_format($transaction['amount'], 2); ?></div>
                                        </td>
                                        
                                        <td class="status-cell">
                                            <span class="status-badge status-<?php echo strtolower($transaction['status']); ?>">
                                                <?php echo htmlspecialchars($transaction['status']); ?>
                                            </span>
                                        </td>
                                        
                                        <td class="date-cell">
                                            <div class="date"><?php echo date('M j, Y', strtotime($transaction['created_at'])); ?></div>
                                            <div class="time"><?php echo date('g:i A', strtotime($transaction['created_at'])); ?></div>
                                        </td>
                                        
                                        <td class="actions-cell">
                                            <div class="action-buttons">
                                                <button class="btn-action btn-view" 
                                                        onclick="viewTransaction(<?php echo $transaction['id']; ?>)"
                                                        title="View Details">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                
                                                <div class="dropdown">
                                                    <button class="btn-action btn-more" title="More Actions">
                                                        <i class="fas fa-ellipsis-v"></i>
                                                    </button>
                                                    <div class="dropdown-content">
                                                        <form method="POST" style="display: inline;">
                                                            <input type="hidden" name="action" value="update_status">
                                                            <input type="hidden" name="transaction_id" value="<?php echo $transaction['id']; ?>">
                                                            <select name="status" onchange="this.form.submit()">
                                                                <option value="">Change Status</option>
                                                                <option value="Pending">Pending</option>
                                                                <option value="Processing">Processing</option>
                                                                <option value="Completed">Completed</option>
                                                                <option value="Failed">Failed</option>
                                                                <option value="Cancelled">Cancelled</option>
                                                            </select>
                                                        </form>
                                                        
                                                        <button onclick="deleteTransaction(<?php echo $transaction['id']; ?>)" 
                                                                class="btn-delete">
                                                            <i class="fas fa-trash"></i>
                                                            Delete
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                        <div class="pagination">
                            <?php if ($page > 1): ?>
                                <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" 
                                   class="page-link">
                                    <i class="fas fa-chevron-left"></i>
                                    Previous
                                </a>
                            <?php endif; ?>
                            
                            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>" 
                                   class="page-link <?php echo $i === $page ? 'active' : ''; ?>">
                                    <?php echo $i; ?>
                                </a>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                                <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" 
                                   class="page-link">
                                    Next
                                    <i class="fas fa-chevron-right"></i>
                                </a>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <!-- Delete Confirmation Modal -->
    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Confirm Delete</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this transaction? This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="deleteForm">
                    <input type="hidden" name="action" value="delete_transaction">
                    <input type="hidden" name="transaction_id" id="deleteTransactionId">
                    <button type="button" class="btn-secondary" onclick="closeModal()">Cancel</button>
                    <button type="submit" class="btn-danger">Delete Transaction</button>
                </form>
            </div>
        </div>
    </div>

    <script src="assets/js/admin.js"></script>
    <script>
        // Transaction management functions
        function viewTransaction(transactionId) {
            // Implement view transaction functionality
            console.log('Viewing transaction:', transactionId);
            // You can redirect to a transaction details page or show a modal
        }

        function createTransaction() {
            // Implement create transaction functionality
            console.log('Creating new transaction');
            // You can redirect to a create transaction page
        }

        function exportTransactions() {
            // Implement export functionality
            console.log('Exporting transactions');
            // You can implement CSV/Excel export
        }

        function deleteTransaction(transactionId) {
            document.getElementById('deleteTransactionId').value = transactionId;
            document.getElementById('deleteModal').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('deleteModal').style.display = 'none';
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('deleteModal');
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        }

        // Close modal when clicking close button
        document.querySelector('.close').onclick = function() {
            closeModal();
        }

        // Auto-submit status changes
        document.querySelectorAll('select[name="status"]').forEach(select => {
            select.addEventListener('change', function() {
                if (this.value) {
                    this.form.submit();
                }
            });
        });
    </script>
</body>
</html>
