<?php
// api/enroll_course.php - FINAL WORKING VERSION
// This script processes a student's request to enroll, inserts the record, and sends a confirmation email.

header('Content-Type: application/json');

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Ensure user is logged in and is a student
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || $_SESSION['user_role'] !== 'student') {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Authentication required or not authorized.']);
    exit();
}

require_once '../config/database.php';
require_once '../vendor/autoload.php'; // Composer autoloader

// >>> PHPMailer Class Imports <<<
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP; 

// >>> START OF EMBEDDED EMAIL FUNCTION <<<

/**
 * Sends an email notification based on the course enrollment status.
 * (EMBEDDED here since a separate file was not available)
 *
 * @param PDO $pdo The active database connection object.
 * @param int $enrollment_id The ID of the course_enrollments record.
 * @param string $email_type The type of email to send ('confirmation', 'approved', or 'rejected').
 * @return bool True on success, false on failure.
 */
function sendEnrollmentEmail(PDO $pdo, int $enrollment_id, string $email_type): bool {
    
    // NOTE: This function only handles 'confirmation' in this context, 
    // but the full logic is preserved for future use.

    // --- 1. Fetch Necessary Data ---
    $sql = "
        SELECT
            u.email AS student_email,
            u.full_name AS student_name,
            c.course_name,
            b.batch_name,
            b.start_date,
            b.fees
        FROM
            course_enrollments ce
        JOIN users u ON ce.student_id = u.id
        JOIN batches b ON ce.batch_id = b.id
        JOIN courses c ON b.course_id = c.id
        WHERE ce.id = ?;
    ";
    
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$enrollment_id]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$data) {
            error_log("Enrollment ID {$enrollment_id} not found for email.");
            return false;
        }

        $mail = new PHPMailer(true);

        // --- 2. Configure SMTP Settings ---
        $mail->SMTPDebug = 0; 
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'bazithali95@gmail.com'; 
        $mail->Password   = 'sqkt opow cvao fiac'; // Your App Password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; 
        $mail->Port       = 587;
        
        $mail->SMTPOptions = [
            'ssl' => ['verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true]
        ];

        // Recipients
        $mail->setFrom('bazithali95@gmail.com', 'Orinsto LMS Admin');
        $mail->addAddress($data['student_email'], $data['student_name']);
        
        // --- 3. Determine Subject and Body for Confirmation ---
        $subject = "Enrollment Confirmed: {$data['course_name']} - Pending Review";
        $body_content = "
            <p>Dear {$data['student_name']},</p>
            <p>Thank you for submitting your enrollment request for the following batch:</p>
            <ul>
                <li><strong>Course:</strong> {$data['course_name']}</li>
                <li><strong>Batch:</strong> {$data['batch_name']}</li>
                <li><strong>Start Date:</strong> " . date('M d, Y', strtotime($data['start_date'])) . "</li>
                <li><strong>Fees:</strong> LKR " . number_format($data['fees'], 2) . "</li>
            </ul>
            <p>Your request is currently **PENDING** review. Please proceed with the payment process to finalize your enrollment.</p>
        ";
        
        // --- 4. Construct and Send Email ---
        $mail->Subject = $subject;
        $mail->isHTML(true);
        $mail->Body = "
            <html>
            <body style='font-family: Arial, sans-serif; line-height: 1.6; color: #333;'>
                <div style='max-width: 600px; margin: 20px auto; padding: 20px; border: 1px solid #ddd; border-radius: 8px;'>
                    <h2 style='color: #007bff;'>" . strip_tags($subject) . "</h2>
                    {$body_content}
                    <p style='margin-top: 20px;'>Thank you for choosing Orinsto LMS!</p>
                </div>
            </body>
            </html>
        ";
        $mail->AltBody = strip_tags($body_content);

        $mail->send();
        return true;

    } catch (PDOException $e) {
        error_log("Enrollment Email DB Error: " . $e->getMessage());
        return false;
    } catch (Exception $e) {
        error_log("Enrollment Email failed for ID {$enrollment_id}. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}
// >>> END OF EMBEDDED EMAIL FUNCTION <<<


$input = json_decode(file_get_contents('php://input'), true);
$batch_id = filter_var($input['batch_id'] ?? null, FILTER_VALIDATE_INT);
$student_id = $_SESSION['user_id'];

$response = ['success' => false, 'message' => ''];

if (!$batch_id) {
    $response['message'] = "Invalid batch ID.";
    echo json_encode($response);
    exit();
}

try {
    // 1. CHECK FOR DUPLICATE ENROLLMENT
    $stmt = $pdo->prepare("SELECT id, status FROM course_enrollments WHERE student_id = ? AND batch_id = ?");
    $stmt->execute([$student_id, $batch_id]);
    $existing_enrollment = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($existing_enrollment) {
        // Handle existing enrollment logic
        $response['enrollment_id'] = $existing_enrollment['id'];
        
        if ($existing_enrollment['status'] === 'pending' || $existing_enrollment['status'] === 'payment_uploaded') {
            $response['message'] = "You have already started the enrollment process for this batch.";
        } elseif ($existing_enrollment['status'] === 'enrolled') {
            $response['message'] = "You are already enrolled in this batch!";
        }
        
        $response['success'] = false; 
        echo json_encode($response);
        exit();
    }

    // 2. INSERT THE NEW ENROLLMENT REQUEST
    $stmt = $pdo->prepare("INSERT INTO course_enrollments (student_id, batch_id, status) VALUES (?, ?, 'pending')");
    $stmt->execute([$student_id, $batch_id]);

    $new_enrollment_id = $pdo->lastInsertId();
    $response['enrollment_id'] = $new_enrollment_id; 

    // 3. SEND CONFIRMATION EMAIL
    $email_sent = sendEnrollmentEmail($pdo, $new_enrollment_id, 'confirmation');

    if ($email_sent) {
        $response['success'] = true;
        $response['message'] = "Enrollment request submitted successfully! A confirmation email has been sent. Please proceed to payment.";
    } else {
        // Log the failure but still return success for the enrollment itself
        error_log("Failed to send enrollment confirmation email for ID: {$new_enrollment_id}");
        $response['success'] = true;
        $response['message'] = "Enrollment request submitted successfully, but the confirmation email failed to send. Check your dashboard for the next steps.";
    }

} catch (PDOException $e) {
    $response['message'] = "Database error: Could not submit enrollment.";
    error_log("Enrollment PDOException: " . $e->getMessage());
} catch (Exception $e) {
    $response['message'] = "Server error: An unexpected error occurred.";
    error_log("Enrollment Exception: " . $e->getMessage());
}

echo json_encode($response);
exit();