<?php
require_once 'includes/auth_check.php';
$page = 'wire';
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
require_once '../config/database.php';
require_once '../includes/functions.php';

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

// Get filter parameters
$status = isset($_GET['status']) ? $_GET['status'] : '';

try {
    // Build query based on filters
    $query = "SELECT w.*, u.first_name, u.last_name, u.email 
              FROM wire_transfers w 
              JOIN users u ON w.user_id = u.id";
    
    $params = [];
    
    if (!empty($status)) {
        if ($status == 'hold') {
            $query .= " WHERE w.hold_reason IS NOT NULL AND w.hold_reason != ''";
        } elseif ($status == 'pending') {
            $query .= " WHERE (w.hold_reason IS NULL OR w.hold_reason = '') 
                        AND (w.approved_at IS NULL) 
                        AND (w.rejected_reason IS NULL OR w.rejected_reason = '')";
        } elseif ($status == 'approved') {
            $query .= " WHERE w.approved_at IS NOT NULL";
        } elseif ($status == 'rejected') {
            $query .= " WHERE w.rejected_reason IS NOT NULL AND w.rejected_reason != ''";
        }
    }
    
    $query .= " ORDER BY w.created_at DESC LIMIT 200";
    
    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $transfers = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get counts for each status
    $count_query = "
        SELECT 
            SUM(CASE 
                WHEN hold_reason IS NOT NULL AND hold_reason != '' THEN 1 
                ELSE 0 
            END) as hold_count,
            SUM(CASE 
                WHEN (hold_reason IS NULL OR hold_reason = '') 
                     AND (approved_at IS NULL) 
                     AND (rejected_reason IS NULL OR rejected_reason = '') THEN 1 
                ELSE 0 
            END) as pending_count,
            SUM(CASE 
                WHEN approved_at IS NOT NULL THEN 1 
                ELSE 0 
            END) as approved_count,
            SUM(CASE 
                WHEN rejected_reason IS NOT NULL AND rejected_reason != '' THEN 1 
                ELSE 0 
            END) as rejected_count
        FROM wire_transfers
    ";
    
    $count_stmt = $db->prepare($count_query);
    $count_stmt->execute();
    $counts = $count_stmt->fetch(PDO::FETCH_ASSOC);
    
    $status_counts = [
        'pending' => $counts['pending_count'] ?? 0,
        'hold' => $counts['hold_count'] ?? 0,
        'approved' => $counts['approved_count'] ?? 0,
        'rejected' => $counts['rejected_count'] ?? 0
    ];
    
    $total_count = array_sum($status_counts);
    
} catch (PDOException $e) {
    error_log("Admin Wire Transactions DB Error: " . $e->getMessage());
    $transfers = [];
    $status_counts = [];
    $total_count = 0;
    $pageError = "Could not load wire transaction data.";
}

