<?php
require_once '../includes/config.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

// Check authentication for sensitive operations
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit();
}

$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'POST':
            // Process payment
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['invoice_id']) || !isset($data['payment_method'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Missing required fields']);
                exit();
            }
            
            // In a real implementation, you would:
            // 1. Validate the invoice exists and belongs to the student
            // 2. Process payment with Stripe/PayPal
            // 3. Record the payment
            
            // This is a simulation
            $invoice_id = $data['invoice_id'];
            $student_id = $_SESSION['user_id'];
            $amount = 0;
            
            // Get invoice amount
            $stmt = $pdo->prepare("SELECT amount FROM invoices WHERE id = ? AND student_id = ?");
            $stmt->execute([$invoice_id, $student_id]);
            $invoice = $stmt->fetch();
            
            if (!$invoice) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Invoice not found']);
                exit();
            }
            
            $amount = $invoice['amount'];
            
            // Create payment record
            $stmt = $pdo->prepare("INSERT INTO payments 
                                 (student_id, payment_type_id, amount, payment_method, status) 
                                 VALUES (?, 1, ?, ?, 'completed')");
            $stmt->execute([$student_id, $amount, $data['payment_method']]);
            $payment_id = $pdo->lastInsertId();
            
            // Update invoice
            $pdo->prepare("UPDATE invoices SET status = 'paid', payment_id = ? WHERE id = ?")
                ->execute([$payment_id, $invoice_id]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Payment processed successfully',
                'payment_id' => $payment_id
            ]);
            break;
            
        case 'GET':
            // Get payment history or details
            if (isset($_GET['student_id']) && hasRole('admin')) {
                // Admin viewing student payments
                $student_id = $_GET['student_id'];
                $stmt = $pdo->prepare("SELECT * FROM payments WHERE student_id = ? ORDER BY payment_date DESC");
                $stmt->execute([$student_id]);
            } elseif (isset($_GET['id'])) {
                // Get specific payment
                $stmt = $pdo->prepare("SELECT * FROM payments WHERE id = ?");
                $stmt->execute([$_GET['id']]);
            } else {
                // Student viewing their own payments
                $student_id = $_SESSION['user_id'];
                $stmt = $pdo->prepare("SELECT * FROM payments WHERE student_id = ? ORDER BY payment_date DESC");
                $stmt->execute([$student_id]);
            }
            
            $payments = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'data' => $payments]);
            break;
            
        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>