<?php
include realpath(dirname(__DIR__) . '/include/header.php');
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="page-title-box">
                <h4 class="page-title">Payment Gateway Management</h4>
                <p class="text-muted">Manage payment gateways and their configurations</p>
            </div>
        </div>
    </div>

    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Installed Gateways -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-credit-card-multiple"></i> Installed Payment Gateways
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($gateways['installed'])): ?>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>Gateway</th>
                                        <th>Version</th>
                                        <th>Status</th>
                                        <th>Last Updated</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($gateways['installed'] as $gateway): ?>
                                        <tr>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <div class="flex-shrink-0">
                                                        <div class="avatar-sm">
                                                            <div class="avatar-title rounded bg-primary text-white">
                                                                <i class="mdi mdi-credit-card"></i>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="flex-grow-1 ms-3">
                                                        <h6 class="mb-0"><?php echo htmlspecialchars($gateway['name']); ?></h6>
                                                        <p class="text-muted mb-0 font-size-12">
                                                            <?php echo htmlspecialchars($gateway['description']); ?>
                                                        </p>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="badge bg-info">v<?php echo htmlspecialchars($gateway['version']); ?></span>
                                            </td>
                                            <td>
                                                <?php if ($gateway['status'] === 'active'): ?>
                                                    <span class="badge bg-success">
                                                        <i class="mdi mdi-check"></i> Active
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary">
                                                        <i class="mdi mdi-pause"></i> Inactive
                                                    </span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php echo $gateway['updated_at'] ? date('M j, Y', strtotime($gateway['updated_at'])) : 'Never'; ?>
                                            </td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <button type="button" class="btn btn-sm btn-outline-primary" 
                                                            onclick="configureGateway('<?php echo $gateway['gateway_id']; ?>')">
                                                        <i class="mdi mdi-cog"></i> Configure
                                                    </button>
                                                    
                                                    <form method="POST" action="?app_route=payment_gateways_toggle" class="d-inline">
                                                        <input type="hidden" name="gateway_id" value="<?php echo $gateway['gateway_id']; ?>">
                                                        <input type="hidden" name="status" value="<?php echo $gateway['status'] === 'active' ? 'inactive' : 'active'; ?>">
                                                        <button type="submit" class="btn btn-sm btn-outline-<?php echo $gateway['status'] === 'active' ? 'warning' : 'success'; ?>">
                                                            <i class="mdi mdi-<?php echo $gateway['status'] === 'active' ? 'pause' : 'play'; ?>"></i>
                                                            <?php echo $gateway['status'] === 'active' ? 'Disable' : 'Enable'; ?>
                                                        </button>
                                                    </form>
                                                    
                                                    <button type="button" class="btn btn-sm btn-outline-info" 
                                                            onclick="testGateway('<?php echo $gateway['gateway_id']; ?>')">
                                                        <i class="mdi mdi-test-tube"></i> Test
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-4">
                            <div class="avatar-lg mx-auto mb-3">
                                <div class="avatar-title rounded-circle bg-soft-primary text-primary">
                                    <i class="mdi mdi-credit-card-plus font-size-24"></i>
                                </div>
                            </div>
                            <h5>No Payment Gateways Installed</h5>
                            <p class="text-muted">Install payment gateways to start accepting payments from your customers.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Available Gateways -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-download"></i> Available Payment Gateways
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($gateways['available'])): ?>
                        <div class="row">
                            <?php foreach ($gateways['available'] as $gateway): ?>
                                <?php
                                // Check if already installed
                                $isInstalled = false;
                                foreach ($gateways['installed'] as $installed) {
                                    if ($installed['gateway_id'] === $gateway['id']) {
                                        $isInstalled = true;
                                        break;
                                    }
                                }
                                ?>
                                <div class="col-md-6 col-lg-4 mb-3">
                                    <div class="card border">
                                        <div class="card-body">
                                            <div class="d-flex align-items-center mb-3">
                                                <?php if (isset($gateway['icon'])): ?>
                                                    <img src="<?php echo htmlspecialchars($gateway['icon']); ?>" 
                                                         alt="<?php echo htmlspecialchars($gateway['name']); ?>" 
                                                         class="avatar-sm rounded me-3">
                                                <?php else: ?>
                                                    <div class="avatar-sm rounded bg-primary text-white me-3">
                                                        <div class="avatar-title">
                                                            <i class="mdi mdi-credit-card"></i>
                                                        </div>
                                                    </div>
                                                <?php endif; ?>
                                                <div>
                                                    <h6 class="mb-0"><?php echo htmlspecialchars($gateway['name']); ?></h6>
                                                    <small class="text-muted">v<?php echo htmlspecialchars($gateway['version']); ?></small>
                                                </div>
                                            </div>
                                            
                                            <p class="text-muted font-size-13">
                                                <?php echo htmlspecialchars($gateway['description']); ?>
                                            </p>
                                            
                                            <?php if (isset($gateway['author'])): ?>
                                                <p class="text-muted font-size-12 mb-2">
                                                    <strong>Author:</strong> <?php echo htmlspecialchars($gateway['author']); ?>
                                                </p>
                                            <?php endif; ?>
                                            
                                            <?php if (!$isInstalled): ?>
                                                <button type="button" class="btn btn-primary btn-sm w-100" 
                                                        onclick="installGateway('<?php echo $gateway['id']; ?>')">
                                                    <i class="mdi mdi-download"></i> Install Gateway
                                                </button>
                                            <?php else: ?>
                                                <button type="button" class="btn btn-success btn-sm w-100" disabled>
                                                    <i class="mdi mdi-check"></i> Already Installed
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-4">
                            <div class="avatar-lg mx-auto mb-3">
                                <div class="avatar-title rounded-circle bg-soft-warning text-warning">
                                    <i class="mdi mdi-package-variant font-size-24"></i>
                                </div>
                            </div>
                            <h5>No Available Gateways</h5>
                            <p class="text-muted">Upload payment gateway addons to the addons/payment_gateways directory.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Developer Documentation Link -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card bg-soft-info">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0">
                            <div class="avatar-sm">
                                <div class="avatar-title rounded bg-info text-white">
                                    <i class="mdi mdi-file-document"></i>
                                </div>
                            </div>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h6 class="mb-1">Developer Documentation</h6>
                            <p class="mb-0">Learn how to create custom payment gateway addons for NuxSaaS</p>
                        </div>
                        <div class="flex-shrink-0">
                            <a href="?app_route=developer_docs_payment_gateways" class="btn btn-info">
                                <i class="mdi mdi-book-open"></i> View Docs
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Gateway Configuration Modal -->
<div class="modal fade" id="configModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Gateway Configuration</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="?app_route=payment_gateways_configure">
                <div class="modal-body" id="configModalBody">
                    <!-- Configuration fields will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Configuration</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Gateway Installation Modal -->
