<?php
// submit_monthly_payment_page.php
// This page displays a form for a student to upload a new MONTHLY payment slip against an active enrollment.

// Use output buffering to prevent header errors, especially with file uploads.
ob_start();

// Ensure session is started.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Redirect if not logged in OR not a student.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || $_SESSION['user_role'] !== 'student') {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';
require_once 'vendor/autoload.php'; // Include PHPMailer via Composer autoloader
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// --- 1. EMAIL NOTIFICATION FUNCTION ---
function sendPaymentConfirmationEmail(array $student_data, float $amount, string $course_name, string $batch_name, string $slip_number): 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');
        $mail->addAddress($student_data['email'], $student_data['full_name']);
        
        $mail->Subject = "✅ Payment Uploaded: Awaiting Verification for {$course_name}";
        $body_content = "
            <p>Dear {$student_data['full_name']},</p>
            <h3 style='color: #28a745; margin-top: 15px;'>Your monthly payment slip has been successfully uploaded!</h3>
            
            <p><strong>Course/Batch:</strong> {$course_name} / {$batch_name}</p>
            <p><strong>Amount:</strong> $" . number_format($amount, 2) . "</p>
            <p><strong>Slip/Reference Number:</strong> {$slip_number}</p>
            
            <div style='padding: 10px; margin-top: 15px; border-radius: 4px; border: 1px solid #ddd; background-color: #f9f9f9;'>
                <p>Your payment is now in the queue for **admin verification**. You will be notified once it has been approved. This usually takes up to 24 hours.</p>
            </div>

            <p style='margin-top: 25px;'>Thank you for your timely payment!</p>
        ";
        
        $mail->isHTML(true);
        $mail->Body = $body_content;
        $mail->AltBody = strip_tags($body_content);

        $mail->send();
        return true;

    } catch (Exception $e) {
        error_log("Payment confirmation email failed for user {$student_data['full_name']}. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}
// --- END OF EMAIL FUNCTION ---

$user_id = $_SESSION['user_id'] ?? null;
// We pass the enrollment_id and outstanding balance via GET
$enrollment_id = $_GET['enrollment_id'] ?? null;
$outstanding_balance_str = $_GET['outstanding_balance'] ?? '0.00';
$outstanding_balance = (float)$outstanding_balance_str;

$message = '';
$is_error = false;
$max_file_size = 5 * 1024 * 1024; // 5MB limit
$upload_dir = 'public/uploads/slips/'; // Directory relative to index.php

// --- 2. Validate and Fetch Enrollment Details ---
$enrollment_details = null; // Initialize to null
if (!$enrollment_id || $outstanding_balance <= 0) {
    $message = "Invalid enrollment ID or zero outstanding balance provided. Please check your payments dashboard.";
    $is_error = true;
} else {
    try {
        $stmt = $pdo->prepare("
            SELECT 
                ce.id, ce.student_id,
                u.full_name AS student_full_name, u.email AS student_email,
                b.batch_name, 
                c.course_name 
            FROM course_enrollments ce
            JOIN batches b ON ce.batch_id = b.id
            JOIN courses c ON b.course_id = c.id
            JOIN users u ON ce.student_id = u.id
            WHERE ce.id = ? AND ce.student_id = ? AND ce.status = 'enrolled'
        ");
        $stmt->execute([$enrollment_id, $user_id]);
        $enrollment_details = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$enrollment_details) {
            $message = "Enrollment not found, not active, or does not belong to you.";
            $is_error = true;
        }

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

// --- 3. Handle Form Submission (POST Request) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$is_error && $enrollment_details) {
    // Collect and sanitize POST data
    $payment_amount = filter_input(INPUT_POST, 'payment_amount', FILTER_VALIDATE_FLOAT);
    $bank_name = trim($_POST['bank_name'] ?? '');
    $slip_number = trim($_POST['slip_number'] ?? '');
    $payment_date = trim($_POST['payment_date'] ?? '');
    $month_due_date = trim($_POST['month_due_date'] ?? NULL); 

    // Basic Validation
    if ($payment_amount === false || $payment_amount <= 0 || $payment_amount > $outstanding_balance) {
        $message = "Invalid payment amount. Must be positive and not exceed the outstanding balance of $" . number_format($outstanding_balance, 2) . ".";
        $is_error = true;
    } elseif (empty($bank_name) || empty($slip_number) || empty($payment_date)) {
        $message = "Bank Name, Slip Number, and Payment Date are required fields.";
        $is_error = true;
    } elseif (!isset($_FILES['payment_slip']) || $_FILES['payment_slip']['error'] !== UPLOAD_ERR_OK) {
        $message = "Payment slip file upload failed or no file selected.";
        $is_error = true;
    } elseif ($_FILES['payment_slip']['size'] > $max_file_size) {
        $message = "File size exceeds the 5MB limit.";
        $is_error = true;
    } else {
        // --- File Upload Processing ---
        $file_info = pathinfo($_FILES['payment_slip']['name']);
        $extension = strtolower($file_info['extension']);
        $allowed_ext = ['jpg', 'jpeg', 'png', 'pdf'];

        if (!in_array($extension, $allowed_ext)) {
            $message = "Invalid file type. Only JPG, JPEG, PNG, and PDF are allowed.";
            $is_error = true;
        } else {
            $filename = "monthly_payment_{$enrollment_id}_" . time() . "." . $extension;
            $destination = $upload_dir . $filename;
            
            if (move_uploaded_file($_FILES['payment_slip']['tmp_name'], $destination)) {
                $slip_path_to_db = $destination; 

                // --- Database Insertion into monthly_payments ---
                try {
                    $pdo->beginTransaction();

                    $stmt_insert = $pdo->prepare("
                        INSERT INTO monthly_payments 
                            (enrollment_id, month_due_date, paid_amount, status, bank_name, slip_number, payment_date, slip_path, uploaded_at)
                        VALUES 
                            (?, ?, ?, 'uploaded', ?, ?, ?, ?, NOW())
                    ");

                    $success = $stmt_insert->execute([
                        $enrollment_id, 
                        $month_due_date, 
                        $payment_amount, 
                        $bank_name, 
                        $slip_number, 
                        $payment_date, 
                        $slip_path_to_db
                    ]);

                    if ($success) {
                        $pdo->commit();
                        
                        // --- SEND EMAIL NOTIFICATION ---
                        $student_info = [
                            'full_name' => $enrollment_details['student_full_name'],
                            'email' => $enrollment_details['student_email']
                        ];

                        sendPaymentConfirmationEmail(
                            $student_info, 
                            $payment_amount, 
                            $enrollment_details['course_name'], 
                            $enrollment_details['batch_name'],
                            $slip_number
                        );

                        // Set success message in session before redirect
                        $_SESSION['flash_message'] = "Payment of $$payment_amount uploaded successfully! It is now awaiting admin verification.";
                        $_SESSION['flash_type'] = 'success';
                        
                        // Redirect to payment dashboard after successful submission
                        header("Location: index.php?page=my_monthly_payments");
                        exit();
                    } else {
                        $pdo->rollBack();
                        $message = "Failed to record payment in the database.";
                        $is_error = true;
                        if (file_exists($destination)) { unlink($destination); }
                    }

                } catch (PDOException $e) {
                    $pdo->rollBack();
                    $message = "Database transaction failed: " . $e->getMessage();
                    $is_error = true;
                    error_log("Monthly Payment Submission DB Error: " . $e->getMessage());
                    if (file_exists($destination)) { unlink($destination); }
                }

            } else {
                $message = "Error moving the uploaded file. Check file permissions on the `$upload_dir` folder.";
                $is_error = true;
            }
        }
    }
}

// Store a flash message if there's an error on POST to display on the current page
if ($is_error && isset($message)) {
    $_SESSION['flash_message'] = $message;
    $_SESSION['flash_type'] = 'error';
    // No redirect here, just let the form re-render with the error message
}

?>

<div class="w-full max-w-xl mx-auto p-6 bg-white rounded-lg shadow-xl border border-blue-200">

    <div class="mb-6 pb-4 border-b border-gray-200">
        <h1 class="text-3xl font-extrabold text-gray-900 mb-2">Upload Course Payment Slip (Installment)</h1>
        <p class="text-gray-600">
            For **<?php echo htmlspecialchars($enrollment_details['course_name'] ?? 'Course'); ?> (<?php echo htmlspecialchars($enrollment_details['batch_name'] ?? 'Batch'); ?>)**
        </p>
    </div>

    <?php 
    // Display flash messages from session if they exist
    if (isset($_SESSION['flash_message'])): ?>
        <div class="mb-4 p-3 rounded-md 
            <?php echo ($_SESSION['flash_type'] === 'success') ? 'bg-green-100 text-green-700 border border-green-200' : 'bg-red-100 text-red-700 border border-red-200'; ?>">
            <p><?php echo $_SESSION['flash_message']; ?></p>
        </div>
        <?php
        // Clear the flash message after displaying it
        unset($_SESSION['flash_message']);
        unset($_SESSION['flash_type']);
    endif;
    ?>

    <?php if (!$enrollment_details): ?>
        <div class="mb-4 p-3 rounded-md bg-red-100 text-red-700 border border-red-200">
            <p class="font-bold">Error:</p>
            <p><?php echo htmlspecialchars($message); ?></p>
        </div>
    <?php endif; ?>

    <?php if ($enrollment_details): ?>
        <div class="mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-md">
            <p class="text-lg font-bold text-yellow-800">
                Outstanding Balance: $<span id="outstanding_balance_display"><?php echo number_format($outstanding_balance, 2); ?></span>
            </p>
            <p class="text-sm text-yellow-700 mt-1">
                You can pay any amount up to this balance. Once submitted, it will await admin verification.
            </p>
        </div>

        <form method="POST" enctype="multipart/form-data" action="index.php?page=submit_monthly_payment_page&enrollment_id=<?php echo htmlspecialchars($enrollment_id); ?>&outstanding_balance=<?php echo htmlspecialchars($outstanding_balance_str); ?>">

            <div class="mb-4">
                <label for="payment_amount" class="block text-sm font-medium text-gray-700 mb-1">Payment Amount ($)</label>
                <input type="number" step="0.01" min="1" max="<?php echo htmlspecialchars($outstanding_balance_str); ?>" id="payment_amount" name="payment_amount" 
                        value="<?php echo htmlspecialchars($outstanding_balance_str); ?>" required
                        class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-lg">
            </div>

            <div class="mb-4">
                <label for="payment_date" class="block text-sm font-medium text-gray-700 mb-1">Date Money was Paid (on the slip)</label>
                <input type="date" id="payment_date" name="payment_date" required
                        max="<?php echo date('Y-m-d'); ?>" 
                        class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-lg">
            </div>
            
            <div class="grid grid-cols-2 gap-4">
                <div class="mb-4 col-span-2 sm:col-span-1">
                    <label for="bank_name" class="block text-sm font-medium text-gray-700 mb-1">Bank Name</label>
                    <input type="text" id="bank_name" name="bank_name" required
                            class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
                </div>
                <div class="mb-4 col-span-2 sm:col-span-1">
                    <label for="slip_number" class="block text-sm font-medium text-gray-700 mb-1">Slip / Reference Number</label>
                    <input type="text" id="slip_number" name="slip_number" required
                            class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
                </div>
            </div>

            <div class="mb-6">
                <label for="payment_slip" class="block text-sm font-medium text-gray-700 mb-1">Upload Payment Slip / Receipt (Max 5MB)</label>
                <input type="file" id="payment_slip" name="payment_slip" accept=".jpg, .jpeg, .png, .pdf" required
                        class="mt-1 block w-full text-sm text-gray-500
                        file:mr-4 file:py-2 file:px-4
                        file:rounded-full file:border-0
                        file:text-sm file:font-semibold
                        file:bg-indigo-50 file:text-indigo-700
                        hover:file:bg-indigo-100">
                <p class="mt-1 text-xs text-gray-500">Allowed formats: JPG, PNG, PDF.</p>
            </div>
            
            <input type="hidden" name="month_due_date" value="">

            <div class="flex justify-end space-x-4">
                <a href="index.php?page=my_monthly_payments" class="px-6 py-3 border border-gray-300 text-gray-700 font-semibold rounded-md hover:bg-gray-100 transition duration-150">
                    Cancel
                </a>
                <button type="submit" class="px-6 py-3 bg-indigo-600 text-white font-bold text-lg rounded-md hover:bg-indigo-700 transition duration-300 shadow-lg">
                    Submit Payment for Verification
                </button>
            </div>
        </form>
    <?php endif; ?>
</div>

<script>
    // Set max date for payment date to today
    document.addEventListener('DOMContentLoaded', function() {
        const today = new Date().toISOString().split('T')[0];
        document.getElementById('payment_date').setAttribute('max', today);
    });
</script>

<?php ob_end_flush(); ?>