<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    echo '<p class="text-danger">Unauthorized access</p>';
    exit;
}

require_once '../config.php';
require_once '../ai/fee_balance.php';
$conn = getDBConnection();

// Get numeric student ID from request
$student_id = intval($_GET['student_id'] ?? 0);

if ($student_id <= 0) {
    echo '<p class="text-danger">Invalid student ID. Please provide a valid numeric ID.</p>';
    exit;
}

// Get student details using numeric ID
$studentQuery = "SELECT * FROM students WHERE id = ?";
$stmt = $conn->prepare($studentQuery);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$studentResult = $stmt->get_result();
$student = $studentResult->fetch_assoc();
$stmt->close();

if (!$student) {
    echo '<p class="text-danger">Student not found with ID: ' . htmlspecialchars($student_id) . '</p>';
    exit;
}

// Get outstanding fees for this student's class in the current academic year
$academicYear = function_exists('getAcademicYear') ? getAcademicYear() : date('Y');

$outstanding_fees = [];
foreach (rbcStudentFeeBreakdown($conn, $student_id, (string) $student['class'], $academicYear) as $row) {
    if ($row['remaining'] <= 0) {
        continue;
    }
    $outstanding_fees[] = [
        'id'            => $row['id'],
        'fee_type'      => $row['fee_type'],
        'amount'        => $row['amount'],
        'due_date'      => $row['due_date'],
        'academic_year' => $academicYear,
        'amount_paid'   => $row['paid'],
        'balance'       => $row['remaining'],
    ];
}

$fee_ids_string = implode(',', array_column($outstanding_fees, 'id'));
$outstandingTotal = array_sum(array_column($outstanding_fees, 'balance'));
$availableCredit = rbcAvailableCredit($conn, $student_id);

// Get all payments for this student
$paymentsQuery = "SELECT
    p.*,
    f.fee_type,
    f.amount as expected_amount,
    f.class_name
FROM payments p
JOIN fee_structures f ON p.fee_structure_id = f.id
WHERE p.student_id = ?
ORDER BY p.payment_date DESC";

$stmt = $conn->prepare($paymentsQuery);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$paymentsResult = $stmt->get_result();

$payments = [];
$totalPaid = 0;
$categoryTotals = [];

while ($row = $paymentsResult->fetch_assoc()) {
    $payments[] = $row;
    $totalPaid += $row['amount_paid'];

    // Calculate totals per category
    $category = $row['fee_type'];
    if (!isset($categoryTotals[$category])) {
        $categoryTotals[$category] = 0;
    }
    $categoryTotals[$category] += $row['amount_paid'];
}
$stmt->close();
$conn->close();
?>

