<?php
// my_monthly_payments.php
// This page allows students to view their total course balance, total paid,
// remaining outstanding balance, and now links to a dedicated payment page.

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

$username = $_SESSION['username'] ?? 'Student';
$user_id = $_SESSION['user_id'] ?? null;

$course_payments_summary = []; // Grouped by enrollment, holds overall payment info
$message = '';
$is_error = false;

try {
    // 1. Fetch all ENROLLED batches for the student.
    // We now join: course_enrollments (ce) -> batches (b) -> courses (c) -> users (u for instructor)
    $stmt_enrollments = $pdo->prepare("
        SELECT
            ce.id AS enrollment_id,
            b.id AS batch_id,
            c.course_name,
            b.batch_name,
            b.fees AS course_total_fees, /* Fees are now on the batch */
            b.duration AS course_duration_text,
            b.start_date AS course_start_date,
            u.full_name AS instructor_name
        FROM course_enrollments ce
        JOIN batches b ON ce.batch_id = b.id /* New JOIN path */
        JOIN courses c ON b.course_id = c.id
        LEFT JOIN users u ON b.instructor_id = u.id /* Instructor is on the batch, use LEFT JOIN as instructor can be NULL */
        WHERE ce.student_id = ? AND ce.status = 'enrolled'
        ORDER BY b.start_date DESC, c.course_name ASC
    ");
    $stmt_enrollments->execute([$user_id]);
    $enrollments = $stmt_enrollments->fetchAll(PDO::FETCH_ASSOC);

    if (empty($enrollments)) {
        $message = "You are not currently enrolled in any active batches that require payments.";
    } else {
        foreach ($enrollments as $enrollment) {
            $enrollment_id = $enrollment['enrollment_id'];

            // 2. Fetch all payment records for this specific enrollment from monthly_payments
            // This query remains the same as it correctly references 'enrollment_id'
            $stmt_payments_received = $pdo->prepare("
                SELECT
                    mp.id AS monthly_payment_id,
                    mp.month_due_date,
                    mp.amount_due,
                    mp.status,
                    mp.paid_amount,
                    mp.bank_name,
                    mp.slip_number,
                    mp.payment_date,
                    mp.slip_path,
                    mp.uploaded_at,
                    mp.admin_notes,
                    mp.verified_at
                FROM monthly_payments mp
                WHERE mp.enrollment_id = ?
                ORDER BY mp.uploaded_at DESC, mp.payment_date DESC
            ");
            $stmt_payments_received->execute([$enrollment_id]);
            $payments_received = $stmt_payments_received->fetchAll(PDO::FETCH_ASSOC);
            
            // 3. Additionally, fetch the initial enrollment payment from the 'payments' table.
            // This payment counts towards the total course fees.
            $stmt_initial_payment = $pdo->prepare("
                SELECT
                    p.id AS monthly_payment_id, /* Alias to match structure for loop */
                    NULL AS month_due_date,
                    NULL AS amount_due,
                    'verified' AS status, /* Enrollment payment is implicitly verified upon enrollment */
                    p.payment_amount AS paid_amount,
                    p.bank_name,
                    p.slip_number,
                    p.payment_date,
                    p.slip_path,
                    p.upload_date AS uploaded_at,
                    NULL AS admin_notes,
                    p.upload_date AS verified_at
                FROM payments p
                WHERE p.enrollment_id = ?
                LIMIT 1
            ");
            $stmt_initial_payment->execute([$enrollment_id]);
            $initial_payment = $stmt_initial_payment->fetch(PDO::FETCH_ASSOC);

            // Add initial payment to the list if found
            if ($initial_payment) {
                // Ensure initial payment is treated as 'verified' and add a reason/note
                $initial_payment['admin_notes'] = 'Initial Enrollment Payment';
                
                // Prepend to show it first in the history
                array_unshift($payments_received, $initial_payment);
            }

            // 4. Calculate overall payment status for the course enrollment
            $total_paid = 0;
            // Iterate over combined payments (initial and monthly)
            foreach ($payments_received as $payment) {
                // Only count amounts for 'verified' status OR the initial enrollment payment
                if ($payment['status'] === 'verified' || $payment['admin_notes'] === 'Initial Enrollment Payment') {
                    $total_paid += $payment['paid_amount'];
                }
            }

            $balance_outstanding = $enrollment['course_total_fees'] - $total_paid;

            $course_payments_summary[] = [
                'enrollment_info' => $enrollment,
                'payments_received' => $payments_received,
                'summary' => [
                    'total_course_fees' => (float)($enrollment['course_total_fees']),
                    'total_paid' => (float)$total_paid,
                    'balance_outstanding' => (float)$balance_outstanding,
                    'can_upload_new_payment' => ($balance_outstanding > 0)
                ]
            ];
        }
    }

} catch (PDOException $e) {
    $message = "Database error fetching your payment details: " . $e->getMessage();
    $is_error = true;
    error_log("My Monthly Payments Fetch Error: " . $e->getMessage());
}

?>

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

    <div class="flex flex-col sm:flex-row justify-between items-center mb-8 pb-4 border-b border-gray-200">
        <h1 class="text-3xl font-extrabold text-gray-900 mb-2 sm:mb-0">
            My Payment Dashboard, <span class="text-blue-700"><?php echo htmlspecialchars($username); ?></span>!
        </h1>
        <div class="text-lg text-gray-700">
            Your Role: <span class="font-semibold capitalize text-blue-600">Student</span>
        </div>
    </div>

    <h2 class="text-2xl font-bold mb-6 text-gray-800">Your Course Payments</h2>

    <?php if (!empty($message) && !$is_error): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-blue-50 text-blue-700 border border-blue-200">
            <?php echo $message; ?>
            <p class="mt-2"><a href="index.php?page=student_dashboard" class="text-blue-600 hover:underline">Explore more courses</a></p>
        </div>
    <?php endif; ?>

    <?php if ($is_error): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-red-100 text-red-700 border border-red-200">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 gap-8">
        <?php if (!empty($course_payments_summary)): ?>
            <?php foreach ($course_payments_summary as $course_data):
                $enrollment_info = $course_data['enrollment_info'];
                $payments_received = $course_data['payments_received'];
                $summary = $course_data['summary'];
            ?>
                <div class="bg-white border border-gray-200 rounded-lg shadow-md overflow-hidden">
                    <div class="p-6 bg-blue-50 border-b border-blue-200">
                        <h3 class="text-xl font-bold text-blue-800 leading-tight">
                            Course: <?php echo htmlspecialchars($enrollment_info['course_name']); ?>
                            <span class="text-sm font-normal text-gray-600 ml-2">(<?php echo htmlspecialchars($enrollment_info['batch_name']); ?>)</span>
                        </h3>
                        <p class="text-sm text-gray-700 mt-2">
                            Instructor: <span class="font-semibold"><?php echo htmlspecialchars($enrollment_info['instructor_name'] ?? 'TBD'); ?></span> |
                            Fees: <span class="font-semibold">$<?php echo number_format($summary['total_course_fees'], 2); ?></span>
                        </p>
                        <div class="mt-4 p-4 rounded-md text-sm font-medium bg-white shadow-sm border border-gray-100">
                            Total Paid: <span class="font-bold text-green-700">$<?php echo number_format($summary['total_paid'], 2); ?></span> |
                            <span class="font-bold <?php echo ($summary['balance_outstanding'] > 0) ? 'text-red-700' : 'text-green-700'; ?>">
                                Balance Outstanding: $<?php echo number_format($summary['balance_outstanding'], 2); ?>
                            </span>
                        </div>
                        <?php if ($summary['can_upload_new_payment']): ?>
                            <div class="mt-4 text-center">
                                <a href="index.php?page=submit_monthly_payment_page&enrollment_id=<?php echo htmlspecialchars($enrollment_info['enrollment_id']); ?>&outstanding_balance=<?php echo htmlspecialchars(number_format($summary['balance_outstanding'], 2, '.', '')); ?>"
                                   class="inline-block px-6 py-3 bg-indigo-600 text-white font-bold text-lg rounded-md hover:bg-indigo-700 transition duration-300 shadow-lg">
                                    Make a New Payment
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="mt-4 text-center text-green-700 font-semibold">
                                Full course fees paid! 🎉
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="p-6">
                        <h4 class="text-lg font-bold text-gray-800 mb-4">Payment History:</h4>
                        <?php if (!empty($payments_received)): ?>
                            <div class="space-y-4">
                                <?php foreach ($payments_received as $payment):
                                    // Determine the payment status and message
                                    $status_display = htmlspecialchars($payment['status']);
                                    $payment_amount = $payment['paid_amount'];
                                    $payment_date = date('M d, Y', strtotime($payment['payment_date'] ?? $payment['uploaded_at']));
                                    
                                    $status_class = 'bg-gray-50 border-gray-200';
                                    $view_slip_button = '';
                                    $payment_info_text = '';

                                    switch ($payment['status']) {
                                        case 'uploaded':
                                            $status_class = 'bg-orange-50 border-orange-200';
                                            $payment_info_text = 'Payment uploaded on ' . date('M d, Y', strtotime($payment['uploaded_at'])) . ', pending admin verification.';
                                            $view_slip_button = '<button type="button" class="view-slip-btn px-4 py-2 bg-yellow-600 text-white text-sm font-semibold rounded-md hover:bg-yellow-700 transition duration-300" data-slip-path="' . htmlspecialchars($payment['slip_path']) . '">View Slip</button>';
                                            break;
                                        case 'verified':
                                            $status_class = 'bg-green-50 border-green-200';
                                            $verified_date = $payment['verified_at'] ? date('M d, Y', strtotime($payment['verified_at'])) : 'N/A';
                                            $payment_info_text = 'Payment verified on ' . $verified_date . '.';
                                            $view_slip_button = '<button type="button" class="view-slip-btn px-4 py-2 bg-green-600 text-white text-sm font-semibold rounded-md hover:bg-green-700 transition duration-300" data-slip-path="' . htmlspecialchars($payment['slip_path']) . '">View Slip</button>';
                                            break;
                                        case 'rejected':
                                            $status_class = 'bg-red-100 border-red-300';
                                            $verified_date = $payment['verified_at'] ? date('M d, Y', strtotime($payment['verified_at'])) : 'N/A';
                                            $payment_info_text = 'Payment rejected on ' . $verified_date . '. Reason: ' . htmlspecialchars($payment['admin_notes'] ?? 'No reason provided.');
                                            $view_slip_button = '<button type="button" class="view-slip-btn px-4 py-2 bg-red-600 text-white text-sm font-semibold rounded-md hover:bg-red-700 transition duration-300" data-slip-path="' . htmlspecialchars($payment['slip_path']) . '">View Slip</button>';
                                            break;
                                        default: // Initial enrollment payment from 'payments' table (implicitly verified)
                                            $status_display = 'Initial Enrollment';
                                            $status_class = 'bg-blue-100 border-blue-300';
                                            $payment_info_text = 'Initial course registration payment.';
                                            $view_slip_button = '<button type="button" class="view-slip-btn px-4 py-2 bg-blue-600 text-white text-sm font-semibold rounded-md hover:bg-blue-700 transition duration-300" data-slip-path="' . htmlspecialchars($payment['slip_path']) . '">View Slip</button>';
                                            break;
                                    }
                                ?>
                                    <div class="<?php echo $status_class; ?> border rounded-md p-4 flex flex-col sm:flex-row justify-between items-start sm:items-center">
                                        <div class="mb-2 sm:mb-0">
                                            <p class="font-semibold text-lg">
                                                Paid: <span class="text-blue-700">$<?php echo number_format($payment_amount, 2); ?></span>
                                                on <span class="text-blue-700"><?php echo htmlspecialchars($payment_date); ?></span>
                                            </p>
                                            <p class="text-gray-700 text-sm">
                                                Status: <span class="font-medium capitalize"><?php echo htmlspecialchars($status_display); ?></span>
                                            </p>
                                            <p class="text-gray-600 text-xs mt-1">
                                                <?php echo htmlspecialchars($payment_info_text); ?>
                                            </p>
                                            <?php if (!empty($payment['slip_number'])): ?>
                                                <p class="text-gray-600 text-xs mt-1">Slip No: <?php echo htmlspecialchars($payment['slip_number']); ?></p>
                                            <?php endif; ?>
                                        </div>
                                        <div class="mt-2 sm:mt-0">
                                            <?php echo $view_slip_button; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <p class="text-gray-600 italic text-center">No payment history found for this course yet. Make your first payment!</p>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="mb-6 p-4 rounded-md text-center text-lg bg-blue-50 text-blue-700 border border-blue-200 col-span-full">
                No enrolled courses requiring payments.
            </div>
        <?php endif; ?>
    </div>
</div>

<div id="viewSlipModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center hidden">
    <div class="bg-white p-6 rounded-lg shadow-xl w-full max-w-md">
        <h3 class="text-xl font-bold mb-4 text-center">Payment Slip</h3>
        <div class="text-center mb-4">
            <img id="slipImageView" src="" alt="Payment Slip" class="max-w-full h-auto rounded-md shadow-md mx-auto" onerror="this.onerror=null;this.src='https://placehold.co/300x200/cccccc/333333?text=Image+Not+Found';" />
        </div>
        <div class="flex justify-center">
            <button type="button" id="closeViewSlipModal" class="px-4 py-2 bg-gray-300 text-gray-800 rounded-md hover:bg-gray-400">Close</button>
        </div>
    </div>
</div>


<script>
    document.addEventListener('DOMContentLoaded', function() {
        const viewSlipModal = document.getElementById('viewSlipModal');
        const slipImageView = document.getElementById('slipImageView');
        const closeViewSlipModalButton = document.getElementById('closeViewSlipModal');

        // Show View Slip Modal
        document.querySelectorAll('.view-slip-btn').forEach(button => {
            button.addEventListener('click', function() {
                const slipPath = this.dataset.slipPath;
                if (slipPath) {
                    // Prepend '../' to the slip path, as the saved path in payments table is '../public/...'
                    // but the monthly_payments table seems to save a relative path, so let's adjust for safety.
                    const finalPath = slipPath.startsWith('../') ? slipPath : '../' + slipPath;
                    slipImageView.src = finalPath;
                    viewSlipModal.classList.remove('hidden');
                } else {
                    alert("No slip path available.");
                }
            });
        });

        // Close View Slip Modal
        if (closeViewSlipModalButton) {
            closeViewSlipModalButton.addEventListener('click', function() {
                viewSlipModal.classList.add('hidden');
                slipImageView.src = '';
            });
        }
    });
</script>