<?php
// enrollment_verification_logic.php
// This file handles the form submission logic for enrollment verification.
// It is included by index.php for POST requests only.
// NO HTML CONTENT HERE.

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

// Ensure user is logged in and has appropriate role
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';
// Using vendor autoloader is correct, assuming vendor/autoload.php is present
require_once 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// --- START OF EMBEDDED EMAIL FUNCTION (Decision Notification) ---
function sendEnrollmentDecisionEmail(array $student_data, string $decision, string $course_name, string $batch_name, string $details_message): bool {
    
    try {
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        // !!! REPLACE WITH YOUR SMTP CREDENTIALS !!!
        $mail->Username   = 'bazithali95@gmail.com'; 
        $mail->Password   = 'sqkt opow cvao fiac'; 
        // !!! END SMTP CONFIG !!!
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; 
        $mail->Port       = 587;
        
        $mail->setFrom('bazithali95@gmail.com', 'Orinsto LMS Administration');
        $mail->addAddress($student_data['email'], $student_data['full_name']);
        
        if ($decision === 'enrolled') {
            $subject = "🎉 Enrollment Approved: Welcome to {$course_name}!";
            $header_color = '#28a745'; // Green
        } else {
            $subject = "❗ Enrollment Update: {$course_name} - Action Required";
            $header_color = '#dc3545'; // Red
        }

        // Basic HTML structure for the email body
        $body_content = "
            <p>Dear " . htmlspecialchars($student_data['full_name']) . ",</p>
            <h3 style='color: {$header_color}; margin-top: 15px;'>Your enrollment request for " . htmlspecialchars($course_name) . " has been processed.</h3>
            
            <p><strong>Status:</strong> <span style='font-weight: bold; color: {$header_color};'>" . ucwords($decision) . "</span></p>
            <p><strong>Course/Batch:</strong> " . htmlspecialchars($course_name) . " / " . htmlspecialchars($batch_name) . "</p>
            
            <div style='padding: 10px; margin-top: 15px; border-radius: 4px; border: 1px solid #ddd; background-color: #f9f9f9;'>
                {$details_message}
            </div>

            <p style='margin-top: 25px;'>If you have any questions, please contact our support team.</p>
        ";
        
        $mail->Subject = $subject;
        $mail->isHTML(true);
        $mail->Body = $body_content;
        $mail->AltBody = strip_tags($body_content);

        $mail->send();
        return true;

    } catch (Exception $e) {
        error_log("Decision Email failed for EID {$student_data['enrollment_id']} ({$decision}). Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}
// --- END OF EMBEDDED EMAIL FUNCTION ---


$enrollment_id = filter_input(INPUT_POST, 'enrollment_id', FILTER_VALIDATE_INT);
$action = filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING);
$rejection_reason = trim(filter_input(INPUT_POST, 'rejection_reason', FILTER_SANITIZE_STRING));
$access_end_date = filter_input(INPUT_POST, 'access_end_date', FILTER_SANITIZE_STRING); 
// Ensure lifetime_access is an integer (0 or 1)
$lifetime_access = filter_var(filter_input(INPUT_POST, 'lifetime_access', FILTER_DEFAULT), FILTER_VALIDATE_INT, ['options' => ['default' => 0]]);


$message = '';
$is_error = false;
$student_id_to_notify = null; 
$notif_title = '';
$notif_message = '';

if (!$enrollment_id) {
    $message = "Invalid enrollment ID provided.";
    $is_error = true;
}

// 1. Fetch Enrollment Details FIRST (for pre-check and notification data)
if (!$is_error) {
    try {
        $sql_fetch = "
            SELECT
                ce.id AS enrollment_id, ce.status, ce.student_id, 
                s.full_name AS student_full_name, s.email AS student_email,
                c.course_name, b.batch_name
            FROM course_enrollments ce
            JOIN users s ON ce.student_id = s.id
            JOIN batches b ON ce.batch_id = b.id
            JOIN courses c ON b.course_id = c.id
            WHERE ce.id = ?
        ";
        
        $user_role = $_SESSION['user_role'];
        $user_id = $_SESSION['user_id'];

        // Apply instructor-specific authorization check
        if ($user_role === 'instructor') {
            $sql_fetch .= " AND b.instructor_id = ?";
            $params_fetch = [$enrollment_id, $user_id];
        } else {
            $params_fetch = [$enrollment_id];
        }

        $stmt_fetch = $pdo->prepare($sql_fetch);
        $stmt_fetch->execute($params_fetch);
        $enrollment = $stmt_fetch->fetch(PDO::FETCH_ASSOC);

        if (!$enrollment) {
            $message = "Enrollment request not found or you do not have permission to view it.";
            $is_error = true;
        } elseif ($enrollment['status'] === 'enrolled' || $enrollment['status'] === 'rejected') {
            // Already processed, prevent double action but allow the user to see the status
            $message = "This enrollment is already **" . strtoupper($enrollment['status']) . "**. No action was taken.";
            $is_error = true;
        } else {
            $student_id_to_notify = $enrollment['student_id'];
        }

    } catch (PDOException $e) {
        $message = "Database error fetching details: " . $e->getMessage();
        $is_error = true;
        error_log("Enrollment Detail Fetch Error: " . $e->getMessage());
    }
}

// 2. Handle Form Submission (Verification/Action)
if (!$is_error && $enrollment) {
    try {
        $new_status = '';
        $email_details = '';

        if ($action === 'approve') {
            $new_status = 'enrolled';
            
            // Validation for Limited Access (if not lifetime)
            if ($lifetime_access === 0 && (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $access_end_date) || strtotime($access_end_date) < time())) {
                $message = "Approval failed: Invalid or past access end date (YYYY-MM-DD) required for limited access.";
                $is_error = true;
            }

            if (!$is_error) {
                $message = "Enrollment successfully **APPROVED**. The student is now enrolled.";
                $notif_title = "✅ Enrollment Approved!";
                
                if ($lifetime_access === 1) {
                    $final_access_end_date = NULL;
                    $notif_message = "Congratulations! Your enrollment has been approved and you have been granted **LIFETIME ACCESS**. Welcome to the course!";
                    $email_details = "<p>Your payment has been verified and you have been granted **LIFETIME ACCESS** to the course materials. Congratulations! You can start learning immediately.</p>";
                } else {
                    $final_access_end_date = $access_end_date;
                    $next_payment_date = date('F d, Y', strtotime($access_end_date));
                    $notif_message = "Congratulations! Your enrollment has been approved. Your access is valid until **{$next_payment_date}**.";
                    $email_details = "<p>Your payment has been verified and your access is granted. Your access will expire on **{$next_payment_date}** unless a subsequent payment is made.</p>";
                }
            }
        } elseif ($action === 'reject') {
            $new_status = 'rejected';
            // Sanitize the reason again just in case, though the filter_input should cover it.
            $rejection_detail = !empty($rejection_reason) ? htmlspecialchars($rejection_reason) : 'No specific reason provided. Please contact administration for details.';

            $message = "Enrollment successfully **REJECTED**.";
            $notif_title = "❌ Enrollment Rejected";
            $notif_message = "Your course enrollment request has been rejected. Details: {$rejection_detail}";
            $email_details = "<p style='color: #dc3545; font-weight: bold;'>Reason for Rejection:</p><p style='padding: 10px; border: 1px dashed #dc3545; background-color: #fff0f0;'>" . $rejection_detail . "</p><p>Please contact our support team to resolve this issue and resubmit your payment proof.</p>";
            
            // Set final_access_end_date and lifetime_access for update below (though not strictly needed, it avoids an undefined variable)
            $final_access_end_date = NULL;
            $lifetime_access = 0; 
        } else {
            $message = "Invalid action specified.";
            $is_error = true;
        }

        // Perform Database Updates inside a transaction if no validation errors occurred
        if (!$is_error) {
            $pdo->beginTransaction();

            // 2a. Update Enrollment Status
            $sql_update = "UPDATE course_enrollments SET status = ? WHERE id = ?";
            $stmt_update = $pdo->prepare($sql_update);
            $stmt_update->execute([$new_status, $enrollment_id]);

            // 2b. Handle LMS Access (Approval Only)
            if ($action === 'approve') {
                
                // Use UPSERT logic for LMS Access
                $sql_access = "
                    INSERT INTO lms_access (enrollment_id, access_start_date, access_end_date, lifetime_access) 
                    VALUES (?, CURDATE(), ?, ?)
                    ON DUPLICATE KEY UPDATE
                        access_start_date = VALUES(access_start_date),
                        access_end_date = VALUES(access_end_date),
                        lifetime_access = VALUES(lifetime_access)
                ";
                $stmt_access = $pdo->prepare($sql_access);
                $stmt_access->execute([$enrollment_id, $final_access_end_date, $lifetime_access]);
            }
            // For rejection, we don't need to change lms_access, as it will be checked based on 'enrolled' status.

            // 2c. Create Internal Notification
            if (!empty($notif_title) && $student_id_to_notify) {
                $sql_notify = "INSERT INTO notifications (user_id, type, title, message, related_id) VALUES (?, 'enrollment', ?, ?, ?)";
                $stmt_notify = $pdo->prepare($sql_notify);
                $stmt_notify->execute([$student_id_to_notify, $notif_title, $notif_message, $enrollment_id]);
            }
            
            $pdo->commit();
            
            // 2d. Send Email Notification (Outside of transaction boundary to prevent holding lock)
            $student_info = [
                'full_name' => $enrollment['student_full_name'],
                'email' => $enrollment['student_email'],
                'enrollment_id' => $enrollment_id 
            ];
            
            $email_sent = sendEnrollmentDecisionEmail(
                $student_info, 
                $new_status, 
                $enrollment['course_name'], 
                $enrollment['batch_name'], 
                $email_details
            );
            
            if (!$email_sent) {
                $message .= " (Warning: Student email notification failed to send.)";
                error_log("Failed to send student decision email for EID: {$enrollment_id}");
            }
        }

    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $message = "Action error: " . $e->getMessage();
        $is_error = true;
        error_log("Enrollment Status Update Error: " . $e->getMessage());
    }
}

// 3. Redirect back to the enrollment verification page with a status message.

// Determine the type of message for the URL
$status_type = $is_error ? 'error' : 'success';

// URL-encode the message for safe passing through the URL
$redirect_message = urlencode($message);

// Redirect back to the review page for the same enrollment ID
$redirect_url = "index.php?page=enrollment_verification&enrollment_id={$enrollment_id}&{$status_type}={$redirect_message}";

header("Location: {$redirect_url}");
exit();

?>