<?php
/**
 * Manual Student Enrollment API
 * Handles admin-initiated student enrollments with bank transfer option
 */

header('Content-Type: application/json');
require_once '../config.php';

// Check admin authentication
try {
    $adminId = requireAdminAuth();
} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

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

// Start transaction
$pdo->beginTransaction();

try {
    // Get and validate input
    $email = trim($_POST['email'] ?? '');
    $fullName = trim($_POST['fullName'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $packageId = intval($_POST['packageId'] ?? 0);
    $paymentMethod = $_POST['paymentMethod'] ?? 'bank_transfer';
    $paymentStatus = $_POST['paymentStatus'] ?? 'paid'; // 'paid' or 'pending'
    $amountPaid = floatval($_POST['amountPaid'] ?? 0);
    $bankReference = trim($_POST['bankReference'] ?? '');
    $depositorName = trim($_POST['depositorName'] ?? '');
    $depositDate = $_POST['depositDate'] ?? date('Y-m-d');
    $adminNotes = trim($_POST['adminNotes'] ?? '');

    // Validate required fields
    if (empty($email) || empty($fullName) || $packageId <= 0 || $amountPaid <= 0) {
        throw new Exception('Please fill all required fields');
    }

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Invalid email address');
    }

    // Get package details
    $stmt = $pdo->prepare("SELECT * FROM subscription_packages WHERE id = ?");
    $stmt->execute([$packageId]);
    $package = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$package) {
        throw new Exception('Invalid package selected');
    }

    // Verify amount matches package price
    if (abs($amountPaid - $package['discounted_price']) > 0.01) {
        throw new Exception('Amount paid does not match package price');
    }

    // Check if user already exists
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND is_deleted = 0");
    $stmt->execute([$email]);
    $existingUser = $stmt->fetch(PDO::FETCH_ASSOC);

    $userId = null;
    $isNewUser = false;
    $tempPassword = null;

    if ($existingUser) {
        // User already exists
        $userId = $existingUser['id'];
        $userName = $existingUser['user_name'];
        
        // Check if user already has an active subscription
        $stmt = $pdo->prepare("
            SELECT * FROM user_subscriptions 
            WHERE user_id = ? AND status IN ('active', 'pending')
            ORDER BY end_date DESC LIMIT 1
        ");
        $stmt->execute([$userId]);
        $activeSubscription = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($activeSubscription && $activeSubscription['status'] === 'active') {
            // Will extend subscription from existing end date
            $extendingSubscription = true;
        }
    } else {
        // Create new user
        $isNewUser = true;
        
        // Generate username if not provided
        if (empty($username)) {
            $username = strstr($email, '@', true); // Get part before @
            $username = preg_replace('/[^a-zA-Z0-9]/', '', $username); // Remove special chars
            
            // Check if username exists, add number if needed
            $baseUsername = $username;
            $counter = 1;
            $stmt = $pdo->prepare("SELECT id FROM users WHERE user_name = ?");
            $stmt->execute([$username]);
            
            while ($stmt->fetch()) {
                $username = $baseUsername . $counter;
                $counter++;
                $stmt->execute([$username]);
            }
        }
        
        $userName = $username;
        
        // Generate temporary password
        $tempPassword = bin2hex(random_bytes(4)); // 8 character random password
        $passwordHash = password_hash($tempPassword, PASSWORD_DEFAULT);
        
        // Create user account
        $userLevel = ($paymentStatus === 'paid') ? 'pro' : 'registered';
        $isPro = ($paymentStatus === 'paid') ? 1 : 0;
        
        $stmt = $pdo->prepare("
            INSERT INTO users (
                email,
                user_name,
                full_name,
                password_hash,
                user_level,
                is_pro,
                is_verified,
                created_at
            ) VALUES (?, ?, ?, ?, ?, ?, 1, NOW())
        ");
        $stmt->execute([
            $email,
            $userName,
            $fullName,
            $passwordHash,
            $userLevel,
            $isPro
        ]);
        
        $userId = $pdo->lastInsertId();
    }

    // Calculate subscription dates
    $durationDays = $package['duration_months'] * 30;
    $subscriptionStatus = ($paymentStatus === 'paid') ? 'active' : 'pending';
    $startDate = null;
    $endDate = null;

    if ($paymentStatus === 'paid') {
        // Check if user has existing active subscription to extend from
        $stmt = $pdo->prepare("
            SELECT * FROM user_subscriptions 
            WHERE user_id = ? AND status = 'active'
            ORDER BY end_date DESC LIMIT 1
        ");
        $stmt->execute([$userId]);
        $existingSubscription = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($existingSubscription) {
            // Extend from existing subscription's end date
            $startDate = $existingSubscription['end_date'];
            $endDate = date('Y-m-d', strtotime($startDate . " + {$durationDays} days"));
        } else {
            // Create new subscription (first time)
            $startDate = date('Y-m-d');
            $endDate = date('Y-m-d', strtotime("+{$durationDays} days"));
        }
    }

    // Create subscription record
    $stmt = $pdo->prepare("
        INSERT INTO user_subscriptions (
            user_id,
            package_id,
            start_date,
            end_date,
            payment_method,
            amount_paid,
            status,
            created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    $stmt->execute([
        $userId,
        $packageId,
        $startDate,
        $endDate,
        $paymentMethod,
        $amountPaid,
        $subscriptionStatus
    ]);
    
    $subscriptionId = $pdo->lastInsertId();

    // Create payment request record
    $paymentRequestStatus = ($paymentStatus === 'paid') ? 'approved' : 'pending';
    $processedAt = ($paymentStatus === 'paid') ? date('Y-m-d H:i:s') : null;
    
    $stmt = $pdo->prepare("
        INSERT INTO payment_requests (
            subscription_id,
            user_id,
            package_id,
            amount,
            payment_method,
            bank_reference,
            depositor_name,
            deposit_date,
            status,
            admin_notes,
            processed_by,
            processed_at,
            created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    $stmt->execute([
        $subscriptionId,
        $userId,
        $packageId,
        $amountPaid,
        $paymentMethod,
        $bankReference,
        $depositorName,
        $depositDate,
        $paymentRequestStatus,
        "Manually enrolled by admin. " . $adminNotes,
        $adminId,
        $processedAt
    ]);

    // Update user to PRO (if payment is marked as paid)
    if ($paymentStatus === 'paid') {
        $stmt = $pdo->prepare("
            UPDATE users 
            SET user_level = 'pro',
                is_pro = 1,
                pro_expires_at = ?
            WHERE id = ?
        ");
        $stmt->execute([$endDate, $userId]);
    }

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

    // Send welcome email if new user
    if ($isNewUser && $tempPassword) {
        try {
            sendWelcomeEmail($email, $fullName, $userName, $tempPassword, $package, $endDate);
        } catch (Exception $e) {
            // Email failed but enrollment succeeded - log it
            error_log("Welcome email failed for user {$userId}: " . $e->getMessage());
        }
    }

    // Prepare success response
    $message = $isNewUser 
        ? "Student enrolled successfully! Welcome email sent to {$email}" 
        : "Subscription added for existing user {$userName}";

    if ($paymentStatus === 'pending') {
        $message .= " (Subscription pending - will activate when payment is confirmed)";
    }

    echo json_encode([
        'success' => true,
        'message' => $message,
        'data' => [
            'userId' => $userId,
            'userName' => $userName,
            'subscriptionId' => $subscriptionId,
            'isNewUser' => $isNewUser,
            'status' => $subscriptionStatus,
            'startDate' => $startDate,
            'endDate' => $endDate
        ]
    ]);

} catch (Exception $e) {
    // Rollback transaction on error
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

/**
 * Send welcome email to new user
 */
function sendWelcomeEmail($email, $fullName, $userName, $tempPassword, $package, $endDate) {
    $subject = "Welcome to ENSI - Your Pro Account is Ready! 🎓";
    
    $message = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
            .content { background: #f9fafb; padding: 30px; border-radius: 0 0 10px 10px; }
            .info-box { background: white; border-left: 4px solid #7c3aed; padding: 15px; margin: 20px 0; border-radius: 5px; }
            .credentials { background: #fff; border: 2px solid #e5e7eb; padding: 20px; border-radius: 8px; margin: 20px 0; }
            .button { display: inline-block; background: #7c3aed; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; margin: 20px 0; }
            .footer { text-align: center; color: #6b7280; margin-top: 30px; font-size: 14px; }
            .important { color: #ef4444; font-weight: bold; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h1>🎓 Welcome to ENSI!</h1>
                <p>Your Pro Account is Ready</p>
            </div>
            <div class='content'>
                <p>Hi <strong>" . htmlspecialchars($fullName) . "</strong>,</p>
                
                <p>Your ENSI Pro account has been created successfully! You can now access all premium features.</p>
                
                <div class='credentials'>
                    <h3 style='margin-top: 0; color: #7c3aed;'>📧 Login Details</h3>
                    <p><strong>Email:</strong> " . htmlspecialchars($email) . "</p>
                    <p><strong>Username:</strong> " . htmlspecialchars($userName) . "</p>
                    <p><strong>Temporary Password:</strong> <code style='background: #f3f4f6; padding: 5px 10px; border-radius: 3px; font-size: 16px;'>" . htmlspecialchars($tempPassword) . "</code></p>
                    <p class='important'>⚠️ You'll be asked to change your password on first login</p>
                </div>
                
                <div class='info-box'>
                    <h3 style='margin-top: 0; color: #7c3aed;'>📦 Your Subscription</h3>
                    <p><strong>Package:</strong> " . htmlspecialchars($package['package_name']) . "</p>
                    <p><strong>Duration:</strong> " . $package['duration_months'] . " Month" . ($package['duration_months'] > 1 ? 's' : '') . "</p>
                    <p><strong>Valid Until:</strong> " . date('F j, Y', strtotime($endDate)) . "</p>
                </div>
                
                <div style='text-align: center;'>
                    <a href='https://ensi.lk/login' class='button'>🚀 Login & Start Learning</a>
                </div>
                
                <div style='margin-top: 30px; padding: 20px; background: white; border-radius: 8px;'>
                    <h3 style='color: #7c3aed;'>✨ What's Next?</h3>
                    <ol>
                        <li>Login to your account using the credentials above</li>
                        <li>Change your temporary password to a secure one</li>
                        <li>Complete your profile setup</li>
                        <li>Start learning English with our premium content!</li>
                    </ol>
                </div>
                
                <p>If you have any questions or need help, please don't hesitate to contact us.</p>
                
                <p>Happy Learning! 📚</p>
                
                <p><strong>The ENSI Team</strong></p>
                
                <div class='footer'>
                    <p>© " . date('Y') . " ENSI - English Learning Platform</p>
                    <p>This email was sent because an admin created an account for you.</p>
                </div>
            </div>
        </div>
    </body>
    </html>
    ";
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: ENSI <noreply@ensi.lk>" . "\r\n";
    
    if (!mail($email, $subject, $message, $headers)) {
        throw new Exception("Failed to send email");
    }
}
