<?php
// api/process_payment.php
// This script handles the payment slip submission via AJAX.

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') {
    echo json_encode(['success' => false, 'message' => 'Authentication required or not authorized.']);
    exit();
}

require_once '../config/database.php';
require_once '../vendor/autoload.php'; 
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$response = ['success' => false, 'message' => ''];
$student_id = $_SESSION['user_id'];
$student_email = $_SESSION['email'] ?? 'unknown@lms.com'; 

// --- START OF EMBEDDED EMAIL FUNCTION ---
function sendStudentPaymentReceivedEmail(PDO $pdo, int $enrollment_id, array $payment_data): bool {
    
    // 1. Fetch Necessary Data
    $sql = "
        SELECT
            u.full_name AS student_name,
            u.email AS student_email,
            c.course_name,
            b.batch_name
        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 student email.");
            return false;
        }

        $mail = new PHPMailer(true);

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

        // Recipients: Send TO THE STUDENT
        $mail->setFrom('bazithali95@gmail.com', 'Orinsto LMS Enrollment');
        $mail->addAddress($data['student_email'], $data['student_name']);

        // 3. Construct Email Content
        $subject = "✅ Payment Slip Received: {$data['course_name']} - Pending Approval";
        $body_content = "
            <p>Dear {$data['student_name']},</p>
            <p>We have successfully received your payment slip submission for the following enrollment. Your enrollment status has been updated to **'Payment Uploaded'** and is now awaiting administrator review.</p>
            
            <h3 style='color: #007bff; margin-top: 20px;'>Submission Details:</h3>
            <table style='border-collapse: collapse; width: 100%; border: 1px solid #ddd; font-size: 14px;'>
                <tr><td style='padding: 8px; border: 1px solid #ddd; font-weight: bold; width: 30%;'>Course/Batch:</td><td style='padding: 8px; border: 1px solid #ddd;'>{$data['course_name']} / {$data['batch_name']}</td></tr>
                <tr><td style='padding: 8px; border: 1px solid #ddd; font-weight: bold;'>Amount Submitted:</td><td style='padding: 8px; border: 1px solid #ddd; font-weight: bold; color: green;'>LKR " . number_format($payment_data['amount_paid'], 2) . "</td></tr>
                <tr><td style='padding: 8px; border: 1px solid #ddd; font-weight: bold;'>Bank Reference:</td><td style='padding: 8px; border: 1px solid #ddd;'>{$payment_data['slip_number']}</td></tr>
            </table>

            <p style='margin-top: 15px;'>The administrator will verify your slip and update your status to **'Enrolled'** soon. Please check your dashboard for updates.</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("Student Payment Received Notification failed for ID {$enrollment_id}. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}
// --- END OF EMBEDDED EMAIL FUNCTION ---

try {
    // 1. Validate and sanitize form data
    $enrollment_id = filter_var($_POST['enrollment_id'] ?? null, FILTER_VALIDATE_INT);
    $bank_name = trim($_POST['bank_name'] ?? '');
    $slip_number = trim($_POST['slip_number'] ?? '');
    $payment_amount = filter_var($_POST['amount_paid'] ?? null, FILTER_VALIDATE_FLOAT);
    $payment_date = trim($_POST['payment_date'] ?? '');

    if (!$enrollment_id || empty($bank_name) || empty($slip_number) || $payment_amount === false || empty($payment_date)) {
        throw new Exception("Please fill in all required fields correctly.");
    }
    
    // 2. Check enrollment status
    $stmt_check = $pdo->prepare("SELECT status FROM course_enrollments WHERE id = ? AND student_id = ?");
    $stmt_check->execute([$enrollment_id, $student_id]);
    $enrollment = $stmt_check->fetch(PDO::FETCH_ASSOC);

    if (!$enrollment || $enrollment['status'] !== 'pending') {
        throw new Exception("Payment for this enrollment has already been submitted or approved.");
    }

    // 3. Handle file upload
    if (!isset($_FILES['payment_slip']) || $_FILES['payment_slip']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception("File upload failed with error code: " . ($_FILES['payment_slip']['error'] ?? 'Unknown'));
    }

    $file_info = $_FILES['payment_slip'];
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf'];
    if (!in_array($file_info['type'], $allowed_types)) {
        throw new Exception("Invalid file type. Only images or PDF are allowed.");
    }

    $upload_dir = dirname(__DIR__) . '/public/uploads/slips/';
    if (!is_dir($upload_dir) && !mkdir($upload_dir, 0777, true)) {
        throw new Exception("Upload directory does not exist and could not be created.");
    }

    $file_extension = pathinfo($file_info['name'], PATHINFO_EXTENSION);
    $filename = "EID{$enrollment_id}_U{$student_id}_" . time() . ".{$file_extension}"; 
    $server_path = $upload_dir . $filename;
    
    $web_path = 'prototype/public/uploads/slips/' . $filename;

    if (!move_uploaded_file($file_info['tmp_name'], $server_path)) {
        throw new Exception("Failed to save the uploaded file. Check directory permissions on the server.");
    }

    // 4. Save to database using a transaction
    $pdo->beginTransaction();

    $stmt_insert = $pdo->prepare("
        INSERT INTO payments (enrollment_id, payment_reason, bank_name, slip_number, payment_amount, payment_date, slip_path, upload_date) 
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    $stmt_insert->execute([
        $enrollment_id, 'enrollment', $bank_name, $slip_number, $payment_amount, $payment_date, $web_path
    ]);

    $stmt_update = $pdo->prepare("
        UPDATE course_enrollments
        SET status = 'payment_uploaded'
        WHERE id = ? AND student_id = ?
    ");
    $stmt_update->execute([$enrollment_id, $student_id]);

    $pdo->commit();

    // 5. Send Student Confirmation Email
    $payment_data_for_email = [
        'bank_name' => $bank_name,
        'slip_number' => $slip_number,
        'amount_paid' => $payment_amount
    ];
    
    sendStudentPaymentReceivedEmail($pdo, $enrollment_id, $payment_data_for_email);

    $response['success'] = true;
    $response['message'] = "Payment slip uploaded successfully. A confirmation email has been sent, and your payment is now pending admin approval.";

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    $response['message'] = $e->getMessage();
    error_log("Payment Process Error: " . $e->getMessage());
}

echo json_encode($response);
exit();