<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);

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

if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

// Role-based access control
$allowed_roles = ['admin', 'accountant', 'cashier'];

if (!in_array($_SESSION['role'], $allowed_roles)) {
    header('Location: dashboard.php?error=access_denied');
    exit;
}

require_once 'config.php';
require_once 'includes/canteen_helpers.php';
require_once 'lib/academic_period.php';
require_once 'includes/payment_helpers.php';
require_once 'ai/fee_balance.php';
$conn = getDBConnection();

// Load active classes for dropdowns
$classes_list = [];
$classRes = $conn->query("SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name");
if ($classRes) {
    while ($row = $classRes->fetch_assoc()) $classes_list[] = $row['class_name'];
}

// Handle POST form submissions
$message = '';
$messageType = '';

// Add Fee Structure
if (isset($_POST['action']) && $_POST['action'] === 'add_structure') {
    $class_name    = trim((string) ($_POST['class_name']    ?? ''));
    $fee_type      = trim((string) ($_POST['fee_type']      ?? ''));
    $term          = trim((string) ($_POST['term']          ?? ''));
    $amount        = floatval($_POST['amount'] ?? 0);
    $due_date      = trim((string) ($_POST['due_date']      ?? ''));
    $academic_year = trim((string) ($_POST['academic_year'] ?? getAcademicYear()));

    if (empty($class_name) || empty($fee_type) || empty($term) || $amount <= 0 || empty($due_date)) {
        $message = 'Please fill all required fields';
        $messageType = 'danger';
    } else {
        // Set default due date if empty
        if (empty($due_date)) {
            $due_date = date('Y-m-d', strtotime('+30 days'));
        }
        
        $billing_frequency = preg_match('/feeding|canteen|meal/i', $fee_type) ? 'recurring_weekly' : 'termly';
        $stmt = $conn->prepare("INSERT INTO fee_structures (class_name, fee_type, term, billing_frequency, amount, due_date, academic_year) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssdss", $class_name, $fee_type, $term, $billing_frequency, $amount, $due_date, $academic_year);

        if ($stmt->execute()) {
            $message = 'Fee structure added successfully!';
            $messageType = 'success';
        } else {
            $message = 'Failed to add fee structure: ' . $stmt->error;
            $messageType = 'danger';
        }
        $stmt->close();
    }
}

// Record Payment
if (isset($_POST['action']) && $_POST['action'] === 'add_payment') {
    $student_id = intval($_POST['student_id'] ?? 0);
    $fee_structure_id = intval($_POST['fee_structure_id'] ?? 0);
    $amount_paid = floatval($_POST['amount_paid'] ?? 0);
    $payment_date   = trim((string) ($_POST['payment_date']   ?? date('Y-m-d')));
    $payment_method = trim((string) ($_POST['payment_method'] ?? 'cash'));
    $transaction_id = trim((string) ($_POST['transaction_id'] ?? ''));
    $notes          = trim((string) ($_POST['notes']          ?? ''));
    $weeks_covered  = max(1, intval($_POST['weeks_covered'] ?? 1));

    if ($student_id <= 0 || $fee_structure_id <= 0 || $amount_paid <= 0 || empty($payment_date)) {
        $message = 'Please fill all required fields';
        $messageType = 'danger';
    } else {
        // Coupon handling
        $coupon_id       = (int) ($_POST['coupon_id'] ?? 0) ?: null;
        $discount_amount = floatval($_POST['discount_amount'] ?? 0);
        $original_amount = $coupon_id ? floatval($_POST['original_amount'] ?? $amount_paid) : null;

        // Start transaction
        $conn->begin_transaction();

        try {
            // Insert payment record (with optional coupon fields)
            $stmt = $conn->prepare("INSERT INTO payments (student_id, fee_structure_id, amount_paid, payment_date, payment_method, transaction_id, notes, coupon_id, discount_amount, original_amount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("iidssssidd", $student_id, $fee_structure_id, $amount_paid, $payment_date, $payment_method, $transaction_id, $notes, $coupon_id, $discount_amount, $original_amount);
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to insert payment: " . $stmt->error);
            }
            
            $payment_id = $stmt->insert_id;

            // Record coupon usage and increment counter
            if ($coupon_id && $payment_id) {
                $cu = $conn->prepare("INSERT INTO coupon_usages (coupon_id, student_id, payment_id, original_amount, discount_amount, final_amount) VALUES (?,?,?,?,?,?)");
                $orig = $original_amount ?? $amount_paid;
                $cu->bind_param('iiiddd', $coupon_id, $student_id, $payment_id, $orig, $discount_amount, $amount_paid);
                $cu->execute();
                $cu->close();
                $upd = $conn->prepare("UPDATE coupons SET times_used = times_used + 1 WHERE id = ?");
                $upd->bind_param('i', $coupon_id);
                $upd->execute();
                $upd->close();
            }

            // Get student and fee details for SMS
            $detailsQuery = "SELECT 
                s.first_name, 
                s.last_name, 
                s.father_name AS parent_name, 
                s.father_phone AS phone,
                f.fee_type,
                f.amount as total_fee_amount
            FROM students s
            JOIN fee_structures f ON f.id = ?
            WHERE s.id = ?";
            
            $detailsStmt = $conn->prepare($detailsQuery);
            $detailsStmt->bind_param("ii", $fee_structure_id, $student_id);
            $detailsStmt->execute();
            $detailsResult = $detailsStmt->get_result();
            
            if ($detailsRow = $detailsResult->fetch_assoc()) {
                $student_Name = $detailsRow['first_name'] . ' ' . $detailsRow['last_name'];
                $parent_name = $detailsRow['parent_name'] ?? 'Parent';
                $phone = $detailsRow['phone'] ?? '';
                $fee_type = $detailsRow['fee_type'] ?? 'Fee';
                
                // Format amount in Ghana Cedi
                $formatted_amount = formatCurrency($amount_paid);
                
                // Check if this is a feeding fee payment
                if (strtolower($fee_type) == 'feeding fee') {
                    $per_week_amount = $amount_paid / $weeks_covered;

                    // Anchor to Monday of the payment week, then iterate forward
                    $anchor = new DateTime($payment_date);
                    $anchor->modify('monday this week');

                    $weekStmt = $conn->prepare(
                        "INSERT INTO weekly_feeding_payments
                         (student_id, payment_id, week_start_date, week_end_date, amount_paid, weeks_covered, sms_sent)
                         VALUES (?, ?, ?, ?, ?, ?, FALSE)"
                    );

                    $first_start = '';
                    $last_end    = '';

                    for ($w = 0; $w < $weeks_covered; $w++) {
                        $ws = clone $anchor;
                        $ws->modify("+{$w} weeks");
                        $we = clone $ws;
                        $we->modify('+4 days'); // Friday

                        $ws_str = $ws->format('Y-m-d');
                        $we_str = $we->format('Y-m-d');

                        if ($w === 0)               $first_start = $ws->format('d M Y');
                        if ($w === $weeks_covered - 1) $last_end  = $we->format('d M Y');

                        $weekStmt->bind_param("iissdi",
                            $student_id, $payment_id,
                            $ws_str, $we_str,
                            $per_week_amount, $weeks_covered
                        );
                        $weekStmt->execute();
                    }
                    $weekStmt->close();

                    // SMS covering the full range
                    if (!empty($phone)) {
                        if ($weeks_covered === 1) {
                            $sms_message = "Dear {$parent_name}, Your payment of {$formatted_amount} for {$student_Name}'s feeding fee ({$first_start} – {$last_end}) has been received. Thank you - School Administration";
                        } else {
                            $sms_message = "Dear {$parent_name}, Your payment of {$formatted_amount} for {$student_Name}'s feeding fee covering {$weeks_covered} weeks ({$first_start} – {$last_end}) has been received. Thank you - School Administration";
                        }
                        sendSMS($phone, $sms_message);
                    }
                } else {
                    // Regular fee payment SMS
                    if (!empty($phone)) {
                        $sms_message = "Dear {$parent_name}, We have received the payment of {$formatted_amount} towards {$fee_type} for {$student_Name}. Thank you for your prompt payment. - School Administration";
                        sendSMS($phone, $sms_message);
                    }
                }
            }
            $detailsStmt->close();

            // Canteen Module — auto-generate entitlement for feeding fees
            if (function_exists('canteen_auto_generate_entitlement') && isset($fee_type)) {
                canteen_auto_generate_entitlement($student_id, $payment_id, $fee_type, $weeks_covered);
            }

            // Commit transaction
            $conn->commit();
            
            $message = 'Payment recorded successfully!';
            $messageType = 'success';
            
        } catch (Exception $e) {
            // Rollback transaction on error
            $conn->rollback();
            $message = 'Failed to record payment: ' . $e->getMessage();
            $messageType = 'danger';
        }
        
        $stmt->close();
    }
}

