<?php
/**
 * Manual Student Enrollment Page
 * Admin can enroll students by choosing bank transfer option
 */
require_once 'config.php';

// Check admin authentication
$adminId = requireAdminAuth();
$admin = getCurrentAdmin();

// Get database connection
$pdo = getDBConnection();

// Get all subscription packages
$query = "SELECT * FROM subscription_packages ORDER BY duration_months ASC";
$stmt = $pdo->query($query);
$packages = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Page title
$pageTitle = "Enroll New Student";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - ENSI Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #7c3aed;
            --secondary-color: #a78bfa;
            --success-color: #10b981;
            --danger-color: #ef4444;
            --warning-color: #f59e0b;
            --info-color: #3b82f6;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .navbar {
            background: rgba(255, 255, 255, 0.95) !important;
            backdrop-filter: blur(10px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .main-container {
            padding: 30px 0;
        }
        
        .enroll-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            padding: 40px;
            margin-bottom: 30px;
        }
        
        .section-header {
            display: flex;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f3f4f6;
        }
        
        .section-header i {
            font-size: 24px;
            margin-right: 12px;
            color: var(--primary-color);
        }
        
        .section-header h5 {
            margin: 0;
            font-weight: 600;
            color: #1f2937;
        }
        
        .package-option {
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }
        
        .package-option:hover {
            border-color: var(--primary-color);
            background: #f9fafb;
        }
        
        .package-option input[type="radio"] {
            position: absolute;
            opacity: 0;
        }
        
        .package-option input[type="radio"]:checked ~ .package-content {
            border-left: 4px solid var(--primary-color);
            padding-left: 16px;
        }
        
        .package-option input[type="radio"]:checked ~ .package-content .package-check {
            display: block;
        }
        
        .package-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
        }
        
        .package-check {
            display: none;
            color: var(--success-color);
            font-size: 24px;
        }
        
        .package-name {
            font-weight: 600;
            color: #1f2937;
            margin-bottom: 5px;
        }
        
        .package-price {
            font-size: 20px;
            font-weight: 700;
            color: var(--primary-color);
        }
        
        .package-duration {
            color: #6b7280;
            font-size: 14px;
        }
        
        .payment-status-option {
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 15px 20px;
            margin-bottom: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .payment-status-option:hover {
            border-color: var(--primary-color);
            background: #f9fafb;
        }
        
        .payment-status-option input[type="radio"]:checked ~ label {
            color: var(--primary-color);
            font-weight: 600;
        }
        
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 8px;
        }
        
        .form-control, .form-select {
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            padding: 12px;
            transition: all 0.3s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.1);
        }
        
        .btn-enroll {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            border: none;
            border-radius: 10px;
            padding: 15px 40px;
            font-weight: 600;
            font-size: 16px;
            color: white;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(124, 58, 237, 0.3);
        }
        
        .btn-enroll:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(124, 58, 237, 0.4);
        }
        
        .btn-reset {
            background: white;
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            padding: 15px 40px;
            font-weight: 600;
            font-size: 16px;
            color: #6b7280;
            transition: all 0.3s ease;
        }
        
        .btn-reset:hover {
            border-color: #9ca3af;
            background: #f9fafb;
        }
        
        .alert-custom {
            border-radius: 12px;
            border: none;
            padding: 15px 20px;
            margin-bottom: 20px;
        }
        
        .required-star {
            color: var(--danger-color);
            margin-left: 3px;
        }
        
        #bankDetails {
            display: none;
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-light">
        <div class="container-fluid">
            <a class="navbar-brand fw-bold text-primary" href="dashboard.php">
                <i class="bi bi-mortarboard-fill"></i> ENSI Admin
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="dashboard.php">
                            <i class="bi bi-speedometer2"></i> Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="subscriptions.php">
                            <i class="bi bi-card-list"></i> Subscriptions
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="enroll_student.php">
                            <i class="bi bi-person-plus-fill"></i> Enroll Student
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="users.php">
                            <i class="bi bi-people"></i> Users
                        </a>
                    </li>
                </ul>
                <div class="d-flex align-items-center">
                    <span class="me-3">
                        <i class="bi bi-person-circle"></i> 
                        <?php echo htmlspecialchars($admin['username'] ?? 'Admin'); ?>
                    </span>
                    <a href="logout.php" class="btn btn-outline-danger btn-sm">
                        <i class="bi bi-box-arrow-right"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <div class="container main-container">
        <!-- Success/Error Messages -->
        <div id="messageContainer"></div>

        <!-- Enrollment Form -->
        <div class="enroll-card">
            <div class="text-center mb-4">
                <h2 class="fw-bold">
                    <i class="bi bi-person-plus-fill text-primary"></i>
                    Enroll New Student
                </h2>
                <p class="text-muted">Create PRO subscriptions for students who paid via bank transfer</p>
            </div>

            <form id="enrollForm">
                <!-- Student Information -->
                <div class="section-header">
                    <i class="bi bi-person-circle"></i>
                    <h5>Student Information</h5>
                </div>

                <div class="row mb-4">
                    <div class="col-md-6 mb-3">
                        <label for="email" class="form-label">
                            Email Address<span class="required-star">*</span>
                        </label>
                        <input type="email" class="form-control" id="email" name="email" required>
                        <small class="text-muted">We'll check if this email already exists</small>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="fullName" class="form-label">
                            Full Name<span class="required-star">*</span>
                        </label>
                        <input type="text" class="form-control" id="fullName" name="fullName" required>
                    </div>
                </div>

                <div class="row mb-4">
                    <div class="col-md-6 mb-3">
                        <label for="username" class="form-label">Username</label>
                        <input type="text" class="form-control" id="username" name="username" placeholder="Auto-generated if empty">
                        <small class="text-muted">Leave empty to auto-generate from email</small>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="phone" class="form-label">Phone Number (Optional)</label>
                        <input type="tel" class="form-control" id="phone" name="phone" placeholder="0771234567">
                    </div>
                </div>

                <!-- Package Selection -->
                <div class="section-header mt-4">
                    <i class="bi bi-box-seam"></i>
                    <h5>Package Selection</h5>
                </div>

                <div class="mb-4">
                    <?php foreach ($packages as $package): ?>
                    <label class="package-option" for="package_<?php echo $package['id']; ?>">
                        <input type="radio" name="packageId" id="package_<?php echo $package['id']; ?>" 
                               value="<?php echo $package['id']; ?>" 
                               data-price="<?php echo $package['discounted_price']; ?>"
                               data-duration="<?php echo $package['duration_months']; ?>"
                               required>
                        <div class="package-content">
                            <div>
                                <div class="package-name"><?php echo htmlspecialchars($package['package_name']); ?></div>
                                <div class="package-duration"><?php echo $package['duration_months']; ?> Month<?php echo $package['duration_months'] > 1 ? 's' : ''; ?></div>
                            </div>
                            <div class="d-flex align-items-center">
                                <div class="package-price me-3">Rs <?php echo number_format($package['discounted_price'], 2); ?></div>
                                <i class="bi bi-check-circle-fill package-check"></i>
                            </div>
                        </div>
                    </label>
                    <?php endforeach; ?>
                </div>

                <!-- Payment Information -->
                <div class="section-header mt-4">
                    <i class="bi bi-credit-card"></i>
                    <h5>Payment Information</h5>
                </div>

                <div class="row mb-3">
                    <div class="col-md-6 mb-3">
                        <label for="paymentMethod" class="form-label">
                            Payment Method<span class="required-star">*</span>
                        </label>
                        <select class="form-select" id="paymentMethod" name="paymentMethod" required>
                            <option value="bank_transfer" selected>Bank Transfer</option>
                            <option value="card_payment">Card Payment (Offline)</option>
                            <option value="cash">Cash Payment</option>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="amountPaid" class="form-label">
                            Amount Paid (Rs)<span class="required-star">*</span>
                        </label>
                        <input type="number" class="form-control" id="amountPaid" name="amountPaid" 
                               step="0.01" min="0" readonly required>
                        <small class="text-muted">Auto-filled from selected package</small>
                    </div>
                </div>

                <div class="mb-4">
                    <label class="form-label">
                        Payment Status<span class="required-star">*</span>
                    </label>
                    <div class="payment-status-option">
                        <input type="radio" name="paymentStatus" id="statusPaid" value="paid" checked>
                        <label for="statusPaid" style="cursor: pointer; margin: 0;">
                            <i class="bi bi-check-circle-fill text-success"></i>
                            <strong>Already Paid</strong> - Activate subscription immediately
                        </label>
                    </div>
                    <div class="payment-status-option">
                        <input type="radio" name="paymentStatus" id="statusPending" value="pending">
                        <label for="statusPending" style="cursor: pointer; margin: 0;">
                            <i class="bi bi-clock-fill text-warning"></i>
                            <strong>Awaiting Payment</strong> - Create as pending (activate later)
                        </label>
                    </div>
                </div>

                <!-- Bank Details (shown when "Already Paid" is selected) -->
                <div id="bankDetails">
                    <div class="row mb-3">
                        <div class="col-md-6 mb-3">
                            <label for="bankReference" class="form-label">Bank Reference / Transaction ID</label>
                            <input type="text" class="form-control" id="bankReference" name="bankReference" 
                                   placeholder="TXN123456789">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="depositorName" class="form-label">Depositor Name</label>
                            <input type="text" class="form-control" id="depositorName" name="depositorName">
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6 mb-3">
                            <label for="depositDate" class="form-label">Deposit Date</label>
                            <input type="date" class="form-control" id="depositDate" name="depositDate" 
                                   value="<?php echo date('Y-m-d'); ?>">
                        </div>
                    </div>
                </div>

                <!-- Admin Notes -->
                <div class="section-header mt-4">
                    <i class="bi bi-pencil-square"></i>
                    <h5>Admin Notes (Optional)</h5>
                </div>

                <div class="mb-4">
                    <textarea class="form-control" id="adminNotes" name="adminNotes" rows="3" 
                              placeholder="Add any notes about this enrollment (e.g., 'Called and confirmed payment', 'Bank: Sampath Bank')"></textarea>
                </div>

                <!-- Action Buttons -->
                <div class="d-flex justify-content-between align-items-center mt-5">
                    <button type="button" class="btn btn-reset" onclick="resetForm()">
                        <i class="bi bi-arrow-counterclockwise"></i> Reset Form
                    </button>
                    <button type="submit" class="btn btn-enroll">
                        <i class="bi bi-check-circle-fill"></i> Enroll Student
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-fill amount when package is selected
        document.querySelectorAll('input[name="packageId"]').forEach(radio => {
            radio.addEventListener('change', function() {
                const price = this.getAttribute('data-price');
                document.getElementById('amountPaid').value = price;
            });
        });

        // Show/hide bank details based on payment status
        document.querySelectorAll('input[name="paymentStatus"]').forEach(radio => {
            radio.addEventListener('change', function() {
                const bankDetails = document.getElementById('bankDetails');
                if (this.value === 'paid') {
                    bankDetails.style.display = 'block';
                } else {
                    bankDetails.style.display = 'none';
                }
            });
        });

        // Initialize - show bank details by default (since "Already Paid" is checked)
        document.getElementById('bankDetails').style.display = 'block';

        // Form submission
        document.getElementById('enrollForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            // Disable submit button
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> Processing...';

            // Get form data
            const formData = new FormData(this);

            try {
                const response = await fetch('api/enroll_student.php', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (result.success) {
                    showMessage('success', result.message);
                    setTimeout(() => {
                        window.location.href = 'subscriptions.php';
                    }, 2000);
                } else {
                    showMessage('error', result.message || 'Failed to enroll student');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            } catch (error) {
                console.error('Error:', error);
                showMessage('error', 'Network error. Please try again.');
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        });

        function showMessage(type, message) {
            const container = document.getElementById('messageContainer');
            const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
            const icon = type === 'success' ? 'check-circle-fill' : 'exclamation-triangle-fill';
            
            container.innerHTML = `
                <div class="alert ${alertClass} alert-custom alert-dismissible fade show" role="alert">
                    <i class="bi bi-${icon}"></i> ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            
            // Scroll to top
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }

        function resetForm() {
            if (confirm('Are you sure you want to reset the form? All entered data will be lost.')) {
                document.getElementById('enrollForm').reset();
                document.getElementById('amountPaid').value = '';
                document.getElementById('bankDetails').style.display = 'block';
            }
        }
    </script>
</body>
</html>