include 'includes/header.php';
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Wire Transfer Management</h1>
    
    <!-- Display Success/Error Messages -->
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    
    <!-- Status Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Transfers</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($total_count); ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-calendar fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($status_counts['pending'] ?? 0); ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-clock fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">On Hold</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($status_counts['hold'] ?? 0); ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-pause fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Approved</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($status_counts['approved'] ?? 0); ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-check fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Filter Card -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Filter Transfers</h6>
        </div>
        <div class="card-body">
            <form method="GET" action="wire_transactions.php" class="mb-0">
                <div class="row align-items-end">
                    <div class="col-md-4">
                        <label for="status" class="form-label">Status</label>
                        <select name="status" id="status" class="form-select">
                            <option value="">All Statuses</option>
                            <option value="pending" <?php echo ($status == 'pending') ? 'selected' : ''; ?>>Pending</option>
                            <option value="hold" <?php echo ($status == 'hold') ? 'selected' : ''; ?>>On Hold</option>
                            <option value="approved" <?php echo ($status == 'approved') ? 'selected' : ''; ?>>Approved</option>
                            <option value="rejected" <?php echo ($status == 'rejected') ? 'selected' : ''; ?>>Rejected</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <button type="submit" class="btn btn-primary">Apply Filter</button>
                        <a href="wire_transactions.php" class="btn btn-secondary">Reset</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Transfers Table -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Wire Transfers</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" width="100%" cellspacing="0">
                    <thead class="table-light">
                        <tr>
                            <th>Reference</th>
                            <th>Date</th>
                            <th>Customer</th>
                            <th>Recipient</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($transfers)): ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted py-4">No wire transfers found.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($transfers as $transfer): ?>
                                <?php 
                                // Determine the effective status based on various fields
                                $effective_status = 'pending';
                                if (!empty($transfer['hold_reason'])) {
                                    $effective_status = 'hold';
                                } elseif (!empty($transfer['approved_at'])) {
                                    $effective_status = 'approved';
                                } elseif (!empty($transfer['rejected_reason'])) {
                                    $effective_status = 'rejected';
                                }
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($transfer['reference']); ?></td>
                                    <td><?php echo date('M j, Y', strtotime($transfer['created_at'])); ?><br>
                                        <small class="text-muted"><?php echo date('g:i A', strtotime($transfer['created_at'])); ?></small>
                                    </td>
                                    <td>
                                        <?php echo htmlspecialchars($transfer['first_name'] . ' ' . $transfer['last_name']); ?><br>
                                        <small class="text-muted"><?php echo htmlspecialchars($transfer['email']); ?></small>
                                    </td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($transfer['recipient_name']); ?></strong><br>
                                        <small class="text-muted"><?php echo htmlspecialchars($transfer['bank_name']); ?> (<?php echo htmlspecialchars($transfer['swift_code']); ?>)</small>
                                    </td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($transfer['currency']); ?> <?php echo number_format($transfer['amount'], 2); ?></strong><br>
                                        <small class="text-muted">Fee: <?php echo htmlspecialchars($transfer['currency']); ?> <?php echo number_format($transfer['fee'], 2); ?></small>
                                    </td>
                                    <td>
                                        <?php if ($effective_status == 'pending'): ?>
                                            <span class="badge bg-warning text-dark">Pending</span>
                                        <?php elseif ($effective_status == 'approved'): ?>
                                            <span class="badge bg-success">Approved</span>
                                        <?php elseif ($effective_status == 'rejected'): ?>
                                            <span class="badge bg-danger">Rejected</span>
                                        <?php elseif ($effective_status == 'hold'): ?>
                                            <span class="badge bg-info">On Hold</span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary"><?php echo ucfirst($effective_status); ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <?php if ($effective_status == 'pending' || $effective_status == 'hold'): ?>
                                            <div class="dropdown">
                                                <button class="btn btn-primary btn-sm dropdown-toggle" type="button" id="actionDropdown<?php echo $transfer['id']; ?>" data-bs-toggle="dropdown" aria-expanded="false">
                                                    Actions
                                                </button>
                                                <ul class="dropdown-menu" aria-labelledby="actionDropdown<?php echo $transfer['id']; ?>">
                                                    <li><a class="dropdown-item" href="view_wire_transfer.php?id=<?php echo $transfer['id']; ?>"><i class='bx bx-show me-2'></i> View Details</a></li>
                                                    <li><a class="dropdown-item" href="#" onclick="approveTransfer(<?php echo $transfer['id']; ?>); return false;"><i class='bx bx-check me-2 text-success'></i> Approve</a></li>
                                                    <?php if ($effective_status == 'pending'): ?>
                                                    <li><a class="dropdown-item" href="#" onclick="holdTransfer(<?php echo $transfer['id']; ?>); return false;"><i class='bx bx-pause me-2 text-info'></i> Place on Hold</a></li>
                                                    <?php endif; ?>
                                                    <li><a class="dropdown-item" href="#" onclick="rejectTransfer(<?php echo $transfer['id']; ?>); return false;"><i class='bx bx-x me-2 text-danger'></i> Reject</a></li>
                                                </ul>
                                            </div>
                                        <?php else: ?>
                                            <a href="view_wire_transfer.php?id=<?php echo $transfer['id']; ?>" class="btn btn-primary btn-sm">
                                                <i class='bx bx-show'></i> View
                                            </a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Hidden form for actions -->
<form id="actionForm" action="admin_wire_actions.php" method="POST" style="display: none;">
    <input type="hidden" name="transfer_id" id="transfer_id_input">
    <input type="hidden" name="action" id="action_input">
    <input type="hidden" name="reason" id="reason_input">
    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'] ?? ''); ?>">
</form>

<script>
function approveTransfer(transferId) {
    Swal.fire({
        title: 'Approve Wire Transfer',
        text: 'Are you sure you want to approve this wire transfer?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, approve it!'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('transfer_id_input').value = transferId;
            document.getElementById('action_input').value = 'approve';
            document.getElementById('actionForm').submit();
        }
    });
}

function holdTransfer(transferId) {
    Swal.fire({
        title: 'Place Transfer on Hold',
        text: 'Please provide a reason for placing this transfer on hold:',
        input: 'text',
        inputAttributes: {
            autocapitalize: 'off',
            required: 'required'
        },
        showCancelButton: true,
        confirmButtonText: 'Place on Hold',
        confirmButtonColor: '#17a2b8',
        cancelButtonColor: '#6c757d',
        showLoaderOnConfirm: true,
        preConfirm: (reason) => {
            if (!reason) {
                Swal.showValidationMessage('Please enter a reason');
            }
            return reason;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('transfer_id_input').value = transferId;
            document.getElementById('action_input').value = 'hold';
            document.getElementById('reason_input').value = result.value;
            document.getElementById('actionForm').submit();
        }
    });
}

function rejectTransfer(transferId) {
    Swal.fire({
        title: 'Reject Wire Transfer',
        text: 'Please provide a reason for rejecting this transfer:',
        input: 'text',
        inputAttributes: {
            autocapitalize: 'off',
            required: 'required'
        },
        showCancelButton: true,
        confirmButtonText: 'Reject Transfer',
        confirmButtonColor: '#dc3545',
        cancelButtonColor: '#6c757d',
        showLoaderOnConfirm: true,
        preConfirm: (reason) => {
            if (!reason) {
                Swal.showValidationMessage('Please enter a reason');
            }
            return reason;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('transfer_id_input').value = transferId;
            document.getElementById('action_input').value = 'reject';
            document.getElementById('reason_input').value = result.value;
            document.getElementById('actionForm').submit();
        }
    });
}
</script>

<?php include 'includes/footer.php'; ?>
