<?php
/**
 * JV Overseas Education - Student Payments
 * Single-file PHP with integrated HTML and backend logic
 * Matches design of original index.html
 */

session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'student') {
    header('Location: student-login.php');
    exit;
}

// Get student data
$stmt = $pdo->prepare("SELECT s.*, u.email, 
                      CONCAT(c.first_name, ' ', c.last_name) as counselor_name,
                      c.id as counselor_id
                      FROM students s 
                      LEFT JOIN counselors c ON s.assigned_counselor_id = c.id
                      JOIN users u ON s.id = u.id 
                      WHERE s.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$student) {
    die("Student profile not found.");
}

// Get payment types
$payment_types = $pdo->query("SELECT * FROM payment_types WHERE is_active = 1 ORDER BY name");
$payment_types = $payment_types->fetchAll(PDO::FETCH_ASSOC);

// Get student payments
$payments = $pdo->prepare("SELECT p.*, pt.name as payment_type_name, pt.description as payment_type_description,
                          a.id as application_id, a.program_id, u.name as university_name, pr.name as program_name
                          FROM payments p
                          JOIN payment_types pt ON p.payment_type_id = pt.id
                          LEFT JOIN applications a ON p.related_application_id = a.id
                          LEFT JOIN programs pr ON a.program_id = pr.id
                          LEFT JOIN universities u ON pr.university_id = u.id
                          WHERE p.student_id = ?
                          ORDER BY p.payment_date DESC, p.created_at DESC");
$payments->execute([$_SESSION['user_id']]);
$payments = $payments->fetchAll();

// Get related invoices
$invoices = $pdo->prepare("SELECT * FROM invoices WHERE student_id = ? ORDER BY due_date DESC");
$invoices->execute([$_SESSION['user_id']]);
$invoices = $invoices->fetchAll();

// Calculate totals
$total_paid = array_sum(array_map(function($p) { 
    return $p['status'] === 'completed' ? $p['amount'] : 0; 
}, $payments));

$total_pending = array_sum(array_map(function($p) { 
    return $p['status'] === 'pending' ? $p['amount'] : 0; 
}, $payments));

// Handle new payment submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['make_payment'])) {
    $payment_type_id = $_POST['payment_type_id'] ?? '';
    $amount = $_POST['amount'] ?? '';
    $payment_date = $_POST['payment_date'] ?? '';
    $payment_method = $_POST['payment_method'] ?? '';
    $transaction_id = trim($_POST['transaction_id'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $related_application_id = $_POST['related_application_id'] ?? null;
    
    if (empty($payment_type_id) || empty($amount) || empty($payment_date) || empty($payment_method)) {
        $error = "All required fields must be filled.";
    } elseif (!is_numeric($amount) || $amount <= 0) {
        $error = "Please enter a valid amount.";
    } elseif (!in_array($payment_method, ['credit_card', 'bank_transfer', 'paypal', 'other'])) {
        $error = "Invalid payment method selected.";
    } else {
        try {
            // Validate payment type exists and is active
            $stmt = $pdo->prepare("SELECT id FROM payment_types WHERE id = ? AND is_active = 1");
            $stmt->execute([$payment_type_id]);
            if (!$stmt->fetch()) {
                $error = "Invalid payment type selected.";
            } else {
                // Insert payment
                $stmt = $pdo->prepare("INSERT INTO payments (
                    student_id, payment_type_id, amount, currency, payment_date, payment_method, 
                    transaction_id, status, related_application_id, notes, receipt_path, created_at
                ) VALUES (?, ?, ?, 'USD', ?, ?, ?, 'completed', ?, ?, NULL, NOW())");
                
                $stmt->execute([
                    $_SESSION['user_id'], $payment_type_id, $amount, $payment_date, 
                    $payment_method, $transaction_id, $related_application_id, $notes
                ]);
                
                $payment_id = $pdo->lastInsertId();
                
                // Create notification for admin/counselor
                $pdo->prepare("INSERT INTO notifications (
                    user_id, title, message, is_read, notification_type, created_at
                ) VALUES (?, ?, ?, 0, 'payment', NOW())")->execute([
                    1, // Admin user ID
                    "New Payment Received",
                    "Student {$_SESSION['first_name']} {$_SESSION['last_name']} has made a payment of USD {$amount}"
                ]);
                
                // Update invoice status if applicable
                if ($related_application_id) {
                    $pdo->prepare("UPDATE invoices SET status = 'paid', payment_id = ? 
                                  WHERE student_id = ? AND related_application_id = ? AND status = 'unpaid'")
                        ->execute([$payment_id, $_SESSION['user_id'], $related_application_id]);
                }
                
                $_SESSION['success'] = "Payment recorded successfully!";
                header("Location: student-payments.php");
                exit;
                
            }
        } catch (Exception $e) {
            $error = "Failed to process payment. Please try again.";
        }
    }
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: student-dashboard.php');
    exit;
}

// Display success message from session if exists
$success = $_SESSION['success'] ?? '';
unset($_SESSION['success']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Payments - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .payment-status {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9em;
        }
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        .status-completed {
            background: #d4edda;
            color: #155724;
        }
        .status-failed {
            background: #f8d7da;
            color: #721c24;
        }
        .status-refunded {
            background: #d1ecf1;
            color: #0c5460;
        }
        .invoice-status {
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 0.8em;
        }
        .invoice-unpaid {
            background: #f8d7da;
            color: #721c24;
        }
        .invoice-paid {
            background: #d4edda;
            color: #155724;
        }
        .invoice-overdue {
            background: #fff3cd;
            color: #856404;
        }
        .stats-card {
            border-left: 4px solid #3fb7fe;
            padding: 15px;
            margin-bottom: 20px;
        }
        .receipt-link {
            color: #3fb7fe;
            text-decoration: none;
        }
        .receipt-link:hover {
            text-decoration: underline;
        }
        .payment-method {
            font-size: 0.9em;
            color: #6c757d;
        }
        .application-ref {
            font-size: 0.9em;
            color: #6c757d;
            margin-top: 2px;
        }
    </style>
</head>
<body>

<?php include 'student-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Payments & Invoices</h6>
        <h1 class="display-5">Manage Your Payments</h1>
    </div>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if (!empty($success)): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <div class="row">
        <div class="col-lg-8">
            <!-- Payment Statistics -->
            <div class="row mb-4">
                <div class="col-md-4 mb-3">
                    <div class="stats-card">
                        <h6>Total Paid</h6>
                        <h3 class="text-primary">$<?= number_format($total_paid, 2) ?></h3>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="stats-card" style="border-left-color: #28a745;">
                        <h6>Pending</h6>
                        <h3 class="text-success">$<?= number_format($total_pending, 2) ?></h3>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="stats-card" style="border-left-color: #dc3545;">
                        <h6>Transactions</h6>
                        <h3 class="text-danger"><?= count($payments) ?></h3>
                    </div>
                </div>
            </div>

            <!-- Make Payment Form -->
            <div class="bg-white p-4 rounded mb-4">
                <h5 class="mb-3">Record a Payment</h5>
                <form method="POST">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Payment Type *</label>
                            <select name="payment_type_id" class="form-control" required>
                                <option value="">Select Payment Type</option>
                                <?php foreach ($payment_types as $type): ?>
                                <option value="<?= $type['id'] ?>" 
                                        data-description="<?= htmlspecialchars($type['description']) ?>">
                                    <?= htmlspecialchars($type['name']) ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Amount (USD) *</label>
                            <input type="number" name="amount" class="form-control" step="0.01" min="1" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Payment Date *</label>
                            <input type="date" name="payment_date" class="form-control" 
                                   value="<?= date('Y-m-d') ?>" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Payment Method *</label>
                            <select name="payment_method" class="form-control" required>
                                <option value="">Select Method</option>
                                <option value="credit_card">Credit Card</option>
                                <option value="bank_transfer">Bank Transfer</option>
                                <option value="paypal">PayPal</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Transaction ID (Optional)</label>
                            <input type="text" name="transaction_id" class="form-control" 
                                   placeholder="e.g., TRX123456789">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Related Application (Optional)</label>
                            <select name="related_application_id" class="form-control">
                                <option value="">No specific application</option>
                                <?php 
                                $stmt = $pdo->prepare("SELECT a.id, u.name as university, p.name as program 
                                                      FROM applications a
                                                      JOIN programs p ON a.program_id = p.id
                                                      JOIN universities u ON p.university_id = u.id
                                                      WHERE a.student_id = ?
                                                      ORDER BY a.submission_date DESC");
                                $stmt->execute([$_SESSION['user_id']]);
                                $applications = $stmt->fetchAll();
                                foreach ($applications as $app): ?>
                                <option value="<?= $app['id'] ?>">
                                    <?= htmlspecialchars($app['university'] . ' - ' . $app['program']) ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group mb-3">
                        <label>Notes (Optional)</label>
                        <textarea name="notes" class="form-control" rows="2" 
                                  placeholder="Any additional information about this payment"></textarea>
                    </div>
                    <button type="submit" name="make_payment" class="btn btn-primary">
                        <i class="fas fa-money-bill-wave"></i> Record Payment
                    </button>
                </form>
            </div>

            <!-- Payment History -->
            <div class="bg-white p-4 rounded">
                <h5 class="mb-4">Payment History</h5>
                
                <?php if (empty($payments)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-money-bill-wave fa-3x text-muted mb-3"></i>
                        <p>You haven't made any payments yet.</p>
                        <p class="small">Your payment history will appear here once you start making payments.</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Type</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Method</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($payments as $payment): ?>
                                <tr>
                                    <td>
                                        <?= date('M j, Y', strtotime($payment['payment_date'])) ?>
                                    </td>
                                    <td>
                                        <strong><?= htmlspecialchars($payment['payment_type_name']) ?></strong>
                                        <?php if ($payment['payment_type_description']): ?>
                                        <div class="payment-method">
                                            <?= htmlspecialchars($payment['payment_type_description']) ?>
                                        </div>
                                        <?php endif; ?>
                                        <?php if ($payment['application_id']): ?>
                                        <div class="application-ref">
                                            For: <?= htmlspecialchars($payment['university_name'] . ' - ' . $payment['program_name']) ?>
                                        </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <strong>$<?= number_format($payment['amount'], 2) ?></strong>
                                        <div class="text-muted"><?= $payment['currency'] ?></div>
                                    </td>
                                    <td>
                                        <span class="payment-status status-<?= $payment['status'] ?>">
                                            <?= ucfirst($payment['status']) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge badge-secondary">
                                            <?= ucfirst(str_replace('_', ' ', $payment['payment_method'])) ?>
                                        </span>
                                        <?php if ($payment['transaction_id']): ?>
                                        <div class="small mt-1">ID: <?= htmlspecialchars($payment['transaction_id']) ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($payment['receipt_path']): ?>
                                        <a href="<?= htmlspecialchars($payment['receipt_path']) ?>" 
                                           class="btn btn-sm btn-outline-primary receipt-link" target="_blank">
                                            <i class="fas fa-file-invoice"></i> Receipt
                                        </a>
                                        <?php else: ?>
                                        <button class="btn btn-sm btn-outline-secondary" disabled>
                                            <i class="fas fa-file-invoice"></i> No Receipt
                                        </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="col-lg-4">
            <!-- Invoices -->
            <?php if (!empty($invoices)): ?>
            <div class="bg-light p-4 rounded mb-4">
                <h6><i class="fas fa-file-invoice"></i> Open Invoices</h6>
                <?php foreach ($invoices as $invoice): ?>
                <div class="border p-3 mb-3 rounded">
                    <div class="d-flex justify-content-between">
                        <strong>Invoice #<?= $invoice['id'] ?></strong>
                        <span class="invoice-status invoice-<?= $invoice['status'] ?>">
                            <?= ucfirst($invoice['status']) ?>
                        </span>
                    </div>
                    <div class="mt-2">
                        <div>Amount: <strong>$<?= number_format($invoice['amount'], 2) ?></strong></div>
                        <div>Due: <strong><?= date('M j, Y', strtotime($invoice['due_date'])) ?></strong></div>
                        <?php if ($invoice['description']): ?>
                        <div class="small mt-1"><?= htmlspecialchars($invoice['description']) ?></div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <div class="bg-light p-4 rounded">
                <h6><i class="fas fa-info-circle"></i> Payment Information</h6>
                <ul class="small">
                    <li>All payments should be in USD unless otherwise specified</li>
                    <li>Keep your transaction ID for reference</li>
                    <li>Contact your counselor for any payment-related queries</li>
                    <li>Receipts will be available within 24 hours of payment</li>
                </ul>
                
                <hr>
                
                <h6><i class="fas fa-question-circle"></i> Need Help?</h6>
                <p class="small mb-1">Contact your counselor:</p>
                <?php if ($student['counselor_name']): ?>
                    <p class="font-weight-bold"><?= htmlspecialchars($student['counselor_name']) ?></p>
                <?php else: ?>
                    <p class="font-weight-bold">Not assigned yet</p>
                <?php endif; ?>
                <p class="small">+256 788 289 235</p>
                <p class="small">Email: <?= htmlspecialchars($student['email']) ?></p>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    // Update description when payment type changes
    $('select[name="payment_type_id"]').on('change', function() {
        const selected = $(this).find('option:selected');
        const description = selected.data('description') || '';
        // You could display the description below the select
    });
    
    // Form submission confirmation
    $('form').on('submit', function(e) {
        const amount = $('input[name="amount"]').val();
        const type = $('select[name="payment_type_id"] option:selected').text();
        
        if (amount && confirm(`You are about to record a payment of $${amount} for ${type}. Continue?`)) {
            return true;
        } else {
            e.preventDefault();
        }
    });
</script>
</body>
</html>