<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/User.php';
require_once __DIR__ . '/../../classes/Cohort.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'] ?? '');
 $paymentPlan = trim($input['payment_plan'] ?? 'full');

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

$db = Database::getInstance();
$course = $db->get('SELECT id, title, price, currency, region 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
if (session_status() === PHP_SESSION_NONE) {
    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);
        }
    }

    $cohortId = null;
    try {
        $region = $_SESSION['region'] ?? ($course['region'] ?? DEFAULT_REGION);
        $cohortModel = new Cohort();
        $cohort = $cohortModel->findOpenCohortForEnrollment($courseId, $region);
        if ($cohort && !empty($cohort['id'])) {
            $cohortId = (int)$cohort['id'];
        }
    } catch (Exception $e) {
    }

    // 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';

    $paymentAmount = $price > 0 ? $price : 0.00;

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

    if ($cohortId !== null) {
        $enrollmentData['cohort_id'] = $cohortId;
    }

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

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

    // If paid course and installment plan selected, create up to 3 installments over <= 2 months
    if ($price > 0 && in_array($paymentPlan, ['installments_3', 'installments_5'], true)) {
        $total = $price;

        // New standard plan: 5 installments over 10 weeks (every 2 weeks).
        // We keep "installments_3" as an alias for backward compatibility.
        $per = round($total / 5, 2);

        $now = new DateTime();
        $currency = $course['currency'] ?? 'USD';
        $installments = [];

        for ($i = 1; $i <= 5; $i++) {
            if ($i < 5) {
                $amount = $per;
            } else {
                // Last installment absorbs any rounding difference so that the
                // total equals the original course price.
                $amount = $total - ($per * 4);
                if ($amount < 0) {
                    $amount = max(0, $amount);
                }
                $amount = round($amount, 2);
            }

            $due = (clone $now)->modify('+' . (14 * ($i - 1)) . ' days');

            $installments[] = [
                'no' => $i,
                'amount' => $amount,
                'due' => $due->format('Y-m-d H:i:s'),
            ];
        }

        foreach ($installments as $inst) {
            if ($inst['amount'] <= 0) {
                continue;
            }
            $db->insert('enrollment_installments', [
                'enrollment_id' => $enrollmentId,
                'installment_no' => $inst['no'],
                'amount' => $inst['amount'],
                'currency' => $currency,
                'due_date' => $inst['due'],
            ]);
        }

        // Update enrollment to expect first installment amount
        $firstAmount = $installments[0]['amount'];
        $db->update('course_enrollments', [
            'payment_amount' => $firstAmount,
        ], 'id = ?', [$enrollmentId]);

        $enrollmentData['payment_amount'] = $firstAmount;
    }

    // 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,
        'payment_plan' => $paymentPlan,
    ]);
    exit;

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