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

// Get active payment gateways
$sql = "SELECT * FROM payment_gateways WHERE status = 'active' ORDER BY name";
$stmt = $conn->query($sql);
$gateways = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get user subscriptions
$userId = $_SESSION['user_id'] ?? 1; // Default for testing
$sql = "SELECT * FROM subscriptions WHERE user_id = ? ORDER BY created_at DESC";
$stmt = $conn->prepare($sql);
$stmt->execute([$userId]);
$subscriptions = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="page-title-box">
                <h4 class="page-title">Payment Center</h4>
                <p class="text-muted">Renew your subscription or make payments</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; ?>

    <!-- Subscription Renewal Section -->
    <div class="row">
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-refresh"></i> Subscription Renewal
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($subscriptions)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Plan</th>
                                        <th>Status</th>
                                        <th>Expires</th>
                                        <th>Amount</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($subscriptions as $subscription): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo htmlspecialchars($subscription['plan_name']); ?></strong>
                                            </td>
                                            <td>
                                                <?php
                                                $statusColor = 'secondary';
                                                switch ($subscription['status']) {
                                                    case 'active': $statusColor = 'success'; break;
                                                    case 'expired': $statusColor = 'danger'; break;
                                                    case 'cancelled': $statusColor = 'warning'; break;
                                                }
                                                ?>
                                                <span class="badge bg-<?php echo $statusColor; ?>">
                                                    <?php echo ucfirst($subscription['status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php 
                                                $expiresAt = strtotime($subscription['expires_at']);
                                                $isExpiringSoon = $expiresAt < strtotime('+7 days');
                                                $textClass = $isExpiringSoon ? 'text-warning' : '';
                                                ?>
                                                <span class="<?php echo $textClass; ?>">
                                                    <?php echo date('M j, Y', $expiresAt); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <strong>$<?php echo number_format($subscription['amount'], 2); ?></strong>
                                                <small class="text-muted">/ <?php echo $subscription['billing_cycle']; ?></small>
                                            </td>
                                            <td>
                                                <?php if ($subscription['status'] !== 'cancelled'): ?>
                                                    <button type="button" class="btn btn-primary btn-sm" 
                                                            onclick="showPaymentModal(<?php echo $subscription['id']; ?>, <?php echo $subscription['amount']; ?>, '<?php echo htmlspecialchars($subscription['plan_name']); ?>')">
                                                        <i class="mdi mdi-credit-card"></i> Renew
                                                    </button>
                                                <?php else: ?>
                                                    <span class="text-muted">Cancelled</span>
                                                <?php endif; ?>
                                            </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-info text-info">
                                    <i class="mdi mdi-package-variant font-size-24"></i>
                                </div>
                            </div>
                            <h5>No Subscriptions</h5>
                            <p class="text-muted">You don't have any active subscriptions yet.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Payment Methods -->
        <div class="col-lg-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-credit-card-multiple"></i> Payment Methods
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($gateways)): ?>
                        <div class="list-group list-group-flush">
                            <?php foreach ($gateways as $gateway): ?>
                                <div class="list-group-item d-flex align-items-center px-0">
                                    <div class="flex-shrink-0">
                                        <div class="avatar-xs">
                                            <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 class="flex-shrink-0">
                                        <span class="badge bg-success">
                                            <i class="mdi mdi-check"></i> Active
                                        </span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-3">
                            <div class="avatar-sm mx-auto mb-2">
                                <div class="avatar-title rounded-circle bg-soft-warning text-warning">
                                    <i class="mdi mdi-alert"></i>
                                </div>
                            </div>
                            <p class="text-muted mb-0">No payment methods available</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Recent Payments -->
            <div class="card mt-4">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="mdi mdi-history"></i> Recent Payments
                    </h5>
                </div>
                <div class="card-body">
                    <?php
                    // Get recent payments
                    $sql = "SELECT p.*, pg.name as gateway_name 
                            FROM payments p 
                            LEFT JOIN payment_gateways pg ON p.gateway_id = pg.gateway_id 
                            WHERE p.user_id = ? 
                            ORDER BY p.created_at DESC 
                            LIMIT 5";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute([$userId]);
                    $recentPayments = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    ?>
                    
                    <?php if (!empty($recentPayments)): ?>
                        <div class="list-group list-group-flush">
                            <?php foreach ($recentPayments as $payment): ?>
                                <div class="list-group-item px-0 py-2">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <h6 class="mb-1">$<?php echo number_format($payment['amount'], 2); ?></h6>
                                            <p class="mb-1 text-muted font-size-12">
                                                <?php echo htmlspecialchars($payment['gateway_name'] ?: 'Unknown Gateway'); ?>
                                            </p>
                                            <small class="text-muted">
                                                <?php echo date('M j, Y', strtotime($payment['created_at'])); ?>
                                            </small>
                                        </div>
                                        <div>
                                            <?php
                                            $statusColor = 'secondary';
                                            switch ($payment['status']) {
                                                case 'completed': $statusColor = 'success'; break;
                                                case 'failed': $statusColor = 'danger'; break;
                                                case 'pending': $statusColor = 'warning'; break;
                                                case 'processing': $statusColor = 'info'; break;
                                            }
                                            ?>
                                            <span class="badge bg-<?php echo $statusColor; ?> font-size-11">
                                                <?php echo ucfirst($payment['status']); ?>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <p class="text-muted text-center">No recent payments</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Payment Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Complete Payment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="/payment_process">
                <div class="modal-body">
                    <input type="hidden" name="subscription_id" id="paymentSubscriptionId">
                    <input type="hidden" name="user_id" value="<?php echo $userId; ?>">
                    
                    <div class="mb-3">
                        <label class="form-label">Subscription Plan</label>
                        <input type="text" class="form-control" id="paymentPlanName" readonly>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Amount</label>
                        <div class="input-group">
                            <span class="input-group-text">$</span>
                            <input type="number" class="form-control" name="amount" id="paymentAmount" step="0.01" readonly>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Payment Gateway</label>
                        <select class="form-control" name="gateway_id" required>
                            <option value="">Select Payment Method</option>
                            <?php foreach ($gateways as $gateway): ?>
                                <option value="<?php echo htmlspecialchars($gateway['gateway_id']); ?>">
                                    <?php echo htmlspecialchars($gateway['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </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">
                        <i class="mdi mdi-credit-card"></i> Proceed to Payment
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function showPaymentModal(subscriptionId, amount, planName) {
    document.getElementById('paymentSubscriptionId').value = subscriptionId;
    document.getElementById('paymentAmount').value = amount;
    document.getElementById('paymentPlanName').value = planName;
    
    new bootstrap.Modal(document.getElementById('paymentModal')).show();
}
</script>

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