<div class="modal fade" id="installModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Install Payment Gateway</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="?app_route=payment_gateways_install">
                <div class="modal-body" id="installModalBody">
                    <!-- Installation form will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Install Gateway</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function configureGateway(gatewayId) {
    // Load gateway configuration form
    fetch(`?app_route=api_gateway_config&gateway_id=${gatewayId}`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('configModalBody').innerHTML = data.html;
            new bootstrap.Modal(document.getElementById('configModal')).show();
        })
        .catch(error => {
            console.error('Error loading gateway config:', error);
            alert('Failed to load gateway configuration');
        });
}

function installGateway(gatewayId) {
    // Load gateway installation form
    fetch(`?app_route=api_gateway_install&gateway_id=${gatewayId}`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('installModalBody').innerHTML = data.html;
            new bootstrap.Modal(document.getElementById('installModal')).show();
        })
        .catch(error => {
            console.error('Error loading gateway install form:', error);
            alert('Failed to load gateway installation form');
        });
}

function testGateway(gatewayId) {
    if (confirm('Test the connection to this payment gateway?')) {
        const formData = new FormData();
        formData.append('gateway_id', gatewayId);
        
        fetch(`?app_route=api_gateway_test`, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Gateway test successful: ' + data.message);
            } else {
                alert('Gateway test failed: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error testing gateway:', error);
            alert('Failed to test gateway connection');
        });
    }
}
</script>

<?php
include realpath(dirname(__DIR__) . '/include/footer.php');
?>