// Issue Credit — manual admin/bursar action, never auto-detected. Covers
// the "student was overpaid / a fee was corrected / withdrew mid-term"
// cases without trying to infer which scenario applies.
if (isset($_POST['action']) && $_POST['action'] === 'issue_credit') {
    $student_id = intval($_POST['student_id'] ?? 0);
    $amount     = floatval($_POST['amount'] ?? 0);
    $source     = trim((string) ($_POST['source'] ?? 'admin_adjustment'));
    $notes      = trim((string) ($_POST['notes'] ?? ''));

    if ($student_id <= 0 || $amount <= 0 || !in_array($source, ['overpayment', 'admin_adjustment', 'fee_correction'], true)) {
        $message = 'Enter a valid student, amount, and reason for the credit';
        $messageType = 'danger';
    } else {
        $stmt = $conn->prepare(
            "INSERT INTO student_fee_credits (student_id, amount, source, status, notes) VALUES (?, ?, ?, 'available', ?)"
        );
        $stmt->bind_param('idss', $student_id, $amount, $source, $notes);
        if ($stmt->execute()) {
            $message = 'Credit of ' . formatCurrency($amount) . ' issued successfully.';
            $messageType = 'success';
        } else {
            $message = 'Failed to issue credit: ' . $stmt->error;
            $messageType = 'danger';
        }
        $stmt->close();
    }
}

// Apply Credit — consumes available student_fee_credits against this
// student's current outstanding balance. Explicit one-click action rather
// than silently netting credit into every future payment across five
// different entry points (single/bulk/both checkouts/both webhooks) —
// keeps the receipt trail auditable ("why did this show GHS 250 instead
// of GHS 300?"). Splits proportionally by each item's remaining balance
// (same engine as bulk payment), consumes credit rows oldest-first, and
// only partially consumes the newest-touched row if the credit exceeds
// what's actually owed right now.
if (isset($_POST['action']) && $_POST['action'] === 'apply_credit') {
    $student_id = intval($_POST['student_id'] ?? 0);

    if ($student_id <= 0) {
        $message = 'Invalid student.';
        $messageType = 'danger';
    } else {
        $conn->begin_transaction();
        try {
            $stuStmt = $conn->prepare("SELECT class FROM students WHERE id = ?");
            $stuStmt->bind_param('i', $student_id);
            $stuStmt->execute();
            $stu = $stuStmt->get_result()->fetch_assoc();
            $stuStmt->close();
            if (!$stu) {
                throw new Exception('Student not found.');
            }

            $academic_year = getAcademicYear();
            $outstandingWeights = [];
            $outstandingFeeTypes = [];
            foreach (rbcStudentFeeBreakdown($conn, $student_id, (string) $stu['class'], $academic_year) as $row) {
                if ($row['remaining'] > 0.005) {
                    $outstandingWeights[$row['id']] = $row['remaining'];
                    $outstandingFeeTypes[$row['id']] = $row['fee_type'];
                }
            }
            $totalOutstanding = array_sum($outstandingWeights);

            $creditStmt = $conn->prepare(
                "SELECT id, amount FROM student_fee_credits WHERE student_id = ? AND status = 'available' ORDER BY created_at ASC FOR UPDATE"
            );
            $creditStmt->bind_param('i', $student_id);
            $creditStmt->execute();
            $creditRows = $creditStmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $creditStmt->close();
            $totalCredit = array_sum(array_column($creditRows, 'amount'));

            if ($totalOutstanding <= 0) {
                throw new Exception('This student has no outstanding balance to apply credit against.');
            }
            if ($totalCredit <= 0) {
                throw new Exception('This student has no available credit.');
            }

            $amountToApply = min($totalCredit, $totalOutstanding);
            $feeIds = array_keys($outstandingWeights);
            $shares = proportionalPaymentShares($feeIds, $outstandingWeights, $amountToApply);

            $payStmt = $conn->prepare(
                "INSERT INTO payments (student_id, fee_structure_id, amount_paid, payment_date, payment_method, notes, recorded_via)
                 VALUES (?, ?, ?, NOW(), 'credit', ?, 'bulk')"
            );
            $noteText = 'Credit applied to balance';
            foreach ($feeIds as $index => $feeId) {
                $amt = $shares[$index];
                $payStmt->bind_param('iids', $student_id, $feeId, $amt, $noteText);
                $payStmt->execute();
                $paymentId = $payStmt->insert_id;

                $feeType = $outstandingFeeTypes[$feeId] ?? '';
                if ($feeType !== '' && function_exists('canteen_auto_generate_entitlement') && preg_match('/feeding|canteen|meal/i', $feeType)) {
                    canteen_auto_generate_entitlement($student_id, $paymentId, $feeType);
                }
            }
            $payStmt->close();

            // Consume credit rows oldest-first until $amountToApply is exhausted;
            // the row that only gets partially used keeps the remainder available.
            $remainingToConsume = $amountToApply;
            foreach ($creditRows as $credit) {
                if ($remainingToConsume <= 0.001) {
                    break;
                }
                $creditAmount = (float) $credit['amount'];
                if ($creditAmount <= $remainingToConsume + 0.001) {
                    $upd = $conn->prepare("UPDATE student_fee_credits SET status = 'applied' WHERE id = ?");
                    $upd->bind_param('i', $credit['id']);
                    $upd->execute();
                    $upd->close();
                    $remainingToConsume -= $creditAmount;
                } else {
                    $newAmount = $creditAmount - $remainingToConsume;
                    $upd = $conn->prepare("UPDATE student_fee_credits SET amount = ? WHERE id = ?");
                    $upd->bind_param('di', $newAmount, $credit['id']);
                    $upd->execute();
                    $upd->close();
                    $remainingToConsume = 0;
                }
            }

            $conn->commit();
            $message = formatCurrency($amountToApply) . ' credit applied to outstanding balance.';
            $messageType = 'success';
        } catch (Throwable $e) {
            $conn->rollback();
            $message = 'Failed to apply credit: ' . $e->getMessage();
            $messageType = 'danger';
        }
    }
}

