<?php
require_once __DIR__ . '/../../includes/dashboard-config.php';

// For role-specific pages, add:
checkRoleAccess(ROLE_STUDENT); // or ROLE_COUNSELOR or ROLE_ADMIN
require_once '../../includes/config.php';
require_once '../../includes/auth.php';
require_once '../../includes/functions.php';

if (!isLoggedIn() || !hasRole('student')) {
    header('Location: ../login.php');
    exit();
}

$student_id = $_SESSION['user_id'];

// Get student payments
$payments = $pdo->prepare("
    SELECT p.*, pt.name as payment_type 
    FROM payments p
    JOIN payment_types pt ON p.payment_type_id = pt.id
    WHERE p.student_id = ?
    ORDER BY p.payment_date DESC
");
$payments->execute([$student_id]);

// Get unpaid invoices
$invoices = $pdo->prepare("
    SELECT * FROM invoices 
    WHERE student_id = ? AND status = 'unpaid'
    ORDER BY due_date
");
$invoices->execute([$student_id]);

include '../../includes/header.php';
?>

<div class="container py-5">
    <h2 class="mb-4">Payment Center</h2>
    
    <div class="row">
        <div class="col-md-6">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Outstanding Invoices</h5>
                </div>
                <div class="card-body">
                    <?php if ($invoices->rowCount() > 0): ?>
                        <ul class="list-group">
                            <?php while ($invoice = $invoices->fetch()): ?>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="mb-1">Invoice #<?= $invoice['id'] ?></h6>
                                        <small class="text-muted">
                                            Due: <?= date('M j, Y', strtotime($invoice['due_date'])) ?>
                                        </small>
                                    </div>
                                    <div class="text-right">
                                        <span class="h5">$<?= number_format($invoice['amount'], 2) ?></span>
                                        <button class="btn btn-sm btn-primary pay-invoice" 
                                                data-id="<?= $invoice['id'] ?>">
                                            Pay Now
                                        </button>
                                    </div>
                                </li>
                            <?php endwhile; ?>
                        </ul>
                    <?php else: ?>
                        <div class="alert alert-success">
                            You have no outstanding invoices.
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Payment History</h5>
                </div>
                <div class="card-body">
                    <?php if ($payments->rowCount() > 0): ?>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Type</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($payment = $payments->fetch()): ?>
                                        <tr>
                                            <td><?= date('M j, Y', strtotime($payment['payment_date'])) ?></td>
                                            <td><?= htmlspecialchars($payment['payment_type']) ?></td>
                                            <td>$<?= number_format($payment['amount'], 2) ?></td>
                                            <td>
                                                <span class="badge badge-<?= 
                                                    $payment['status'] == 'completed' ? 'success' : 
                                                    ($payment['status'] == 'pending' ? 'warning' : 'danger') ?>">
                                                    <?= ucfirst($payment['status']) ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-info">
                            No payment history found.
                        </div>
                    <?php endif; ?>
                </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">Make Payment</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="paymentForm">
                        <input type="hidden" id="invoice_id" name="invoice_id">
                        
                        <div class="form-group">
                            <label>Payment Method</label>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="payment_method" 
                                       id="creditCard" value="credit_card" checked>
                                <label class="form-check-label" for="creditCard">
                                    Credit/Debit Card
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="payment_method" 
                                       id="bankTransfer" value="bank_transfer">
                                <label class="form-check-label" for="bankTransfer">
                                    Bank Transfer
                                </label>
                            </div>
                        </div>
                        
                        <div id="creditCardFields">
                            <div class="form-group">
                                <label for="cardNumber">Card Number</label>
                                <input type="text" class="form-control" id="cardNumber" 
                                       placeholder="1234 5678 9012 3456">
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <label for="expiryDate">Expiry Date</label>
                                    <input type="text" class="form-control" id="expiryDate" 
                                           placeholder="MM/YY">
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="cvv">CVV</label>
                                    <input type="text" class="form-control" id="cvv" placeholder="123">
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="cardName">Name on Card</label>
                                <input type="text" class="form-control" id="cardName">
                            </div>
                        </div>
                        
                        <div id="bankTransferFields" style="display: none;">
                            <div class="alert alert-info">
                                <p>Please transfer to:</p>
                                <p><strong>Bank Name:</strong> International Bank</p>
                                <p><strong>Account Name:</strong> JV Overseas Education</p>
                                <p><strong>Account Number:</strong> 1234567890</p>
                                <p><strong>SWIFT Code:</strong> INTLCBANK</p>
                                <p>Include your student ID as reference.</p>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary btn-block">
                                Submit Payment
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Show payment modal
document.querySelectorAll('.pay-invoice').forEach(button => {
    button.addEventListener('click', function() {
        document.getElementById('invoice_id').value = this.dataset.id;
        $('#paymentModal').modal('show');
    });
});

// Toggle payment method fields
document.querySelectorAll('input[name="payment_method"]').forEach(radio => {
    radio.addEventListener('change', function() {
        if (this.value === 'credit_card') {
            document.getElementById('creditCardFields').style.display = 'block';
            document.getElementById('bankTransferFields').style.display = 'none';
        } else {
            document.getElementById('creditCardFields').style.display = 'none';
            document.getElementById('bankTransferFields').style.display = 'block';
        }
    });
});

// Handle payment form submission
document.getElementById('paymentForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    // In a real implementation, you would integrate with Stripe/PayPal here
    // This is just a simulation
    
    const invoiceId = document.getElementById('invoice_id').value;
    const paymentMethod = document.querySelector('input[name="payment_method"]:checked').value;
    
    fetch('../../api/payments.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            invoice_id: invoiceId,
            payment_method: paymentMethod
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Payment submitted successfully!');
            location.reload();
        } else {
            alert('Payment failed: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred during payment');
    });
});
</script>

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