<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/User.php';

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

$input = json_decode(file_get_contents('php://input'), true) ?? [];
$courseId = (int)($input['course_id'] ?? 0);
$firstName = trim($input['first_name'] ?? ($input['name'] ?? ''));
$lastName = trim($input['last_name'] ?? '');
$email = trim($input['email'] ?? '');
$password = trim($input['password'] ?? '');

if (!$courseId) {
    echo json_encode(['success' => false, 'message' => 'Course ID is required']);
    exit;
}

$db = Database::getInstance();
$course = $db->get('SELECT id, title, price, currency FROM courses WHERE id = ? AND status = ?', [$courseId, 'published']);
if (!$course) {
    echo json_encode(['success' => false, 'message' => 'Course not found or not published']);
    exit;
}

$price = (float)$course['price'];

// Determine student id
session_start();
$studentId = getCurrentUserId();
$userModel = new User();

try {
    if (!$studentId) {
        if (empty($email)) throw new Exception('Email is required for guest checkout');

        $existing = $userModel->getByEmail($email);
        if ($existing) {
            $studentId = (int)$existing['id'];
            // if password provided, try to login the existing user
            if (!empty($password)) {
                try {
                    $userModel->login($email, $password);
                    $studentId = getCurrentUserId();
                } catch (Exception $e) {
                    // login failed; continue and just attach enrollment to existing account
                }
            }
        } else {
            // Create a guest account automatically using provided first/last names and password if given
            $fn = !empty($firstName) ? $firstName : 'Guest';
            $ln = !empty($lastName) ? $lastName : 'User';
            $username = preg_replace('/[^a-z0-9]+/i', '', strtolower($fn . substr($email, 0, 6))) . rand(100,9999);
            $generatedPassword = $password ?: bin2hex(random_bytes(6)); // 12 char

            $regData = [
                'first_name' => $fn,
                'last_name' => $ln,
                'username' => $username,
                'email' => $email,
                'password' => $generatedPassword
            ];

            $studentId = $userModel->register($regData);

            // mark active and verified
            $db->update('users', ['status' => 'active', 'email_verified' => 1, 'email_verification_token' => null], 'id = ?', [$studentId]);

            // log the user in (create session)
            try {
                $userModel->login($username, $generatedPassword);
            } catch (Exception $e) {
                // ignore login failures here
            }

            // send welcome email with instructions (do not include password in production; consider password-reset instead)
            $subject = 'Welcome to ' . APP_NAME;
            $message = "<h3>Welcome to " . APP_NAME . "</h3><p>An account was created for you with the email {$email}. You can log in to access your courses.</p>";
            sendEmail($email, $subject, $message);
        }
    }

    // Check existing enrollment
    $exists = $db->get('SELECT * FROM course_enrollments WHERE course_id = ? AND student_id = ?', [$courseId, $studentId]);
    if ($exists) {
        echo json_encode(['success' => true, 'message' => 'Already enrolled or pending', 'enrollment_id' => $exists['id']]);
        exit;
    }

    // Insert pending enrollment. For paid courses we set status 'suspended' and payment_status 'pending'
    $status = ($price > 0) ? 'suspended' : 'active';
    $paymentStatus = ($price > 0) ? 'pending' : 'free';

    $enrollmentData = [
        'course_id' => $courseId,
        'student_id' => $studentId,
        'status' => $status,
        'payment_status' => $paymentStatus,
        'payment_amount' => $price > 0 ? $price : 0.00,
        'payment_currency' => $course['currency'] ?? 'USD',
        'created_at' => date('Y-m-d H:i:s')
    ];

    $enrollmentId = $db->insert('course_enrollments', $enrollmentData);

    if (!$enrollmentId) throw new Exception('Failed to create enrollment');

    // Notify student via email
    $student = $db->get('SELECT id, email, first_name, last_name FROM users WHERE id = ?', [$studentId]);
    if ($student) {
        $subject = 'Enrollment initiated: ' . $course['title'];
        $msg = "<p>Hi " . htmlspecialchars($student['first_name']) . ",</p>";
        $msg .= "<p>Your enrollment for the course <strong>" . htmlspecialchars($course['title']) . "</strong> has been created";
        if ($price > 0) {
            $msg .= " and is pending payment of " . htmlspecialchars(number_format($price,2)) . " {$course['currency']}. Please complete payment to access the course.";
        } else {
            $msg .= " and is now active. You can access the course in your dashboard.";
        }
        $msg .= "</p><p><a href='" . APP_URL . "/lms/enrollments.php'>View your enrollments</a></p>";
        sendEmail($student['email'], $subject, $msg);
    }

    echo json_encode(['success' => true, 'enrollment_id' => $enrollmentId, 'amount' => $enrollmentData['payment_amount'], 'currency' => $enrollmentData['payment_currency'], 'user_id' => $studentId]);
    exit;

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    exit;
}