<div class="container-fluid">
    <!-- Student Info -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card bg-light">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">
                            <strong>Student ID:</strong> <?php echo htmlspecialchars($student['student_id']); ?>
                        </div>
                        <div class="col-md-3">
                            <strong>Name:</strong> <?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?>
                        </div>
                        <div class="col-md-3">
                            <strong>Class:</strong> <?php echo htmlspecialchars($student['class']); ?>
                        </div>
                        <div class="col-md-3">
                            <strong>Total Paid:</strong> <span class="text-success"><?php echo formatCurrency($totalPaid); ?></span>
                        </div>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mt-3 pt-3 border-top flex-wrap gap-2">
                        <div>
                            <strong>Outstanding Fees:</strong>
                            <span class="text-danger">
                                <?php echo !empty($outstanding_fees) ? formatCurrency($outstandingTotal) : formatCurrency(0); ?>
                            </span>
                            <?php if ($availableCredit > 0.005): ?>
                            <span class="ms-3"><strong>Available Credit:</strong> <span class="text-success"><?php echo formatCurrency($availableCredit); ?></span></span>
                            <?php endif; ?>
                        </div>
                        <div class="d-flex align-items-center gap-1">
                            <button type="button" class="btn btn-primary btn-sm"
                                    onclick="addPaymentForStudent(<?php echo (int) $student_id; ?>)">
                                <i class="fas fa-plus me-1"></i>Add Payment
                            </button>
                            <?php if (!empty($outstanding_fees) && hasModule('online_payments')): ?>
                            <a href="payment_checkout.php?student_id=<?= (int)$student_id ?>&fee_ids=<?= htmlspecialchars($fee_ids_string) ?>"
                               class="btn btn-success btn-sm">
                               <i class="fas fa-mobile-alt me-1"></i>Pay Online
                            </a>
                            <?php endif; ?>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="issueCreditForStudent(<?php echo (int) $student_id; ?>)">
                                <i class="fas fa-hand-holding-usd me-1"></i>Issue Credit
                            </button>
                            <?php if ($availableCredit > 0.005 && $outstandingTotal > 0.005): ?>
                            <form method="POST" action="fees.php" class="d-inline" onsubmit="return confirm('Apply <?php echo htmlspecialchars(formatCurrency(min($availableCredit, $outstandingTotal))); ?> credit to this student\'s outstanding balance?');">
                                <input type="hidden" name="action" value="apply_credit">
                                <input type="hidden" name="student_id" value="<?php echo (int) $student_id; ?>">
                                <button type="submit" class="btn btn-outline-success btn-sm">
                                    <i class="fas fa-check-circle me-1"></i>Apply Credit
                                </button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Summary by Category -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0"><i class="fas fa-chart-pie me-2"></i>Summary by Fee Category</h6>
                </div>
                <div class="card-body">
                    <?php if (!empty($outstanding_fees)): ?>
                    <div class="alert alert-warning py-2 mb-3">
                        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                            <div>
                                <strong>Outstanding fee items:</strong>
                                <?php echo htmlspecialchars(implode(', ', array_map(static function ($fee) {
                                    return $fee['fee_type'];
                                }, $outstanding_fees))); ?>
                            </div>
                            <?php if (hasModule('online_payments')): ?>
                            <a href="payment_checkout.php?student_id=<?= (int)$student_id ?>&fee_ids=<?= htmlspecialchars($fee_ids_string) ?>"
                               class="btn btn-success btn-sm ms-1">
                               <i class="fas fa-mobile-alt me-1"></i>Pay Online
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    <div class="row">
                        <?php if (empty($categoryTotals)): ?>
                            <div class="col-12 text-center">No payments found for this student</div>
                        <?php else: ?>
                            <?php foreach ($categoryTotals as $category => $total): ?>
                            <div class="col-md-4 mb-2">
                                <div class="d-flex justify-content-between border-bottom pb-1">
                                    <span><?php echo htmlspecialchars($category); ?>:</span>
                                    <span class="fw-bold"><?php echo formatCurrency($total); ?></span>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    <hr>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="d-flex justify-content-between">
                                <span class="fw-bold">GRAND TOTAL:</span>
                                <span class="fw-bold text-success"><?php echo formatCurrency($totalPaid); ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Detailed Payments Table -->
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h6 class="mb-0"><i class="fas fa-list me-2"></i>All Payment Records</h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover" id="studentPaymentsTable">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Fee Category</th>
                                    <th>Expected Amount</th>
                                    <th>Amount Paid</th>
                                    <th>Payment Method</th>
                                    <th>Transaction ID</th>
                                    <th>Notes</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($payments)): ?>
                                <tr>
                                    <td colspan="8" class="text-center">No payment records found for this student</td>
                                </tr>
                                <?php else: ?>
                                    <?php foreach ($payments as $payment): ?>
                                    <tr>
                                        <td><?php echo date('d M Y', strtotime($payment['payment_date'])); ?></td>
                                        <td><?php echo htmlspecialchars($payment['fee_type']); ?></td>
                                        <td><?php echo formatCurrency($payment['expected_amount']); ?></td>
                                        <td class="text-success fw-bold"><?php echo formatCurrency($payment['amount_paid']); ?></td>
                                        <td><?php echo ucfirst($payment['payment_method']); ?></td>
                                        <td><?php echo htmlspecialchars($payment['transaction_id'] ?: '-'); ?></td>
                                        <td><?php echo htmlspecialchars($payment['notes'] ?: '-'); ?></td>
                                        <td>
                                            <div class="action-buttons">
                                                <button class="action-btn edit" onclick="editPayment(<?php echo $payment['id']; ?>)" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="action-btn delete" onclick="deletePayment(<?php echo $payment['id']; ?>)" title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        $('#studentPaymentsTable').DataTable({
            pageLength: 10,
            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            order: [[0, 'desc']],
            language: {
                emptyTable: "No payment records found"
            }
        });
    });
</script>