// Bulk Payment (2+ fee items for one student in a single transaction)
if (isset($_POST['action']) && $_POST['action'] === 'add_bulk_payment') {
    $student_id     = intval($_POST['student_id'] ?? 0);
    $fee_ids        = array_values(array_unique(array_filter(array_map('intval', (array) ($_POST['fee_structure_ids'] ?? [])))));
    $total_amount   = floatval($_POST['total_amount'] ?? 0);
    $payment_date   = trim((string) ($_POST['payment_date'] ?? date('Y-m-d')));
    $payment_method = trim((string) ($_POST['payment_method'] ?? 'cash'));
    $transaction_id = trim((string) ($_POST['transaction_id'] ?? ''));
    $notes          = trim((string) ($_POST['notes'] ?? ''));
    $weeks_covered  = max(1, intval($_POST['weeks_covered'] ?? 1));

    if ($student_id <= 0 || count($fee_ids) < 2 || $total_amount <= 0 || empty($payment_date)) {
        $message = 'Select at least two fee items and enter a valid total amount';
        $messageType = 'danger';
    } else {
        $conn->begin_transaction();
        try {
            $stuStmt = $conn->prepare("SELECT first_name, last_name, class, father_name, father_phone, mother_phone FROM students WHERE id = ?");
            $stuStmt->bind_param('i', $student_id);
            $stuStmt->execute();
            $stu = $stuStmt->get_result()->fetch_assoc();
            $stuStmt->close();
            if (!$stu) {
                throw new Exception('Student not found.');
            }

            $academic_year = getAcademicYear();
            $term          = getCurrentTerm();

            // Weight the split by each item's own outstanding remaining
            // balance (not its sticker amount) — the bursar is looking at
            // exactly these remaining figures on screen, so if they enter
            // the combined total unchanged, each item should be marked paid
            // in full, not skewed by how much of a *different* item was
            // already paid before today. See proportionalPaymentShares().
            $details = [];
            $weights = [];
            foreach (rbcStudentFeeBreakdown($conn, $student_id, (string) $stu['class'], $academic_year) as $row) {
                if (in_array($row['id'], $fee_ids, true)) {
                    $details[$row['id']] = ['fee_type' => $row['fee_type']];
                    $weights[$row['id']] = $row['remaining'];
                }
            }
            $shares = proportionalPaymentShares($fee_ids, $weights, $total_amount);

            $initiated_by = (int) ($_SESSION['user_id'] ?? 0);
            $batchStmt = $conn->prepare(
                "INSERT INTO bulk_payment_batches
                 (student_id, academic_year, term, payment_channel, total_amount, status, initiated_by, completed_at)
                 VALUES (?, ?, ?, 'cash', ?, 'completed', ?, NOW())"
            );
            $batchStmt->bind_param('issdi', $student_id, $academic_year, $term, $total_amount, $initiated_by);
            $batchStmt->execute();
            $batchId = (int) $batchStmt->insert_id;
            $batchStmt->close();

            $receiptNumber = 'BLK-' . $academic_year . '-' . str_pad((string) $batchId, 6, '0', STR_PAD_LEFT);
            $recStmt = $conn->prepare("UPDATE bulk_payment_batches SET receipt_number = ? WHERE id = ?");
            $recStmt->bind_param('si', $receiptNumber, $batchId);
            $recStmt->execute();
            $recStmt->close();

            $payStmt = $conn->prepare(
                "INSERT INTO payments
                 (student_id, fee_structure_id, amount_paid, payment_date, payment_method, transaction_id, notes, recorded_via, batch_id)
                 VALUES (?, ?, ?, ?, ?, ?, ?, 'bulk', ?)"
            );
            $paymentIdsByFee = [];
            foreach ($fee_ids as $index => $feeId) {
                $amountPaid = $shares[$index];
                $payStmt->bind_param('iidssssi', $student_id, $feeId, $amountPaid, $payment_date, $payment_method, $transaction_id, $notes, $batchId);
                $payStmt->execute();
                $paymentIdsByFee[$feeId] = $payStmt->insert_id;
            }
            $payStmt->close();

            foreach ($fee_ids as $feeId) {
                $feeType = $details[$feeId]['fee_type'] ?? '';
                if ($feeType !== '' && function_exists('canteen_auto_generate_entitlement') && preg_match('/feeding|canteen|meal/i', $feeType)) {
                    canteen_auto_generate_entitlement($student_id, $paymentIdsByFee[$feeId], $feeType, $weeks_covered);
                }
            }

            $conn->commit();

            $parent_name = $stu['father_name'] ?: 'Parent';
            $phone = $stu['father_phone'] ?: ($stu['mother_phone'] ?? '');
            if (!empty($phone)) {
                $studentFullName = trim($stu['first_name'] . ' ' . $stu['last_name']);
                $itemNames = array_map(static function ($d) { return $d['fee_type']; }, $details);
                $sms_message = "Dear {$parent_name}, Your payment of " . formatCurrency($total_amount) . " for {$studentFullName} covering " . implode(', ', $itemNames) . " has been received. Receipt: {$receiptNumber}. Thank you - School Administration";
                sendSMS($phone, $sms_message);
            }

            $message = 'Bulk payment recorded successfully! Receipt: ' . $receiptNumber;
            $messageType = 'success';
        } catch (Throwable $e) {
            $conn->rollback();
            $message = 'Failed to record bulk payment: ' . $e->getMessage();
            $messageType = 'danger';
        }
    }
}

