<?php
$page_title = "Transaction Details";
require_once 'header.php';

$db = Database::getInstance()->connect();

if (!isset($_GET['id'])) {
    header('Location: transactions.php');
    exit;
}

$transaction_id = intval($_GET['id']);

// Handle actions
if (isset($_GET['action'])) {
    $action = $_GET['action'];
    
    try {
        $db->beginTransaction();
        
        // Get transaction details for action
        $stmt = $db->prepare("SELECT * FROM transactions WHERE id = ?");
        $stmt->execute([$transaction_id]);
        $transaction = $stmt->fetch();
        
        if (!$transaction) {
            throw new Exception("Transaction not found");
        }
        
        $user_id = $transaction['user_id'];
        $amount = $transaction['amount'];
        $type = $transaction['type'];
        
        $success = false;
        $message = "";

        if ($action == 'approve' && $transaction['status'] == 'pending') {
            if ($type == 'deposit') {
                $update_stmt = $db->prepare("UPDATE transactions SET status = 'completed', admin_action_by = ? WHERE id = ?");
                $update_stmt->execute([$_SESSION['admin_id'], $transaction_id]);
                
                $balance_stmt = $db->prepare("UPDATE users SET balance = balance + ?, total_deposit = total_deposit + ? WHERE id = ?");
                $balance_stmt->execute([$amount, $amount, $user_id]);
                
                $message = "Deposit approved successfully!";
                $success = true;
            } elseif ($type == 'withdrawal') {
                $update_stmt = $db->prepare("UPDATE transactions SET status = 'completed', admin_action_by = ? WHERE id = ?");
                $update_stmt->execute([$_SESSION['admin_id'], $transaction_id]);
                
                $total_stmt = $db->prepare("UPDATE users SET total_withdrawal = total_withdrawal + ? WHERE id = ?");
                $total_stmt->execute([$amount, $user_id]);
                
                $message = "Withdrawal approved successfully!";
                $success = true;
            }
            
            if ($success) {
                // Log action
                $log_stmt = $db->prepare("INSERT INTO activity_logs (admin_id, user_id, action, description, details, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
                $log_stmt->execute([
                    $_SESSION['admin_id'],
                    $user_id,
                    $type . '_approve',
                    ucfirst($type) . ' approved',
                    json_encode(['transaction_id' => $transaction_id, 'amount' => $amount, 'reference' => $transaction['reference']])
                ]);
            }

        } elseif ($action == 'reject' && $transaction['status'] == 'pending') {
            if ($type == 'deposit') {
                $update_stmt = $db->prepare("UPDATE transactions SET status = 'rejected', admin_action_by = ? WHERE id = ?");
                $update_stmt->execute([$_SESSION['admin_id'], $transaction_id]);
                $message = "Deposit rejected successfully!";
                $success = true;
            } elseif ($type == 'withdrawal') {
                $update_stmt = $db->prepare("UPDATE transactions SET status = 'rejected', admin_action_by = ? WHERE id = ?");
                $update_stmt->execute([$_SESSION['admin_id'], $transaction_id]);
                
                $return_stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                $return_stmt->execute([$amount, $user_id]);
                
                $message = "Withdrawal rejected successfully!";
                $success = true;
            }
            
            if ($success) {
                // Log action
                $log_stmt = $db->prepare("INSERT INTO activity_logs (admin_id, user_id, action, description, details, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
                $log_stmt->execute([
                    $_SESSION['admin_id'],
                    $user_id,
                    $type . '_reject',
                    ucfirst($type) . ' rejected',
                    json_encode(['transaction_id' => $transaction_id, 'amount' => $amount, 'reference' => $transaction['reference']])
                ]);
            }
        } elseif ($action == 'delete') {
            // For withdrawals, return balance if pending
            if ($type == 'withdrawal' && $transaction['status'] == 'pending') {
                $return_stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                $return_stmt->execute([$amount, $user_id]);
            }
            
            $delete_stmt = $db->prepare("DELETE FROM transactions WHERE id = ?");
            $delete_stmt->execute([$transaction_id]);
            
            $message = "Transaction deleted successfully!";
            $success = true;
        }
        
        $db->commit();
        
        if ($success) {
            if ($action == 'delete') {
                echo "<script>alert('$message'); window.location.href='transactions.php';</script>";
            } else {
                echo "<script>alert('$message'); window.location.href='transaction-view.php?id=$transaction_id';</script>";
            }
            exit();
        }
        
    } catch (Exception $e) {
        $db->rollBack();
        $error = "Action failed: " . $e->getMessage();
    }
}

// Get transaction details
$sql = "SELECT t.*, u.username, u.email, u.full_name, u.phone, u.country, u.balance as user_balance,
               au.username as admin_username
        FROM transactions t 
        LEFT JOIN users u ON t.user_id = u.id 
        LEFT JOIN admin_users au ON t.admin_action_by = au.id
        WHERE t.id = ?";

$stmt = $db->prepare($sql);
$stmt->execute([$transaction_id]);
$transaction = $stmt->fetch();

if (!$transaction) {
    echo "<script>alert('Transaction not found'); window.location.href='transactions.php';</script>";
    exit;
}

$details = json_decode($transaction['details'] ?? '{}', true);
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="mb-6">
        <div class="flex justify-between items-center">
            <div>
                <h1 class="text-2xl font-bold">Transaction #<?php echo $transaction['id']; ?></h1>
                <p class="text-gray-600">Reference: <?php echo htmlspecialchars($transaction['reference']); ?></p>
            </div>
            <div class="flex space-x-2">
                <a href="transactions.php" class="bg-gray-200 text-gray-800 px-4 py-2 rounded-lg hover:bg-gray-300">
                    <i class="fas fa-arrow-left mr-2"></i>Back to List
                </a>
                <button onclick="window.print()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-print mr-2"></i>Print
                </button>
            </div>
        </div>
    </div>

    <?php if (isset($error)): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
        <?php echo $error; ?>
    </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Left Column: Transaction Details -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Transaction Card -->
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <div class="flex justify-between items-center">
                        <div>
                            <h2 class="text-xl font-bold">Transaction Details</h2>
                            <p class="text-gray-600">Created on <?php echo date('F d, Y H:i', strtotime($transaction['created_at'])); ?></p>
                        </div>
                        <span class="px-4 py-2 rounded-full text-sm font-semibold <?php
                            echo $transaction['status'] == 'completed' ? 'bg-green-100 text-green-800' :
                                ($transaction['status'] == 'pending' ? 'bg-yellow-100 text-yellow-800' :
                                ($transaction['status'] == 'rejected' ? 'bg-red-100 text-red-800' :
                                'bg-gray-100 text-gray-800'));
                        ?>">
                            <?php echo ucfirst($transaction['status']); ?>
                        </span>
                    </div>
                </div>
                
                <div class="p-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Amount & Type -->
                        <div class="space-y-4">
                            <div>
                                <p class="text-sm text-gray-600">Amount</p>
                                <p class="text-3xl font-bold <?php echo in_array($transaction['type'], ['deposit', 'profit', 'referral_bonus']) ? 'text-green-600' : 'text-red-600'; ?>">
                                    <?php echo in_array($transaction['type'], ['deposit', 'profit', 'referral_bonus']) ? '+' : '-'; ?>
                                    $<?php echo number_format($transaction['amount'], 2); ?>
                                </p>
                                <?php if ($transaction['fee'] > 0): ?>
                                <p class="text-sm text-gray-500">Fee: $<?php echo number_format($transaction['fee'], 2); ?></p>
                                <p class="text-sm text-gray-500">Net: $<?php echo number_format($transaction['net_amount'], 2); ?></p>
                                <?php endif; ?>
                            </div>
                            
                            <div>
                                <p class="text-sm text-gray-600">Type</p>
                                <p class="text-lg font-semibold capitalize"><?php echo str_replace('_', ' ', $transaction['type']); ?></p>
                            </div>
                            
                            <div>
                                <p class="text-sm text-gray-600">Method</p>
                                <p class="text-lg font-semibold capitalize"><?php echo $transaction['method'] ?: 'N/A'; ?></p>
                            </div>
                        </div>
                        
                        <!-- Additional Info -->
                        <div class="space-y-4">
                            <div>
                                <p class="text-sm text-gray-600">Description</p>
                                <p class="font-medium"><?php echo htmlspecialchars($transaction['description']); ?></p>
                            </div>
                            
                            <?php if ($transaction['admin_action_by']): ?>
                            <div>
                                <p class="text-sm text-gray-600">Processed By</p>
                                <p class="font-medium"><?php echo htmlspecialchars($transaction['admin_username']); ?></p>
                                <p class="text-xs text-gray-500"><?php echo date('M d, Y H:i', strtotime($transaction['updated_at'])); ?></p>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (isset($details['wallet_address'])): ?>
                            <div>
                                <p class="text-sm text-gray-600">Wallet Address</p>
                                <p class="font-mono text-sm break-all bg-gray-50 p-2 rounded"><?php echo htmlspecialchars($details['wallet_address']); ?></p>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (isset($details['bank_name'])): ?>
                            <div>
                                <p class="text-sm text-gray-600">Bank Details</p>
                                <div class="bg-gray-50 p-2 rounded text-sm">
                                    <p>Bank: <?php echo htmlspecialchars($details['bank_name']); ?></p>
                                    <p>Account: <?php echo htmlspecialchars($details['account_number']); ?></p>
                                    <p>Name: <?php echo htmlspecialchars($details['account_name']); ?></p>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <?php if ($transaction['payment_proof']): ?>
                    <div class="mt-6 border-t pt-6">
                        <p class="text-sm text-gray-600 mb-2">Payment Proof</p>
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <?php 
                            $ext = strtolower(pathinfo($transaction['payment_proof'], PATHINFO_EXTENSION));
                            if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'])): 
                            ?>
                                <img src="../uploads/proofs/<?php echo htmlspecialchars($transaction['payment_proof']); ?>" alt="Payment Proof" class="rounded-lg shadow-sm max-w-full mb-4" style="max-height: 400px;">
                            <?php endif; ?>
                            <a href="../uploads/proofs/<?php echo htmlspecialchars($transaction['payment_proof']); ?>" download class="flex items-center text-blue-600 hover:text-blue-800">
                                <i class="fas fa-download text-xl mr-3"></i>
                                <span>Download Proof Document</span>
                            </a>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Right Column: User Info & Actions -->
        <div class="space-y-6">
            <!-- User Information -->
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <h3 class="text-lg font-bold">User Information</h3>
                </div>
                <div class="p-6">
                    <div class="space-y-4">
                        <div class="flex items-center space-x-3 mb-4">
                            <div class="w-12 h-12 bg-gray-200 rounded-full flex items-center justify-center text-gray-600 font-bold text-xl">
                                <?php echo strtoupper(substr($transaction['username'], 0, 1)); ?>
                            </div>
                            <div>
                                <p class="font-bold"><?php echo htmlspecialchars($transaction['username']); ?></p>
                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($transaction['email']); ?></p>
                            </div>
                        </div>
                        
                        <div class="border-t pt-4 space-y-2">
                            <div class="flex justify-between">
                                <span class="text-gray-600">Full Name:</span>
                                <span class="font-medium"><?php echo htmlspecialchars($transaction['full_name'] ?? 'N/A'); ?></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">Phone:</span>
                                <span class="font-medium"><?php echo htmlspecialchars($transaction['phone'] ?? 'N/A'); ?></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">Country:</span>
                                <span class="font-medium"><?php echo htmlspecialchars($transaction['country'] ?? 'N/A'); ?></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">Current Balance:</span>
                                <span class="font-bold text-green-600">$<?php echo number_format($transaction['user_balance'], 2); ?></span>
                            </div>
                        </div>
                        
                        <div class="mt-6">
                            <a href="user-edit.php?id=<?php echo $transaction['user_id']; ?>" 
                               class="block text-center bg-gray-800 text-white py-2 rounded-lg hover:bg-gray-900">
                                <i class="fas fa-user-edit mr-2"></i>View User Profile
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <h3 class="text-lg font-bold">Actions</h3>
                </div>
                <div class="p-6 space-y-3">
                    <?php if ($transaction['status'] == 'pending'): ?>
                        <?php if (in_array($transaction['type'], ['deposit', 'withdrawal'])): ?>
                        <a href="?action=approve&id=<?php echo $transaction['id']; ?>" 
                           onclick="return confirm('Are you sure you want to approve this transaction?')"
                           class="block w-full bg-green-600 text-white text-center py-2 rounded-lg hover:bg-green-700">
                            <i class="fas fa-check mr-2"></i>Approve
                        </a>
                        
                        <a href="?action=reject&id=<?php echo $transaction['id']; ?>" 
                           onclick="return confirm('Are you sure you want to reject this transaction?')"
                           class="block w-full bg-red-600 text-white text-center py-2 rounded-lg hover:bg-red-700">
                            <i class="fas fa-times mr-2"></i>Reject
                        </a>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <a href="?action=delete&id=<?php echo $transaction['id']; ?>" 
                       onclick="return confirm('WARNING: This will permanently delete this transaction record. Are you sure?')"
                       class="block w-full bg-gray-600 text-white text-center py-2 rounded-lg hover:bg-gray-700">
                        <i class="fas fa-trash-alt mr-2"></i>Delete Record
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once 'footer.php'; ?>