<?php
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'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

$error = '';
$success = '';
$upload_dir = 'uploads/receipts/';

// Create upload directory if it doesn't exist
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Get students for dropdown
$students = $pdo->query("SELECT s.id, s.first_name, s.last_name, u.email 
                        FROM students s 
                        JOIN users u ON s.id = u.id 
                        ORDER BY s.last_name, s.first_name")->fetchAll();

// Get payment types for dropdown
$payment_types = $pdo->query("SELECT id, name FROM payment_types WHERE is_active = 1 ORDER BY name")->fetchAll();

// Get applications for dropdown (optional)
$applications = $pdo->query("SELECT a.id, a.application_status, p.name as program_name, u.name as university_name
                           FROM applications a
                           JOIN programs p ON a.program_id = p.id
                           JOIN universities u ON p.university_id = u.id
                           ORDER BY a.created_at DESC")->fetchAll();

// Handle payment creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_payment'])) {
    $student_id = $_POST['student_id'] ?? null;
    $payment_type_id = $_POST['payment_type_id'] ?? null;
    $amount = $_POST['amount'] ?? null;
    $currency = $_POST['currency'] ?? 'USD';
    $payment_date = $_POST['payment_date'] ?? date('Y-m-d');
    $payment_method = $_POST['payment_method'] ?? 'other';
    $transaction_id = $_POST['transaction_id'] ?? '';
    $status = $_POST['status'] ?? 'completed';
    $related_application_id = $_POST['related_application_id'] ?? null;
    $notes = $_POST['notes'] ?? '';
    $reference_number = $_POST['reference_number'] ?? '';

    // Validate form data
    if (!$student_id || !$payment_type_id || !$amount) {
        $error = "Student, payment type, and amount are required.";
    } elseif (!is_numeric($amount) || $amount <= 0) {
        $error = "Amount must be a positive number.";
    } else {
        try {
            // Start transaction
            $pdo->beginTransaction();

            // Create 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, reference_number, admin_id, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");

            $stmt->execute([
                $student_id, $payment_type_id, $amount, $currency, $payment_date,
                $payment_method, $transaction_id, $status, $related_application_id,
                $notes, $reference_number, $_SESSION['user_id']
            ]);

            $payment_id = $pdo->lastInsertId();

            // Handle receipt upload
            $receipt_path = null;
            if (isset($_FILES['receipt']) && $_FILES['receipt']['name']) {
                $file_name = $_FILES['receipt']['name'];
                $file_tmp = $_FILES['receipt']['tmp_name'];
                $file_size = $_FILES['receipt']['size'];
                $file_error = $_FILES['receipt']['error'];

                if ($file_error === UPLOAD_ERR_OK && $file_size <= 10 * 1024 * 1024) {
                    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    $allowed_exts = ['pdf', 'jpg', 'jpeg', 'png'];

                    if (in_array($file_ext, $allowed_exts)) {
                        $unique_name = $payment_id . '_receipt_' . time() . '.' . $file_ext;
                        $file_path = $upload_dir . $unique_name;

                        if (move_uploaded_file($file_tmp, $file_path)) {
                            // Update payment with receipt path
                            $pdo->prepare("UPDATE payments SET receipt_path = ? WHERE id = ?")
                                ->execute([$file_path, $payment_id]);

                            $receipt_path = $file_path;
                        }
                    }
                }
            }

            // If payment is completed and related to an application, update application fee status
            if ($status === 'completed' && $related_application_id) {
                $pdo->prepare("UPDATE applications SET application_fee_paid = 1, fee_payment_date = ?, fee_amount = ? WHERE id = ?")
                    ->execute([$payment_date, $amount, $related_application_id]);
            }

            // If payment is completed, create or update invoice status
            if ($status === 'completed') {
                // Check if there's an unpaid invoice for this student and payment type
                $stmt = $pdo->prepare("SELECT id FROM invoices WHERE student_id = ? AND status = 'unpaid' AND description LIKE ?");
                $stmt->execute([$student_id, "%{$payment_types[array_search($payment_type_id, array_column($payment_types, 'id'))]['name']}%"]);
                $invoice = $stmt->fetch();

                if ($invoice) {
                    // Update existing invoice
                    $pdo->prepare("UPDATE invoices SET status = 'paid', payment_id = ? WHERE id = ?")
                        ->execute([$payment_id, $invoice['id']]);
                }
            }

            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "payment_created",
                "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} created payment of {$currency} {$amount} for student {$student_id}"
            ]);

            // Create notification for student
            $student_stmt = $pdo->prepare("SELECT first_name, last_name FROM students WHERE id = ?");
            $student_stmt->execute([$student_id]);
            $student = $student_stmt->fetch();

            $pdo->prepare("INSERT INTO notifications (
                user_id, title, message, is_read, notification_type, created_at
            ) VALUES (?, ?, ?, 0, 'payment', NOW())")->execute([
                $student_id,
                "Payment Received",
                "A payment of {$currency} {$amount} has been recorded for your account"
            ]);

            // Commit transaction
            $pdo->commit();

            $success = "Payment created successfully!";

            // Optionally reset $_POST to clear form after success
            $_POST = [];

        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Failed to create payment. Please try again.";
        }
    }
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Create Payment - 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>
        .form-section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        .form-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        .section-title {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3fb7fe;
        }
        .file-upload {
            position: relative;
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
        }
        .file-upload:hover {
            border-color: #3fb7fe;
            background: #f8f9fa;
        }
        .file-input {
            display: none;
        }
        .info-box {
            background: #f8f9fa;
            border-left: 4px solid #3fb7fe;
            padding: 15px;
            margin: 20px 0;
            border-radius: 5px;
        }
        .payment-info {
            font-size: 1.2em;
            font-weight: 600;
            color: #3fb7fe;
        }
    </style>