// Update Payment
if (isset($_POST['action']) && $_POST['action'] === 'update_payment') {
    $payment_id = intval($_POST['payment_id'] ?? 0);
    $student_id = intval($_POST['student_id'] ?? 0);
    $fee_structure_id = intval($_POST['fee_structure_id'] ?? 0);
    $amount_paid = floatval($_POST['amount_paid'] ?? 0);
    $payment_date = trim((string) ($_POST['payment_date'] ?? ''));
    $payment_method = trim((string) ($_POST['payment_method'] ?? 'cash'));
    $transaction_id = trim((string) ($_POST['transaction_id'] ?? ''));
    $notes = trim((string) ($_POST['notes'] ?? ''));

    if ($payment_id <= 0 || $student_id <= 0 || $fee_structure_id <= 0 || $amount_paid <= 0 || empty($payment_date)) {
        $message = 'Please fill all required fields';
        $messageType = 'danger';
    } else {
        $stmt = $conn->prepare("UPDATE payments SET fee_structure_id = ?, amount_paid = ?, payment_date = ?, payment_method = ?, transaction_id = ?, notes = ? WHERE id = ?");
        $stmt->bind_param("iissssi", $fee_structure_id, $amount_paid, $payment_date, $payment_method, $transaction_id, $notes, $payment_id);

        if ($stmt->execute()) {
            $message = 'Payment updated successfully!';
            $messageType = 'success';
        } else {
            $message = 'Failed to update payment: ' . $stmt->error;
            $messageType = 'danger';
        }
        $stmt->close();
    }
}

// Delete Payment
if (isset($_GET['action']) && $_GET['action'] === 'delete_payment' && isset($_GET['id'])) {
    $payment_id = intval($_GET['id']);
    
    // Check if this is a feeding fee payment
    $checkStmt = $conn->prepare("SELECT id FROM weekly_feeding_payments WHERE payment_id = ?");
    $checkStmt->bind_param("i", $payment_id);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    
    if ($checkResult->num_rows > 0) {
        // Delete from weekly_feeding_payments first
        $deleteWeeklyStmt = $conn->prepare("DELETE FROM weekly_feeding_payments WHERE payment_id = ?");
        $deleteWeeklyStmt->bind_param("i", $payment_id);
        $deleteWeeklyStmt->execute();
        $deleteWeeklyStmt->close();
    }
    $checkStmt->close();
    
    // Delete the payment
    $stmt = $conn->prepare("DELETE FROM payments WHERE id = ?");
    $stmt->bind_param("i", $payment_id);

    if ($stmt->execute()) {
        $message = 'Payment deleted successfully!';
        $messageType = 'success';
    } else {
        $message = 'Failed to delete payment: ' . $stmt->error;
        $messageType = 'danger';
    }
    $stmt->close();
}

// Delete Fee Structure (via GET for simplicity)
if (isset($_GET['action']) && $_GET['action'] === 'delete_structure' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    
    // Check if there are payments linked
    $checkStmt = $conn->prepare("SELECT COUNT(*) as count FROM payments WHERE fee_structure_id = ?");
    $checkStmt->bind_param("i", $id);
    $checkStmt->execute();
    $result = $checkStmt->get_result();
    $row = $result->fetch_assoc();
    $checkStmt->close();
    
    if ($row['count'] > 0) {
        $message = 'Cannot delete fee structure. There are payments linked to it.';
        $messageType = 'danger';
    } else {
        $stmt = $conn->prepare("DELETE FROM fee_structures WHERE id = ?");
        $stmt->bind_param("i", $id);

        if ($stmt->execute()) {
            $message = 'Fee structure deleted successfully!';
            $messageType = 'success';
        } else {
            $message = 'Failed to delete fee structure: ' . $stmt->error;
            $messageType = 'danger';
        }
        $stmt->close();
    }
}

// Get all fee structures
$feeStructures = [];
$result = $conn->query("SELECT * FROM fee_structures ORDER BY id DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $feeStructures[] = $row;
    }
}

// Get all students for payment
$students = [];
$result = $conn->query("SELECT * FROM students WHERE status = 'active' ORDER BY first_name, last_name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $students[] = $row;
    }
}

// Get all payments grouped by student
$groupedPayments = [];
$result = $conn->query("SELECT 
    s.id as student_id, 
    s.student_id as student_code, 
    s.first_name,
    s.last_name,
    s.class,
    COUNT(p.id) as payment_count,
    SUM(p.amount_paid) as total_paid
FROM students s
LEFT JOIN payments p ON s.id = p.student_id
GROUP BY s.id
ORDER BY s.first_name, s.last_name");

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $groupedPayments[] = $row;
    }
}

// Connection left open intentionally — getAcademicYear() and canteen helpers
// use the same singleton from getDBConnection() during HTML rendering below.
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fees - EduTrack Pro</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="css/style.css">
    <style>
        .search-box {
            position: absolute;
            right:20px;
            max-width: 300px;
        }
        .search-box input {
            padding-left: 35px;
            border-radius: 20px;
            border: 1px solid #e0e6ed;
        }
        .search-box i {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #95a5a6;
        }
        .table-search {
            margin-bottom: 15px;
        }
        .payment-summary {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
        }
        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #dee2e6;
        }
        .summary-item:last-child {
            border-bottom: none;
            font-weight: bold;
        }
        .dataTables_filter {
            margin-bottom: 15px;
        }
        .dataTables_filter label {
            display: flex;
            align-items: center;
            justify-content: flex-end;
        }
        .dataTables_filter input {
            margin-left: 10px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            padding: 5px 10px;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <nav id="sidebar" class="sidebar">
        <?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?>
        </nav>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Header -->
            <header class="header">
                <button class="btn-toggle" id="sidebarToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="header-right">
                    <div class="dropdown">
                        <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string) ($_SESSION['full_name'] ?? '')); ?>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                        </ul>
                    </div>
                </div>
            </header>

            <!-- Page Content -->
            <main class="content">
                <div class="content-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h2><i class="fas fa-money-bill-wave me-2"></i>Fee Management</h2>
                            <p>Manage fee structures and record payments</p>
                        </div>
                        <div class="d-flex flex-wrap gap-2">
                            <?php if (function_exists('canteen_is_active') && canteen_is_active()): ?>
                            <button class="btn btn-outline-success" data-bs-toggle="modal" data-bs-target="#scanQrModal">
                                <i class="fas fa-qrcode me-1"></i>Scan QR
                            </button>
                            <?php endif; ?>
                            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addFeeStructureModal">
                                <i class="fas fa-plus me-2"></i>Add Fee Structure
                            </button>
                            <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#recordPaymentModal">
                                <i class="fas fa-rupee-sign me-2"></i>Record Payment
                            </button>
                        </div>
                        <div>
                            <button class="btn btn-info me-2" onclick="viewWeeklyFeedingSummary()">
                                <i class="fas fa-chart-line me-2"></i>Weekly Feeding Summary
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Canteen Express Collection banner -->
                <?php if (function_exists('canteen_is_active') && canteen_is_active()): ?>
                <div class="alert alert-success alert-dismissible fade show d-flex align-items-center gap-2 py-2" role="alert">
                    <i class="fas fa-bolt text-warning"></i>
                    <span>Faster fee collection available →
                        <a href="fees_express.php" class="alert-link fw-semibold">Express Collection</a>
                        — scan a student QR in seconds.
                    </span>
                    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <!-- Alert Message -->
                <?php if ($message): ?>
                <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                    <?php echo $message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <!-- Tabs -->
                <ul class="nav nav-tabs" id="feeTabs" role="tablist">
                    <li class="nav-item">
                        <button class="nav-link active" id="structures-tab" data-bs-toggle="tab" data-bs-target="#structures" type="button">
                            <i class="fas fa-list me-2"></i>Fee Structures
                        </button>
                    </li>
                    <li class="nav-item">
                        <button class="nav-link" id="payments-tab" data-bs-toggle="tab" data-bs-target="#payments" type="button">
                            <i class="fas fa-history me-2"></i>Payment History
                        </button>
                    </li>
                </ul>

                <div class="tab-content" id="feeTabsContent">
                    <!-- Fee Structures Tab -->
                    <div class="tab-pane fade show active" id="structures" role="tabpanel">
                        <div class="card">
                            <div class="card-header">
                                <h5><i class="fas fa-layer-group me-2"></i>All Fee Structures</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover" id="structuresTable">
                                        <thead>
                                            <tr>
                                                <th>Class</th>
                                                <th>Fee Type</th>
                                                <th>Amount</th>
                                                <th>Due Date</th>
                                                <th>Academic Year</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (empty($feeStructures)): ?>
                                                <tr>
                                                    <td colspan="6" class="text-center py-5">
                                                        <div class="empty-state">
                                                            <i class="fas fa-file-invoice"></i>
                                                            <h4>No Fee Structures</h4>
                                                            <p>Create a fee structure to start collecting fees</p>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php else: ?>
                                                <?php foreach ($feeStructures as $fee): ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($fee['class_name']); ?></td>
                                                        <td><?php echo htmlspecialchars($fee['fee_type']); ?></td>
                                                        <td><?php echo formatCurrency($fee['amount']); ?></td>
                                                        <td><?php echo date('d M Y', strtotime($fee['due_date'])); ?></td>
                                                        <td><?php echo htmlspecialchars($fee['academic_year']); ?></td>
                                                        <td>
                                                            <div class="action-buttons">
                                                                <a href="fees.php?action=delete_structure&id=<?php echo $fee['id']; ?>" class="action-btn delete" title="Delete" onclick="return confirm('Are you sure you want to delete this fee structure?');">
                                                                    <i class="fas fa-trash"></i>
                                                                </a>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Payment History Tab -->
                   <!-- Payment History Tab -->
<div class="tab-pane fade" id="payments" role="tabpanel">
    <div class="card">
        <div class="card-header">
            <h5><i class="fas fa-history me-2"></i>Payment History - Grouped by Student</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="paymentsTable">
                    <thead>
                        <tr>
                            <th>Student ID</th>
                            <th>Student Name</th>
                            <th>Class</th>
                            <th>Total Payments</th>
                            <th>Total Amount Paid</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($groupedPayments)): ?>
                            <tr>
                                <td colspan="6" class="text-center py-5">
                                    <div class="empty-state">
                                        <i class="fas fa-receipt"></i>
                                        <h4>No Students Found</h4>
                                        <p>Add students and record payments to see them here</p>
                                    </div>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($groupedPayments as $student): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($student['student_id']); ?></td>
                                    <td><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></td>
                                    <td><?php echo htmlspecialchars($student['class']); ?></td>
                                    <td><?php echo $student['payment_count'] ?: 0; ?></td>
                                    <td><?php echo formatCurrency($student['total_paid'] ?: 0); ?></td>
                                    <td>
                                        <div class="action-buttons">
                                            <!-- FIX: Use numeric student_id, not the string STU code -->
                                            <button class="action-btn view" onclick="viewStudentPayments(<?php echo $student['student_id']; ?>)" title="View All Payments">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button class="action-btn edit" onclick="addPaymentForStudent(<?php echo $student['student_id']; ?>)" title="Add Payment">
                                                <i class="fas fa-plus"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
                </div>
            </main>

            <!-- Footer -->
            <footer class="footer">
                <p>&copy; 2024 EduTrack Pro. All rights reserved.</p>
            </footer>
        </div>
    </div>

    <!-- Add Fee Structure Modal -->
    <div class="modal fade" id="addFeeStructureModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus-circle me-2"></i>Add Fee Structure</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" action="fees.php">
                    <input type="hidden" name="action" value="add_structure">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Class *</label>
                            <select class="form-select" name="class_name" required>
                                <option value="">Select Class</option>
                                <?php foreach ($classes_list as $cls): ?>
                                <option value="<?= htmlspecialchars($cls) ?>"><?= htmlspecialchars($cls) ?></option>
                                <?php endforeach; ?>
                                <?php if (empty($classes_list)): ?>
                                <option disabled>No active classes — add classes in Class Management</option>
                                <?php endif; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Fee Type *</label>
                            <select class="form-select" name="fee_type" required>
                                <option value="">Select Fee Type</option>
                                <option value="School Fee">School Fee</option>
                                <option value="Feeding Fee">Feeding Fee</option>
                                <option value="Admission Fee">Admission Fee</option>
                                <option value="Printing Fee">Printing Fee</option>
                                <option value="School Attire">School Attire</option>
                                <option value="Others">Others</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Amount *</label>
                            <input type="number" class="form-control" name="amount" placeholder="Enter amount" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Term *</label>
                            <select class="form-select" name="term" required>
                                <option value="">Select Term</option>
                                <?php foreach (ACADEMIC_TERMS as $termOption): ?>
                                <option value="<?= htmlspecialchars($termOption) ?>"><?= htmlspecialchars($termOption) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Due Date *</label>
                            <input type="date" class="form-control" name="due_date" value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Academic Year *</label>
                            <input type="text" class="form-control" name="academic_year" placeholder="e.g., 2023-2024" value="<?php echo getAcademicYear(); ?>" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Add Structure</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Record Payment Modal -->
    <div class="modal fade" id="recordPaymentModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-rupee-sign me-2"></i>Record Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" action="fees.php">
                    <input type="hidden" name="action" id="paymentAction" value="add_payment">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Student *</label>
                            <select class="form-select" name="student_id" id="studentSelect" required>
                                <option value="">Select Student</option>
                                <?php foreach ($students as $student): ?>
                                    <option value="<?php echo $student['id']; ?>">
                                        <?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name'] . ' - ' . $student['student_id']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Outstanding Fee Items *</label>
                            <div id="feeItemsHint" class="text-muted small mb-2">Select a student above to see what they owe.</div>
                            <div id="feeItemsList" class="border rounded p-2 mb-2" style="max-height:220px; overflow-y:auto;"></div>
                            <div class="form-check d-none" id="selectAllTermWrap">
                                <input class="form-check-input" type="checkbox" id="selectAllTermCheckbox">
                                <label class="form-check-label small" for="selectAllTermCheckbox">
                                    Select all <span id="currentTermLabel"></span> items (pay the term in full)
                                </label>
                            </div>
                            <input type="hidden" name="fee_structure_id" id="feeStructureSelect">
                            <div id="bulkFeeIdsContainer"></div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Amount Paid *</label>
                            <input type="number" class="form-control" name="amount_paid" id="amountPaid" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Payment Date *</label>
                            <input type="date" class="form-control" name="payment_date" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Payment Method *</label>
                            <select class="form-select" name="payment_method" required>
                                <option value="cash">Cash</option>
                                <option value="card">Card</option>
                                <option value="bank_transfer">Bank Transfer</option>
                                <option value="online">Online</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Transaction ID</label>
                            <input type="text" class="form-control" name="transaction_id" placeholder="Enter transaction ID">
                        </div>
                        <div class="mb-3 d-none" id="weeksCoveredRow">
                            <label class="form-label">
                                Weeks Covered
                                <span class="text-muted small ms-1">(how many weeks does this payment cover?)</span>
                            </label>
                            <div class="input-group">
                                <input type="number" class="form-control" name="weeks_covered" id="weeksCovered"
                                       value="1" min="1" max="52">
                                <span class="input-group-text">week(s)</span>
                            </div>
                            <div class="btn-group btn-group-sm mt-2" role="group" id="weeksShortcutGroup">
                                <button type="button" class="btn btn-outline-secondary weeks-shortcut-btn" data-weeks="1">1 Week</button>
                                <button type="button" class="btn btn-outline-secondary weeks-shortcut-btn" data-weeks="4">1 Month</button>
                                <button type="button" class="btn btn-outline-secondary weeks-shortcut-btn" data-weeks-full-term="1">Full Term</button>
                            </div>
                            <div id="perWeekHint" class="form-text text-success"></div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="2" placeholder="Any additional notes"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Coupon Code <span class="text-muted">(optional)</span></label>
                            <div class="input-group">
                                <input type="text" class="form-control text-uppercase" id="couponCode" placeholder="Enter coupon code">
                                <button class="btn btn-outline-secondary" type="button" id="applyCouponBtn">Apply</button>
                            </div>
                            <div id="couponResult" class="mt-1 small"></div>
                        </div>
                        <div id="discountBreakdown" class="alert alert-success py-2 d-none">
                            <div class="d-flex justify-content-between"><span>Original amount:</span><span id="origAmountDisplay"></span></div>
                            <div class="d-flex justify-content-between"><span id="discountLabel">Discount:</span><span id="discountAmountDisplay" class="text-success fw-bold"></span></div>
                            <div class="d-flex justify-content-between fw-bold border-top pt-1 mt-1"><span>Amount to pay:</span><span id="finalAmountDisplay"></span></div>
                            <button type="button" class="btn btn-sm btn-link text-danger p-0 mt-1" onclick="removeCoupon()">Remove coupon</button>
                        </div>
                        <input type="hidden" name="coupon_id" id="hiddenCouponId" value="">
                        <input type="hidden" name="discount_amount" id="hiddenDiscountAmount" value="0">
                        <input type="hidden" name="original_amount" id="hiddenOriginalAmount" value="">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">Record Payment</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Student Payments Modal -->
    <div class="modal fade" id="viewPaymentsModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-history me-2"></i>Student Payment History</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="viewPaymentsContent">
                    <p class="text-center">Loading...</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Issue Credit Modal -->
    <div class="modal fade" id="issueCreditModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST" action="fees.php">
                    <input type="hidden" name="action" value="issue_credit">
                    <input type="hidden" name="student_id" id="issueCreditStudentId">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="fas fa-hand-holding-usd me-2"></i>Issue Credit</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <p class="text-muted small">Records money owed back to this student — an overpayment, a fee correction, or a withdrawal after a bulk payment. It will show as available credit and can be applied to their next outstanding balance from the payment history view.</p>
                        <div class="mb-3">
                            <label class="form-label">Amount *</label>
                            <input type="number" class="form-control" name="amount" step="0.01" min="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Reason *</label>
                            <select class="form-select" name="source" required>
                                <option value="overpayment">Overpayment</option>
                                <option value="fee_correction">Fee Correction</option>
                                <option value="admin_adjustment" selected>Admin Adjustment</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="2" placeholder="Brief explanation for the record"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Issue Credit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Payment Modal -->
    <div class="modal fade" id="editPaymentModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" action="fees.php">
                    <input type="hidden" name="action" value="update_payment">
                    <input type="hidden" name="payment_id" id="editPaymentId">
                    <div class="modal-body" id="editPaymentContent">
                        <p class="text-center">Loading...</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Payment</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Weekly Feeding Summary Modal -->
    <div class="modal fade" id="weeklySummaryModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-chart-line me-2"></i>Weekly Feeding Fee Summary</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="weeklySummaryContent">
                    <p class="text-center">Loading...</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="window.location.href='send_weekly_feeding_summary.php?manual=1'">
                        <i class="fas fa-paper-plane me-2"></i>Send SMS Now
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Canteen: Scan QR modal -->
    <?php if (function_exists('canteen_is_active') && canteen_is_active()): ?>
    <div class="modal fade" id="scanQrModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-qrcode me-2"></i>Scan Student QR</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" id="btn-close-qr-modal"></button>
                </div>
                <div class="modal-body text-center">
                    <style>
                        #qr-modal-reader { width:100%; max-width:340px; margin:0 auto; border-radius:10px; overflow:hidden; }
                        #qr-modal-reader video { width:100% !important; height:100% !important; object-fit:cover !important; }
                        #qr-modal-reader img { display:none !important; }
                    </style>
                    <div id="qr-modal-reader"></div>
                    <div id="qr-modal-camera-error" class="alert alert-warning mt-2 d-none">
                        Camera unavailable. Type the student QR token or ID below.
                    </div>
                    <div id="qr-modal-status" class="mt-2 text-muted small">Point camera at student QR code</div>
                </div>
                <div class="modal-footer flex-column gap-2">
                    <input type="text" id="qr-modal-manual" class="form-control text-center"
                           placeholder="Or type Student ID / QR token" autocomplete="off">
                    <button class="btn btn-primary w-100" id="btn-qr-modal-go">
                        <i class="fas fa-search me-1"></i>Look Up Student
                    </button>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="js/main.js"></script>

    <?php if (function_exists('canteen_is_active') && canteen_is_active()): ?>
    <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
    <script>
    (function(){
        var qrScanner  = null;
        var lastToken  = '';
        var lastTime   = 0;
        var scanActive = false;

        var modal = document.getElementById('scanQrModal');
        if (!modal) return;
        modal.addEventListener('shown.bs.modal', startScanner);
        modal.addEventListener('hide.bs.modal',  stopScanner);

        function startScanner() {
            if (qrScanner) { qrScanner.clear(); }
            qrScanner  = new Html5Qrcode('qr-modal-reader');
            scanActive = true;
            qrScanner.start(
                { facingMode: { ideal: 'environment' } },
                { fps: 15, videoConstraints: { facingMode: { ideal: 'environment' }, width: { ideal: 1280 }, height: { ideal: 720 } } },
                function(decodedText) {
                    if (!scanActive) return;
                    var tok = decodedText.trim();
                    var now = Date.now();
                    if (tok === lastToken && now - lastTime < 3000) return;
                    lastToken = tok; lastTime = now;
                    onScan(tok);
                },
                function() {}
            ).catch(function() {
                document.getElementById('qr-modal-camera-error').classList.remove('d-none');
                document.getElementById('qr-modal-reader').style.display = 'none';
            });
        }

        function stopScanner() {
            scanActive = false;
            if (qrScanner) { qrScanner.stop().catch(function(){}); qrScanner = null; }
        }

        function onScan(token) {
            stopScanner();
            bootstrap.Modal.getInstance(modal).hide();
            window.location.href = 'fees_express.php?token=' + encodeURIComponent(token);
        }

        document.getElementById('btn-qr-modal-go').addEventListener('click', function() {
            var val = document.getElementById('qr-modal-manual').value.trim();
            if (!val) return;
            stopScanner();
            bootstrap.Modal.getInstance(modal).hide();
            window.location.href = 'fees_express.php?token=' + encodeURIComponent(val);
        });

        document.getElementById('qr-modal-manual').addEventListener('keydown', function(e) {
            if (e.key === 'Enter') document.getElementById('btn-qr-modal-go').click();
        });

        document.getElementById('btn-close-qr-modal').addEventListener('click', stopScanner);
    })();
    </script>
    <?php endif; ?>

    <script>
    // ── Coupon state (module-level) ────────────────────────────
    var activeCoupon = null;

    $(document).ready(function() {
        // DataTables
        $('#structuresTable').DataTable({
            pageLength: 10,
            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            order: [[0, 'asc']],
            language: { emptyTable: "No fee structures found" }
        });

        $('#paymentsTable').DataTable({
            pageLength: 10,
            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            order: [[1, 'asc']],
            language: { emptyTable: "No payment records found" }
        });

        // Auto-fill amount in edit form
        $(document).on('change', '#editFeeStructureSelect', function() {
            var amount = $(this).find(':selected').data('amount');
            if (amount) $('#editAmountPaid').val(amount);
        });

        var currentFeeItems  = [];
        var maxWeeksCovered  = 52;

        function escapeHtml(s) {
            return $('<div>').text(s == null ? '' : s).html();
        }

        function renderFeeItemsList() {
            var $list = $('#feeItemsList');
            if (!currentFeeItems.length) {
                $list.html('<div class="text-muted small p-1">No outstanding fees for this student.</div>');
                $('#selectAllTermWrap').addClass('d-none');
                return;
            }
            var html = '';
            currentFeeItems.forEach(function(item) {
                html += '<div class="form-check">' +
                    '<input class="form-check-input fee-item-checkbox" type="checkbox" ' +
                        'id="feeItem' + item.fee_structure_id + '" ' +
                        'data-fee-id="' + item.fee_structure_id + '" ' +
                        'data-amount="' + item.remaining + '" ' +
                        'data-is-feeding="' + (item.is_feeding ? '1' : '0') + '" ' +
                        'data-current-term="' + (item.is_current_term ? '1' : '0') + '">' +
                    '<label class="form-check-label small" for="feeItem' + item.fee_structure_id + '">' +
                        escapeHtml(item.fee_type) + ' (' + escapeHtml(item.term || 'no term') + ') — GHS ' + Number(item.remaining).toFixed(2) +
                    '</label>' +
                '</div>';
            });
            $list.html(html);
            $('#selectAllTermWrap').removeClass('d-none');
        }

        function updateSelectionState() {
            var checked = $('.fee-item-checkbox:checked');
            var total = 0;
            var anyFeeding = false;
            checked.each(function() {
                total += parseFloat($(this).data('amount')) || 0;
                if ($(this).data('is-feeding') == 1) anyFeeding = true;
            });
            $('#amountPaid').val(total > 0 ? total.toFixed(2) : '');

            if (anyFeeding) {
                $('#weeksCoveredRow').removeClass('d-none');
                $('#weeksCovered').attr('max', maxWeeksCovered);
            } else {
                $('#weeksCoveredRow').addClass('d-none');
                $('#weeksCovered').val(1);
            }
            updatePerWeekHint();

            // 1 item: identical to the old single-select flow (same hidden
            // fee_structure_id, coupons still usable). 2+ items: bulk path —
            // coupons aren't supported together with a bulk payment yet.
            if (checked.length === 1) {
                $('#feeStructureSelect').val(checked.data('fee-id'));
                $('#couponCode, #applyCouponBtn').prop('disabled', false);
            } else {
                $('#feeStructureSelect').val('');
                $('#couponCode, #applyCouponBtn').prop('disabled', checked.length >= 2);
                if (checked.length >= 2) window.removeCoupon();
            }

            var currentTermBoxes = $('.fee-item-checkbox[data-current-term="1"]');
            $('#selectAllTermCheckbox').prop('checked',
                currentTermBoxes.length > 0 && currentTermBoxes.length === currentTermBoxes.filter(':checked').length);
        }
        $(document).on('change', '.fee-item-checkbox', updateSelectionState);

        $('#selectAllTermCheckbox').on('change', function() {
            $('.fee-item-checkbox[data-current-term="1"]').prop('checked', $(this).is(':checked'));
            updateSelectionState();
        });

        $('#studentSelect').on('change', function() {
            var studentId = $(this).val();
            currentFeeItems = [];
            $('#feeItemsList').html('');
            $('#selectAllTermWrap').addClass('d-none');
            $('#feeStructureSelect').val('');
            if (!studentId) {
                $('#feeItemsHint').text('Select a student above to see what they owe.').removeClass('d-none');
                return;
            }
            $('#feeItemsHint').text('Loading...').removeClass('d-none');
            $.getJSON('ajax/get_outstanding_fee_items.php', { student_id: studentId }, function(r) {
                if (!r.success) {
                    $('#feeItemsHint').text(r.message || 'Could not load fees for this student.');
                    return;
                }
                currentFeeItems = r.items || [];
                maxWeeksCovered = r.max_weeks_covered || 52;
                $('#currentTermLabel').text(r.current_term || '');
                $('#feeItemsHint').addClass('d-none');
                renderFeeItemsList();
                updateSelectionState();
            }).fail(function() {
                $('#feeItemsHint').text('Failed to load outstanding fees. Please try again.');
            });
        });

        // Update per-week hint when amount or weeks changes. The amount
        // field always defaults to the checked items' full remaining
        // balance regardless of weeks selected (amount and weeks are
        // independently-entered fields, same as the original single-item
        // flow) — so when weeks is less than the full term, remind whoever
        // is recording this that the amount shown covers the whole
        // remaining balance, not just the selected weeks, in case they
        // meant to collect (and should type in) a smaller partial amount.
        function updatePerWeekHint() {
            var amount = parseFloat($('#amountPaid').val()) || 0;
            var weeks  = parseInt($('#weeksCovered').val()) || 1;
            if (amount > 0 && weeks > 1) {
                var perWeek = (amount / weeks).toFixed(2);
                var hint = 'GHS ' + perWeek + ' per week x ' + weeks + ' weeks';
                if (weeks < maxWeeksCovered) {
                    hint += ' — amount above is still the full remaining balance for the term; adjust it if you\'re only collecting for these ' + weeks + ' week(s)';
                }
                $('#perWeekHint').text(hint);
            } else {
                $('#perWeekHint').text('');
            }
        }
        $('#amountPaid').on('input', updatePerWeekHint);
        $('#weeksCovered').on('input', updatePerWeekHint);

        $(document).on('click', '.weeks-shortcut-btn', function() {
            var weeks = $(this).data('weeksFullTerm') ? maxWeeksCovered : parseInt($(this).data('weeks'), 10);
            weeks = Math.max(1, Math.min(weeks || 1, maxWeeksCovered || weeks || 1));
            $('#weeksCovered').val(weeks);
            updatePerWeekHint();
        });

        // Coupon: clear when modal closes
        $('#recordPaymentModal').on('hidden.bs.modal', function() {
            window.removeCoupon();
            $('#studentSelect').val('');
            currentFeeItems = [];
            $('#feeItemsList').html('');
            $('#feeItemsHint').text('Select a student above to see what they owe.').removeClass('d-none');
            $('#selectAllTermWrap').addClass('d-none');
        });

        // Coupon: apply button
        $('#applyCouponBtn').on('click', function() {
            var code    = $('#couponCode').val().trim().toUpperCase();
            var amount  = parseFloat($('#amountPaid').val()) || 0;
            var student = $('#studentSelect').val();
            var feeId   = $('#feeStructureSelect').val();

            if (!code)             { $('#couponResult').html('<span class="text-danger">Please enter a coupon code</span>'); return; }
            if (!amount || amount <= 0) { $('#couponResult').html('<span class="text-danger">Enter payment amount first</span>'); return; }

            $.post('ajax/coupons.php', {
                action: 'validate', coupon_code: code,
                student_id: student, fee_amount: amount, fee_structure_id: feeId
            }, function(r) {
                if (r.valid) {
                    activeCoupon = r;
                    $('#couponResult').html('<span class="text-success"><i class="fas fa-tag me-1"></i>' + r.message + '</span>');
                    $('#origAmountDisplay').text('GHS ' + amount.toFixed(2));
                    $('#discountLabel').text(r.coupon_name + ':');
                    $('#discountAmountDisplay').text('- GHS ' + r.discount_amount.toFixed(2));
                    $('#finalAmountDisplay').text('GHS ' + r.final_amount.toFixed(2));
                    $('#discountBreakdown').removeClass('d-none');
                    $('#hiddenCouponId').val(r.coupon_id);
                    $('#hiddenDiscountAmount').val(r.discount_amount);
                    $('#hiddenOriginalAmount').val(amount);
                    $('#amountPaid').val(r.final_amount.toFixed(2));
                } else {
                    $('#couponResult').html('<span class="text-danger"><i class="fas fa-times me-1"></i>' + r.message + '</span>');
                    window.removeCoupon();
                }
            }, 'json').fail(function() {
                $('#couponResult').html('<span class="text-danger">Failed to validate coupon</span>');
            });
        });

        // Route to the single-item or bulk action depending on how many items are checked.
        $('#recordPaymentModal form').on('submit', function(e) {
            var checked = $('.fee-item-checkbox:checked');
            if (checked.length === 0) {
                e.preventDefault();
                alert('Select at least one fee item.');
                return;
            }
            $('#bulkFeeIdsContainer').empty();
            if (checked.length === 1) {
                $('#paymentAction').val('add_payment');
                $('#feeStructureSelect').val(checked.data('fee-id'));
            } else {
                $('#paymentAction').val('add_bulk_payment');
                $('#feeStructureSelect').val('');
                checked.each(function() {
                    $('#bulkFeeIdsContainer').append(
                        '<input type="hidden" name="fee_structure_ids[]" value="' + $(this).data('fee-id') + '">'
                    );
                });
                $('#bulkFeeIdsContainer').append(
                    '<input type="hidden" name="total_amount" value="' + (parseFloat($('#amountPaid').val()) || 0) + '">'
                );
            }
        });
    });

    // ── Global modal functions (must be on window for onclick= attributes) ──

    window.viewStudentPayments = function(studentId) {
        var modal = new bootstrap.Modal(document.getElementById('viewPaymentsModal'));
        modal.show();
        $('#viewPaymentsContent').html('<p class="text-center"><i class="fas fa-spinner fa-spin me-2"></i>Loading...</p>');
        $.ajax({
            url: 'ajax/get_student_payments.php',
            type: 'GET',
            data: { student_id: studentId },
            success: function(response) { $('#viewPaymentsContent').html(response); },
            error: function() { $('#viewPaymentsContent').html('<p class="text-danger">Failed to load payment data. Please try again.</p>'); }
        });
    };

    window.addPaymentForStudent = function(studentId) {
        var modal = new bootstrap.Modal(document.getElementById('recordPaymentModal'));
        modal.show();
        setTimeout(function() { $('#studentSelect').val(studentId).trigger('change'); }, 500);
    };

    window.editPayment = function(paymentId) {
        var modal = new bootstrap.Modal(document.getElementById('editPaymentModal'));
        modal.show();
        $('#editPaymentContent').html('<p class="text-center"><i class="fas fa-spinner fa-spin me-2"></i>Loading...</p>');
        $.ajax({
            url: 'ajax/get_payment_details.php',
            type: 'GET',
            data: { payment_id: paymentId },
            success: function(response) { $('#editPaymentContent').html(response); },
            error: function() { $('#editPaymentContent').html('<p class="text-danger">Failed to load payment data. Please try again.</p>'); }
        });
    };

    window.deletePayment = function(paymentId) {
        if (confirm('Are you sure you want to delete this payment? This action cannot be undone.')) {
            window.location.href = 'fees.php?action=delete_payment&id=' + paymentId;
        }
    };

    window.issueCreditForStudent = function(studentId) {
        $('#issueCreditStudentId').val(studentId);
        var modal = new bootstrap.Modal(document.getElementById('issueCreditModal'));
        modal.show();
    };

    window.viewWeeklyFeedingSummary = function() {
        var modal = new bootstrap.Modal(document.getElementById('weeklySummaryModal'));
        modal.show();
        $('#weeklySummaryContent').html('<p class="text-center"><i class="fas fa-spinner fa-spin me-2"></i>Loading...</p>');
        $.ajax({
            url: 'ajax/get_weekly_feeding_summary.php',
            type: 'GET',
            success: function(response) { $('#weeklySummaryContent').html(response); },
            error: function() { $('#weeklySummaryContent').html('<p class="text-danger">Failed to load summary. Please try again.</p>'); }
        });
    };

    window.removeCoupon = function() {
        activeCoupon = null;
        $('#couponCode').val('');
        $('#couponResult').html('');
        $('#discountBreakdown').addClass('d-none');
        $('#hiddenCouponId').val('');
        $('#hiddenDiscountAmount').val('0');
        $('#hiddenOriginalAmount').val('');
    };
    </script>
</body>
</html>