</head>
<body>

<?php include 'admin-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">Financial Management</h6>
        <h1 class="display-5">Record New Payment</h1>
    </div>

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

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

    <form method="POST" enctype="multipart/form-data">
        <div class="form-section">
            <h5 class="section-title">Payment Details</h5>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Student *</label>
                    <select name="student_id" class="form-control" id="studentSelect" required onchange="updateStudentInfo()">
                        <option value="">Select Student</option>
                        <?php foreach ($students as $s): ?>
                        <option value="<?= $s['id'] ?>" data-email="<?= htmlspecialchars($s['email']) ?>"
                            <?= (isset($_POST['student_id']) && $_POST['student_id'] == $s['id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <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 $pt): ?>
                        <option value="<?= $pt['id'] ?>" <?= (isset($_POST['payment_type_id']) && $_POST['payment_type_id'] == $pt['id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($pt['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Amount *</label>
                    <div class="input-group">
                        <input type="number" name="amount" class="form-control" step="0.01" min="0.01"
                            value="<?= htmlspecialchars($_POST['amount'] ?? '') ?>" required>
                        <div class="input-group-append">
                            <select name="currency" class="form-control">
                                <option value="USD" <?= (($_POST['currency'] ?? 'USD') === 'USD') ? 'selected' : '' ?>>USD</option>
                                <option value="EUR" <?= (($_POST['currency'] ?? 'USD') === 'EUR') ? 'selected' : '' ?>>EUR</option>
                                <option value="GBP" <?= (($_POST['currency'] ?? 'USD') === 'GBP') ? 'selected' : '' ?>>GBP</option>
                                <option value="CAD" <?= (($_POST['currency'] ?? 'USD') === 'CAD') ? 'selected' : '' ?>>CAD</option>
                                <option value="AUD" <?= (($_POST['currency'] ?? 'USD') === 'AUD') ? 'selected' : '' ?>>AUD</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Payment Date *</label>
                    <input type="date" name="payment_date" class="form-control"
                        value="<?= htmlspecialchars($_POST['payment_date'] ?? date('Y-m-d')) ?>" required>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Payment Method *</label>
                    <select name="payment_method" class="form-control" required>
                        <option value="credit_card" <?= (($_POST['payment_method'] ?? 'other') === 'credit_card') ? 'selected' : '' ?>>Credit Card</option>
                        <option value="bank_transfer" <?= (($_POST['payment_method'] ?? 'other') === 'bank_transfer') ? 'selected' : '' ?>>Bank Transfer</option>
                        <option value="paypal" <?= (($_POST['payment_method'] ?? 'other') === 'paypal') ? 'selected' : '' ?>>PayPal</option>
                        <option value="cash" <?= (($_POST['payment_method'] ?? 'other') === 'cash') ? 'selected' : '' ?>>Cash</option>
                        <option value="other" <?= (($_POST['payment_method'] ?? 'other') === 'other') ? 'selected' : '' ?>>Other</option>
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Status *</label>
                    <select name="status" class="form-control" required>
                        <option value="completed" <?= (($_POST['status'] ?? 'completed') === 'completed') ? 'selected' : '' ?>>Completed</option>
                        <option value="pending" <?= (($_POST['status'] ?? 'completed') === 'pending') ? 'selected' : '' ?>>Pending</option>
                        <option value="failed" <?= (($_POST['status'] ?? 'completed') === 'failed') ? 'selected' : '' ?>>Failed</option>
                        <option value="refunded" <?= (($_POST['status'] ?? 'completed') === 'refunded') ? 'selected' : '' ?>>Refunded</option>
                    </select>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Transaction ID</label>
                    <input type="text" name="transaction_id" class="form-control"
                        value="<?= htmlspecialchars($_POST['transaction_id'] ?? '') ?>">
                    <small class="form-text text-muted">Reference number from payment processor</small>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Reference Number</label>
                    <input type="text" name="reference_number" class="form-control"
                        value="<?= htmlspecialchars($_POST['reference_number'] ?? '') ?>">
                    <small class="form-text text-muted">Internal reference number</small>
                </div>
            </div>
        </div>

        <div class="form-section">
            <h5 class="section-title">Related Information</h5>
            <div class="form-group">
                <label>Related Application</label>
                <select name="related_application_id" class="form-control">
                    <option value="">No Related Application</option>
                    <?php foreach ($applications as $app): ?>
                    <option value="<?= $app['id'] ?>" <?= ($app['id'] == ($_POST['related_application_id'] ?? '')) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($app['university_name'] . ' - ' . $app['program_name'] . ' (' . $app['application_status'] . ')') ?>
                    </option>
                    <?php endforeach; ?>
                </select>
                <small class="form-text text-muted">If this payment is for an application fee, select the related application</small>
            </div>
        </div>

        <div class="form-section">
            <h5 class="section-title">Receipt</h5>
            <div class="form-group">
                <label>Upload Receipt</label>
                <div class="file-upload" id="receiptUpload">
                    <i class="fas fa-file-upload fa-3x mb-3" style="color: #3fb7fe;"></i>
                    <h6>Upload Receipt</h6>
                    <p class="text-muted small">PDF, JPG, PNG (max 10MB)</p>
                    <input type="file" name="receipt" id="receiptFile" class="file-input" accept=".pdf,.jpg,.jpeg,.png">
                </div>
                <small class="form-text text-muted">Optional: Upload a copy of the receipt or payment confirmation</small>
            </div>
        </div>

        <div class="form-section">
            <h5 class="section-title">Additional Notes</h5>
            <div class="form-group">
                <label>Notes</label>
                <textarea name="notes" class="form-control" rows="4"
                    placeholder="Internal notes about this payment"><?= htmlspecialchars($_POST['notes'] ?? '') ?></textarea>
            </div>
        </div>

        <div class="info-box">
            <h6><i class="fas fa-info-circle"></i> What Happens Next?</h6>
            <ul class="small">
                <li>The student will be notified of the new payment</li>
                <li>If this is a completed payment for an application, the application fee status will be updated</li>
                <li>If there's an unpaid invoice matching this payment type, it will be marked as paid</li>
                <li>You can view and manage this payment from the payments section</li>
            </ul>
        </div>

        <div class="text-center">
            <button type="submit" name="create_payment" class="btn btn-primary btn-lg px-5">Record Payment</button>
        </div>

        <div class="text-center mt-3">
            <a href="admin-payments.php" class="btn btn-outline-primary">Cancel</a>
        </div>
    </form>
</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>
    // Receipt upload functionality
    document.getElementById('receiptUpload').addEventListener('click', function() {
        document.getElementById('receiptFile').click();
    });

    document.getElementById('receiptFile').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            document.getElementById('receiptUpload').innerHTML = `
                <i class="fas fa-file-alt fa-3x mb-3" style="color: #3fb7fe;"></i>
                <h6>${file.name}</h6>
                <p class="text-muted small">${(file.size / 1024 / 1024).toFixed(2)} MB</p>
                <p class="text-success">Ready to upload</p>
            `;
        }
    });

    // Form submission confirmation
    $('form').on('submit', function(e) {
        const studentSelect = $('#studentSelect');
        const amountInput = $('input[name="amount"]');
        const studentName = studentSelect.find('option:selected').text();
        const amount = amountInput.val();
        const currency = $('select[name="currency"]').val();

        if (studentSelect.val() && amount && confirm(`You are about to record a payment of ${currency} ${amount} for ${studentName}. Continue?`)) {
            return true;
        } else {
            e.preventDefault();
        }
    });
</script>
</body>
</html>
