<?php
ob_start();
ini_set('display_errors', 0);
error_reporting(0);
session_start();
include "../include/config.php";

// Check if user is logged in
if (!isset($_SESSION['studentid'])) {
    header("location:../index.php");
    exit();
}

$userlogin = $_SESSION['studentid'];
$intake = $_SESSION['intake'];
$program = $_SESSION['program'];

// Get admin details
$admin = mysqli_query($conn, "SELECT * FROM admin LIMIT 1");
if ($admin && mysqli_num_rows($admin) > 0) {
    $row = mysqli_fetch_array($admin);
    $school = $row['sname'];
    $address = $row['address'];
    $phone = $row['contact'];
    $email = $row['email'];
    $web = $row['web'];
} else {
    $school = "Zama University";
    $address = "Lusaka, Zambia";
    $phone = "+260 955 110 100";
    $email = "finance@zama.edu.zm";
    $web = "www.zama.edu.zm";
}

// Get student details
$studentQuery = "SELECT studentname, email, mobile, studentid, program, intake FROM students WHERE studentid = '$userlogin'";
$studentResult = mysqli_query($conn, $studentQuery);
if ($studentResult && mysqli_num_rows($studentResult) > 0) {
    $student = mysqli_fetch_assoc($studentResult);
} else {
    $student = [
        'studentname' => $_SESSION['fullname'] ?? 'Student',
        'email' => $_SESSION['email'] ?? '',
        'mobile' => $_SESSION['phone'] ?? '',
        'studentid' => $userlogin,
        'program' => $program,
        'intake' => $intake
    ];
}

// Get scholarship percentage for the student
$scholarshipPercentage = 0;
$scholarshipQuery = "SELECT percentage as scholarship FROM scholarship WHERE studentid = '$userlogin'";
$scholarshipResult = mysqli_query($conn, $scholarshipQuery);
if ($scholarshipResult && mysqli_num_rows($scholarshipResult) > 0) {
    $scholarshipRow = mysqli_fetch_assoc($scholarshipResult);
    $scholarshipPercentage = $scholarshipRow['scholarship'] ?? 0;
}

// Bank details
$bankDetails = [
    'bank_name' => 'MY BANK',
    'account_name' => 'Zama Student Portal',
    'account_number' => '000000000000000000',
    'branch' => 'lusaka',
    'branch_code' => '081',
    'swift_code' => 'RMBZDFF'
];

// Include FPDF library
require('../../fpdf/fpdf.php');

// Function to get fee description
function getFeeDescription($feeType) {
    $descriptions = [
        'tuition' => 'Tuition Fee',
        'registration' => 'Registration Fee',
        'library' => 'Library Fee',
        'examination' => 'Examination Fee',
        'hostel' => 'Hostel Fee',
        'sports' => 'Sports Fee',
        'medical' => 'Medical Fee',
        'laboratory' => 'Laboratory Fee',
        'development' => 'Development Levy',
        'caution' => 'Caution Money',
        'late' => 'Late Registration'
    ];
    return $descriptions[strtolower($feeType)] ?? 'Academic Fee';
}

// FPDF Function for Single Invoice with Scholarship
function generateSingleBalanceInvoiceFPDF($balance, $bankDetails, $scholarshipPercentage = 0, $adminDetails = null) {
    global $conn; // Add this to access connection inside function
    
    $pdf = new FPDF('P', 'mm', 'A4');
    $pdf->SetMargins(10, 10, 10);
    $pdf->AddPage();
    
    // Colors
    $primaryColor = array(208, 63, 77); // var(--primary)
    $secondaryColor = array(44, 62, 80); // #2c3e50
    $lightGray = array(248, 249, 250);
    $successColor = array(40, 167, 69);
    $warningColor = array(255, 193, 7);
    
    // Current date and invoice number
    $currentDate = date('d/m/Y');
    $dueDate = date('d/m/Y', strtotime('+30 days'));
    $invoiceNumber = 'INV-' . date('Y') . '-' . $balance['studentid'] . '-' . str_pad($balance['id'], 4, '0', STR_PAD_LEFT);
    
    // Header using admin details
    $pdf->SetFont('Arial', 'B', 16);
    $pdf->Cell(0, 8, $adminDetails['school'] ?? 'ZAMA UNIVERSITY', 0, 1, 'C');
    
    $pdf->SetFont('Arial', 'I', 10);
    $pdf->SetTextColor(100, 100, 100);
    $pdf->Cell(0, 5, '"The future belongs to those who believe in the beauty of their dreams"', 0, 1, 'C');
    
    $pdf->SetFont('Arial', '', 9);
    $pdf->Cell(0, 5, $adminDetails['address'] ?? 'Lusaka, Zambia', 0, 1, 'C');
    
    $pdf->Ln(5);
    
    // Invoice Title
    $pdf->SetFont('Arial', 'B', 14);
    $pdf->SetTextColor($secondaryColor[0], $secondaryColor[1], $secondaryColor[2]);
    $pdf->Cell(0, 8, 'FEE PAYMENT INVOICE', 0, 1, 'C');
    
    // Scholarship Badge if applicable
    if ($scholarshipPercentage > 0) {
        $pdf->SetFont('Arial', 'B', 10);
        $pdf->SetFillColor(40, 167, 69);
        $pdf->SetTextColor(255, 255, 255);
        $pdf->Cell(35, 6, $scholarshipPercentage . '% SCHOLARSHIP', 1, 0, 'C', true);
        $pdf->SetTextColor($secondaryColor[0], $secondaryColor[1], $secondaryColor[2]);
    }
    
    // Status Badge
    $status = $balance['status'];
    $pdf->SetFont('Arial', 'B', 10);
    if ($status == 'PAID') {
        $pdf->SetFillColor($successColor[0], $successColor[1], $successColor[2]);
        $pdf->SetTextColor(255, 255, 255);
    } else {
        $pdf->SetFillColor($warningColor[0], $warningColor[1], $warningColor[2]);
        $pdf->SetTextColor(0, 0, 0);
    }
    $pdf->Cell(20, 6, $status, 1, 0, 'C', true);
    $pdf->Ln(8);
    
    // Invoice Info
    $pdf->SetFont('Arial', '', 9);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->Cell(60, 5, 'Invoice No: ' . $invoiceNumber, 0, 0);
    $pdf->Cell(60, 5, 'Date: ' . $currentDate, 0, 0);
    $pdf->Cell(60, 5, 'Due Date: ' . $dueDate, 0, 1);
    $pdf->Cell(60, 5, 'Student ID: ' . $balance['studentid'], 0, 0);
    $pdf->Cell(60, 5, 'Program: ' . $balance['program'], 0, 0);
    $pdf->Cell(60, 5, 'Intake: ' . $balance['intake'], 0, 1);
    $pdf->Ln(3);
    
    // Student Information
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetTextColor($primaryColor[0], $primaryColor[1], $primaryColor[2]);
    $pdf->Cell(0, 6, 'STUDENT INFORMATION', 0, 1);
    $pdf->SetDrawColor(200, 200, 200);
    $pdf->Cell(0, 0, '', 'B', 1);
    
    $pdf->SetFont('Arial', '', 9);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->Cell(60, 5, 'Name: ' . $balance['fullname'], 0, 0);
    $pdf->Cell(60, 5, 'Email: ' . $balance['email'], 0, 0);
    $pdf->Cell(60, 5, 'Phone: ' . $balance['mobile'], 0, 1);
    $pdf->Ln(3);
    
    // Invoice Details
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetTextColor($primaryColor[0], $primaryColor[1], $primaryColor[2]);
    $pdf->Cell(0, 6, 'INVOICE DETAILS', 0, 1);
    $pdf->Cell(0, 0, '', 'B', 1);
    
    // Fee Type and Description
    $pdf->SetFont('Arial', '', 9);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->Cell(40, 5, 'Fee Type:', 0, 0);
    $pdf->Cell(0, 5, strtoupper($balance['fee_type']), 0, 1);
    
    $pdf->Cell(40, 5, 'Description:', 0, 0);
    $pdf->Cell(0, 5, getFeeDescription($balance['fee_type']), 0, 1);
    
    $pdf->Cell(40, 5, 'Academic Year:', 0, 0);
    $pdf->Cell(0, 5, $balance['year'], 0, 1);
    
    $pdf->Cell(40, 5, 'Semester:', 0, 0);
    $pdf->Cell(0, 5, 'Semester ' . $balance['period'], 0, 1);
    $pdf->Ln(3);
    
    // Table Header
    $pdf->SetFillColor($primaryColor[0], $primaryColor[1], $primaryColor[2]);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetFont('Arial', 'B', 9);
    
    $pdf->Cell(70, 7, 'DESCRIPTION', 1, 0, 'L', true);
    $pdf->Cell(30, 7, 'ACADEMIC YEAR', 1, 0, 'C', true);
    $pdf->Cell(30, 7, 'SEMESTER', 1, 0, 'C', true);
    $pdf->Cell(40, 7, 'AMOUNT (ZMW)', 1, 1, 'R', true);
    
    // Table Content with Scholarship
    $pdf->SetFillColor(255, 255, 255);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetFont('Arial', '', 9);
    
    $pdf->Cell(70, 7, getFeeDescription($balance['fee_type']), 'LR', 0, 'L');
    $pdf->Cell(30, 7, $balance['year'], 'LR', 0, 'C');
    $pdf->Cell(30, 7, 'Semester ' . $balance['period'], 'LR', 0, 'C');
    
    // Show net amount after scholarship
    $pdf->Cell(40, 7, number_format($balance['net_amount'], 2), 'LR', 1, 'R');
    
    // Show scholarship discount row if applicable
    if ($scholarshipPercentage > 0) {
        $pdf->Cell(70, 5, '', 'LR', 0, 'L');
        $pdf->Cell(30, 5, '', 'LR', 0, 'C');
        $pdf->Cell(30, 5, '', 'LR', 0, 'C');
        $pdf->SetFont('Arial', 'I', 8);
        $pdf->SetTextColor(40, 167, 69);
        $pdf->Cell(40, 5, '- ' . number_format($balance['scholarship_amount'], 2) . ' (' . $scholarshipPercentage . '%)', 'LR', 1, 'R');
    }
    
    $pdf->Cell(170, 0, '', 'T', 1);
    $pdf->Ln(5);
    
    // Payment Summary with Scholarship
    $pdf->SetFillColor($lightGray[0], $lightGray[1], $lightGray[2]);
    $pdf->SetDrawColor(200, 200, 200);
    $pdf->Rect(10, $pdf->GetY(), 190, $scholarshipPercentage > 0 ? 30 : 25);
    
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetTextColor($primaryColor[0], $primaryColor[1], $primaryColor[2]);
    $pdf->Cell(0, 6, 'PAYMENT SUMMARY', 0, 1);
    
    $pdf->SetFont('Arial', '', 9);
    $pdf->SetTextColor(0, 0, 0);
    
    $y = $pdf->GetY();
    $pdf->SetXY(15, $y);
    $pdf->Cell(80, 5, 'Original Amount:', 0, 0);
    $pdf->Cell(40, 5, 'ZMW ' . number_format($balance['original_amount'], 2), 0, 1, 'R');
    
    // Scholarship discount line
    if ($scholarshipPercentage > 0) {
        $pdf->SetX(15);
        $pdf->Cell(80, 5, 'Scholarship Discount (' . $scholarshipPercentage . '%):', 0, 0);
        $pdf->SetTextColor(40, 167, 69);
        $pdf->Cell(40, 5, '-ZMW ' . number_format($balance['scholarship_amount'], 2), 0, 1, 'R');
        $pdf->SetTextColor(0, 0, 0);
        
        $pdf->SetX(15);
        $pdf->SetFont('Arial', 'B', 10);
        $pdf->Cell(80, 5, 'Net Amount Payable:', 0, 0);
        $pdf->Cell(40, 5, 'ZMW ' . number_format($balance['net_amount'], 2), 0, 1, 'R');
        $pdf->SetFont('Arial', '', 9);
    }
    
    $pdf->SetX(15);
    $pdf->Cell(80, 5, 'Amount Paid:', 0, 0);
    $pdf->Cell(40, 5, 'ZMW ' . number_format($balance['paid_amount'], 2), 0, 1, 'R');
    
    $pdf->SetX(15);
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetTextColor($primaryColor[0], $primaryColor[1], $primaryColor[2]);
    $pdf->Cell(80, 6, 'Remaining Balance:', 0, 0);
    $pdf->Cell(40, 6, 'ZMW ' . number_format($balance['remaining_amount'], 2), 0, 1, 'R');
    
    $pdf->Ln(10);
    
    // Bank Details (if balance remaining)
    if ($balance['remaining_amount'] > 0) {
        $pdf->SetFillColor(232, 244, 255);
        $pdf->SetDrawColor(179, 215, 255);
        
        $pdf->SetFont('Arial', 'B', 10);
        $pdf->SetTextColor($primaryColor[0], $primaryColor[1], $primaryColor[2]);
        $pdf->Cell(0, 4, 'BANK PAYMENT DETAILS', 0, 1);
        
        // Important Note
        $pdf->SetFillColor(255, 243, 205);
        $pdf->SetDrawColor(255, 193, 7);
        $pdf->Rect(15, $pdf->GetY() + 2, 180, 8);
        
        $pdf->SetFont('Arial', 'B', 8);
        $pdf->SetTextColor(133, 100, 4);
        $pdf->SetXY(20, $pdf->GetY() + 4);
        $pdf->Cell(170, 4, 'IMPORTANT: Use Student ID as payment reference: ' . $balance['studentid'], 0, 1);
        
        $pdf->SetY($pdf->GetY() + 10);
        $pdf->SetFont('Arial', '', 9);
        $pdf->SetTextColor(0, 0, 0);
        
        $pdf->Cell(40, 5, 'Bank Name:', 0, 0);
        $pdf->Cell(0, 5, $bankDetails['bank_name'], 0, 1);
        
        $pdf->Cell(40, 5, 'Account Name:', 0, 0);
        $pdf->Cell(0, 5, $bankDetails['account_name'], 0, 1);
        
        $pdf->Cell(40, 5, 'Account Number:', 0, 0);
        $pdf->Cell(0, 5, $bankDetails['account_number'], 0, 1);
        
        $pdf->Cell(40, 5, 'Branch:', 0, 0);
        $pdf->Cell(0, 5, $bankDetails['branch'], 0, 1);
        
        $pdf->Ln(10);
    }
    
    // Signature Area
    $pdf->SetDrawColor(100, 100, 100);
    
    $pdf->SetFont('Arial', '', 9);
    $pdf->SetTextColor(100, 100, 100);
    
    $pdf->Cell(70, 20, 'Bank Stamp', 1, 1, 'C');
    
    $pdf->Ln(10);
    
    // Footer
    $pdf->SetFont('Arial', 'I', 8);
    $pdf->SetTextColor(150, 150, 150);
    $pdf->Cell(0, 4, 'This is a computer generated invoice. No signature required.', 0, 1, 'C');
    $pdf->Cell(0, 4, 'For inquiries: ' . ($adminDetails['email'] ?? 'finance@zama.edu.zm') . ' | Phone: ' . ($adminDetails['phone'] ?? '+260 955 110 100'), 0, 1, 'C');
    $pdf->Cell(0, 4, chr(169) . ' ' . date('Y') . ' ' . ($adminDetails['school'] ?? 'Zama University') . '. All rights reserved.', 0, 1, 'C');
    
    return $pdf;
}

// FPDF Function for All Invoices with Scholarship
function generateAllBalancesInvoiceFPDF($balances, $bankDetails, $totalAmount, $totalPaid, $totalRemaining, $student, $scholarshipPercentage = 0, $totalScholarship = 0, $totalNetAmount = 0, $adminDetails = null) {
    $pdf = new FPDF('P', 'mm', 'A4');
    $pdf->SetMargins(10, 10, 10);
    $pdf->AddPage();
    
    // Colors
    $primaryColor = array(208, 63, 77);
    $secondaryColor = array(44, 62, 80);
    $lightGray = array(248, 249, 250);
    
    // Header
    $pdf->SetFont('Arial', 'B', 16);
    $pdf->Cell(0, 8, $adminDetails['school'] ?? 'ZAMA UNIVERSITY', 0, 1, 'C');
    
    // Scholarship header if applicable
    if ($scholarshipPercentage > 0) {
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->SetTextColor(40, 167, 69);
        $pdf->Cell(0, 6, 'CONSOLIDATED FEE INVOICE STATEMENT', 0, 1, 'C');
        $pdf->SetFont('Arial', 'I', 10);
        $pdf->Cell(0, 5, 'With ' . $scholarshipPercentage . '% Scholarship Applied', 0, 1, 'C');
    } else {
        $pdf->SetFont('Arial', 'B', 12);
        $pdf->Cell(0, 6, 'CONSOLIDATED FEE INVOICE STATEMENT', 0, 1, 'C');
    }
    
    $pdf->Ln(5);
    
    // Student Information Box
    $pdf->SetFillColor($lightGray[0], $lightGray[1], $lightGray[2]);
    $pdf->SetDrawColor(200, 200, 200);
    $pdf->Rect(10, $pdf->GetY(), 190, 25);
    
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetTextColor($secondaryColor[0], $secondaryColor[1], $secondaryColor[2]);
    $pdf->Cell(0, 6, 'STUDENT INFORMATION', 0, 1);
    
    $pdf->SetFont('Arial', '', 9);
    $pdf->SetTextColor(0, 0, 0);
    
    $pdf->Cell(95, 5, 'Student: ' . $student['studentname'], 0, 0);
    $pdf->Cell(95, 5, 'Student ID: ' . $student['studentid'], 0, 1);
    
    $pdf->Cell(95, 5, 'Program: ' . $student['program'], 0, 0);
    $pdf->Cell(95, 5, 'Intake: ' . $student['intake'], 0, 1);
    
    $pdf->Cell(95, 5, 'Generated: ' . date('d/m/Y'), 0, 0);
    $pdf->Cell(95, 5, 'Invoice: INV-ALL-' . $student['studentid'] . '-' . date('Ymd'), 0, 1);
    
    // Scholarship info if applicable
    if ($scholarshipPercentage > 0) {
        $pdf->Cell(95, 5, 'Scholarship: ' . $scholarshipPercentage . '%', 0, 0);
        $pdf->Cell(95, 5, 'Discount: ZMW ' . number_format($totalScholarship, 2), 0, 1);
    }
    
    $pdf->Ln(8);
    
    // All Invoices Table Header
    $pdf->SetFillColor($primaryColor[0], $primaryColor[1], $primaryColor[2]);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->SetFont('Arial', 'B', 9);
    
    $pdf->Cell(10, 7, '#', 1, 0, 'C', true);
    $pdf->Cell(35, 7, 'FEE TYPE', 1, 0, 'L', true);
    $pdf->Cell(20, 7, 'YEAR', 1, 0, 'C', true);
    $pdf->Cell(15, 7, 'SEM', 1, 0, 'C', true);
    $pdf->Cell(25, 7, 'NET AMOUNT', 1, 0, 'R', true);
    $pdf->Cell(25, 7, 'PAID', 1, 0, 'R', true);
    $pdf->Cell(25, 7, 'BALANCE', 1, 0, 'R', true);
    $pdf->Cell(25, 7, 'STATUS', 1, 1, 'C', true);
    
    // Table Content
    $pdf->SetFillColor(255, 255, 255);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetFont('Arial', '', 8);
    
    $counter = 1;
    $currentYear = '';
    
    foreach ($balances as $balance) {
        // Year Separator
        if ($currentYear != $balance['year']) {
            $currentYear = $balance['year'];
            $pdf->SetFillColor(232, 244, 255);
            $pdf->SetFont('Arial', 'B', 9);
            $pdf->Cell(170, 6, 'ACADEMIC YEAR ' . $currentYear, 1, 1, 'L', true);
            $pdf->SetFont('Arial', '', 8);
        }
        
        // Status color
        if ($balance['status'] == 'PAID') {
            $statusColor = array(40, 167, 69);
        } else {
            $statusColor = array(255, 193, 7);
        }
        
        $pdf->Cell(10, 6, $counter++, 1, 0, 'C');
        $pdf->Cell(35, 6, ucfirst($balance['fee_type']), 1, 0, 'L');
        $pdf->Cell(20, 6, $balance['year'], 1, 0, 'C');
        $pdf->Cell(15, 6, $balance['period'], 1, 0, 'C');
        $pdf->Cell(25, 6, number_format($balance['net_amount'], 2), 1, 0, 'R');
        $pdf->Cell(25, 6, number_format($balance['paid_amount'], 2), 1, 0, 'R');
        $pdf->Cell(25, 6, number_format($balance['remaining_amount'], 2), 1, 0, 'R');
        
        $pdf->SetFillColor($statusColor[0], $statusColor[1], $statusColor[2]);
        $pdf->Cell(25, 6, $balance['status'], 1, 1, 'C', true);
        
        $pdf->SetFillColor(255, 255, 255);
        
        // Show scholarship discount in smaller font if applicable
        if ($scholarshipPercentage > 0 && $balance['scholarship_amount'] > 0) {
            $pdf->SetFont('Arial', 'I', 7);
            $pdf->SetTextColor(40, 167, 69);
            $pdf->Cell(170, 4, 'Original: ZMW ' . number_format($balance['original_amount'], 2) . 
                      ' | Scholarship: -ZMW ' . number_format($balance['scholarship_amount'], 2) . 
                      ' (' . $scholarshipPercentage . '%)', 0, 1, 'R');
            $pdf->SetFont('Arial', '', 8);
            $pdf->SetTextColor(0, 0, 0);
        }
    }
    
    $pdf->Ln(5);
    
    // Summary Box with Scholarship
    $summaryHeight = $scholarshipPercentage > 0 ? 35 : 20;
    $pdf->SetFillColor($lightGray[0], $lightGray[1], $lightGray[2]);
    $pdf->SetDrawColor(200, 200, 200);
    $pdf->Rect(10, $pdf->GetY(), 190, $summaryHeight);
    
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetTextColor($primaryColor[0], $primaryColor[1], $primaryColor[2]);
    $pdf->Cell(0, 6, 'SUMMARY', 0, 1);
    
    $pdf->SetFont('Arial', '', 9);
    $pdf->SetTextColor(0, 0, 0);
    
    $y = $pdf->GetY();
    $pdf->SetXY(15, $y);
    $pdf->Cell(80, 5, 'Total Invoices:', 0, 0);
    $pdf->Cell(40, 5, count($balances), 0, 1, 'R');
    
    $pdf->SetX(15);
    $pdf->Cell(80, 5, 'Total Original Amount:', 0, 0);
    $pdf->Cell(40, 5, 'ZMW ' . number_format($totalAmount, 2), 0, 1, 'R');
    
    if ($scholarshipPercentage > 0) {
        $pdf->SetX(15);
        $pdf->Cell(80, 5, 'Total Scholarship (' . $scholarshipPercentage . '%):', 0, 0);
        $pdf->SetTextColor(40, 167, 69);
        $pdf->Cell(40, 5, '-ZMW ' . number_format($totalScholarship, 2), 0, 1, 'R');
        $pdf->SetTextColor(0, 0, 0);
        
        $pdf->SetX(15);
        $pdf->SetFont('Arial', 'B', 10);
        $pdf->Cell(80, 5, 'Total Net Amount:', 0, 0);
        $pdf->Cell(40, 5, 'ZMW ' . number_format($totalNetAmount, 2), 0, 1, 'R');
        $pdf->SetFont('Arial', '', 9);
    }
    
    $pdf->SetX(15);
    $pdf->Cell(80, 5, 'Total Paid:', 0, 0);
    $pdf->Cell(40, 5, 'ZMW ' . number_format($totalPaid, 2), 0, 1, 'R');
    
    $pdf->SetX(15);
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetTextColor($primaryColor[0], $primaryColor[1], $primaryColor[2]);
    $pdf->Cell(80, 6, 'Total Remaining:', 0, 0);
    $pdf->Cell(40, 6, 'ZMW ' . number_format($totalRemaining, 2), 0, 1, 'R');
    
    $pdf->Ln(10);
    
    // Payment Instructions (if balance remaining)
    if ($totalRemaining > 0) {
        $pdf->SetFillColor(232, 244, 255);
        $pdf->SetDrawColor(179, 215, 255);
        $pdf->Rect(10, $pdf->GetY(), 190, 25);
        
        $pdf->SetFont('Arial', 'B', 10);
        $pdf->SetTextColor($primaryColor[0], $primaryColor[1], $primaryColor[2]);
        $pdf->Cell(0, 6, 'PAYMENT INSTRUCTIONS', 0, 1);
        
        // Important Note
        $pdf->SetFillColor(255, 243, 205);
        $pdf->SetDrawColor(255, 193, 7);
        $pdf->Rect(15, $pdf->GetY() + 2, 180, 6);
        
        $pdf->SetFont('Arial', 'B', 8);
        $pdf->SetTextColor(133, 100, 4);
        $pdf->SetXY(20, $pdf->GetY() + 3);
        $pdf->Cell(170, 4, 'REFERENCE: ' . $student['studentid'], 0, 1);
        
        $pdf->SetY($pdf->GetY() + 8);
        $pdf->SetFont('Arial', '', 9);
        $pdf->SetTextColor(0, 0, 0);
        
        $pdf->Cell(40, 5, 'Bank:', 0, 0);
        $pdf->Cell(0, 5, $bankDetails['bank_name'], 0, 1);
        
        $pdf->Cell(40, 5, 'Account:', 0, 0);
        $pdf->Cell(0, 5, $bankDetails['account_name'], 0, 1);
        
        $pdf->Cell(40, 5, 'Account No:', 0, 0);
        $pdf->Cell(0, 5, $bankDetails['account_number'], 0, 1);
        
        $pdf->Ln(5);
    }
    
    // Footer
    $pdf->SetFont('Arial', 'I', 8);
    $pdf->SetTextColor(150, 150, 150);
    $pdf->Cell(0, 4, 'Computer generated document - ' . ($adminDetails['school'] ?? 'Zama University') . ' Finance Department', 0, 1, 'C');
    $pdf->Cell(0, 4, chr(169) . ' ' . date('Y') . ' ' . ($adminDetails['school'] ?? 'Zama University'), 0, 1, 'C');
    
    return $pdf;
}

// Handle PDF download for single balance
if (isset($_GET['download_invoice']) && isset($_GET['id'])) {
    $balanceId = intval($_GET['id']);
    
    $balanceQuery = "SELECT b.* FROM balances b WHERE b.id = $balanceId";
    $balanceResult = mysqli_query($conn, $balanceQuery);
    
    if (mysqli_num_rows($balanceResult) > 0) {
        $balance = mysqli_fetch_assoc($balanceResult);
        
        $paymentQuery = "SELECT SUM(amount) as paid_amount FROM payments WHERE studentid = '$userlogin' AND fee_type = '{$balance['fee_type']}' AND year = '{$balance['year']}' AND period = '{$balance['period']}'";
        $paymentResult = mysqli_query($conn, $paymentQuery);
        $paymentData = mysqli_fetch_assoc($paymentResult);
        $paidAmount = $paymentData['paid_amount'] ?? 0;
        
        $balance['fullname'] = $student['studentname'];
        $balance['email'] = $student['email'];
        $balance['mobile'] = $student['mobile'];
        $balance['studentid'] = $student['studentid'];
        $balance['program'] = $program;
        $balance['intake'] = $intake;
        
        // Apply scholarship discount
        $originalAmount = $balance['amount'];
        if ($scholarshipPercentage > 0) {
            $scholarshipAmount = ($originalAmount * $scholarshipPercentage) / 100;
            $netAmount = $originalAmount - $scholarshipAmount;
        } else {
            $scholarshipAmount = 0;
            $netAmount = $originalAmount;
        }
        
        $balance['paid_amount'] = $paidAmount;
        $balance['remaining_amount'] = max(0, $netAmount - $paidAmount);
        $balance['status'] = ($paidAmount >= $netAmount) ? 'PAID' : 'PENDING';
        $balance['original_amount'] = $originalAmount;
        $balance['scholarship_amount'] = $scholarshipAmount;
        $balance['net_amount'] = $netAmount;
        
        // Admin details for PDF
        $adminDetails = [
            'school' => $school,
            'address' => $address,
            'phone' => $phone,
            'email' => $email,
            'web' => $web
        ];
        
        // Generate PDF using FPDF with scholarship
        $pdf = generateSingleBalanceInvoiceFPDF($balance, $bankDetails, $scholarshipPercentage, $adminDetails);
        $pdf->Output('I', 'INVOICE_' . $balance['studentid'] . '_' . $balance['fee_type'] . '_' . $balance['year'] . '.pdf');
        exit();
    }
}

// Handle bulk PDF download
if (isset($_GET['download_all_invoices'])) {
    $allBalancesQuery = "SELECT b.* FROM balances b WHERE b.intake = '$intake' AND b.program = '$program' ORDER BY b.year DESC, b.period DESC";
    $allBalancesResult = mysqli_query($conn, $allBalancesQuery);
    
    $allBalances = [];
    $totalAmount = $totalPaid = $totalRemaining = $totalScholarship = $totalNetAmount = 0;
    
    while ($row = mysqli_fetch_assoc($allBalancesResult)) {
        $paymentQuery = "SELECT SUM(amount) as paid_amount FROM payments WHERE studentid = '$userlogin' AND fee_type = '{$row['fee_type']}' AND year = '{$row['year']}' AND period = '{$row['period']}'";
        $paymentResult = mysqli_query($conn, $paymentQuery);
        $paymentData = mysqli_fetch_assoc($paymentResult);
        $paidAmount = $paymentData['paid_amount'] ?? 0;
        
        // Apply scholarship discount
        $originalAmount = $row['amount'];
        if ($scholarshipPercentage > 0) {
            $scholarshipAmount = ($originalAmount * $scholarshipPercentage) / 100;
            $netAmount = $originalAmount - $scholarshipAmount;
        } else {
            $scholarshipAmount = 0;
            $netAmount = $originalAmount;
        }
        
        $row['paid_amount'] = $paidAmount;
        $row['remaining_amount'] = max(0, $netAmount - $paidAmount);
        $row['status'] = ($paidAmount >= $netAmount) ? 'PAID' : 'PENDING';
        $row['original_amount'] = $originalAmount;
        $row['scholarship_amount'] = $scholarshipAmount;
        $row['net_amount'] = $netAmount;
        
        $allBalances[] = $row;
        $totalAmount += $originalAmount;
        $totalPaid += $paidAmount;
        $totalScholarship += $scholarshipAmount;
        $totalNetAmount += $netAmount;
        $totalRemaining += $row['remaining_amount'];
    }
    
    if (count($allBalances) > 0) {
        $adminDetails = [
            'school' => $school,
            'address' => $address,
            'phone' => $phone,
            'email' => $email,
            'web' => $web
        ];
        
        $pdf = generateAllBalancesInvoiceFPDF($allBalances, $bankDetails, $totalAmount, $totalPaid, $totalRemaining, $student, $scholarshipPercentage, $totalScholarship, $totalNetAmount, $adminDetails);
        $pdf->Output('I', 'ALL_INVOICES_' . $student['studentid'] . '_' . date('Ymd') . '.pdf');
        exit();
    }
}

// Get all balances for display
$allBalancesQuery = "SELECT b.* FROM balances b WHERE b.intake = '$intake' AND b.program = '$program' ORDER BY b.year DESC, b.period DESC";
$allBalancesResult = mysqli_query($conn, $allBalancesQuery);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fee Invoices - <?php echo htmlspecialchars($school); ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary: #202342;
            --secondary: #2c3e50;
        }
        
        body {
            font-family: Arial, sans-serif;
            background: #f5f7fa;
            margin: 0;
            padding: 0;
        }
        
        .content {
            margin-left: 210px;
            padding: 20px;
            min-height: 100vh;
        }
        
        .header-section {
            background: var(--primary);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .invoice-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.08);
            margin-bottom: 20px;
            overflow: hidden;
        }
        
        .card-header {
            background: #2c3e50;
            color: white;
            padding: 15px 20px;
            font-weight: 600;
        }
        
        .invoice-item {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            align-items: center;
            transition: background 0.3s;
        }
        
        .invoice-item:hover {
            background: #f8f9fa;
        }
        
        .invoice-item:last-child {
            border-bottom: none;
        }
        
        .fee-info {
            flex: 1;
        }
        
        .fee-type {
            font-weight: 600;
            color: #2c3e50;
            font-size: 15px;
        }
        
        .fee-meta {
            font-size: 13px;
            color: #666;
            margin-top: 3px;
        }
        
        .amount-section {
            text-align: right;
            margin-right: 20px;
            min-width: 150px;
        }
        
        .amount {
            font-weight: bold;
            color: #202342;
            font-size: 16px;
        }
        
        .original-amount {
            text-decoration: line-through;
            color: #999;
            font-size: 14px;
            display: block;
        }
        
        .payment-details {
            font-size: 12px;
            color: #666;
            margin-top: 2px;
        }
        
        .status-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin-right: 10px;
        }
        
        .status-paid {
            background: #d4edda;
            color: #155724;
        }
        
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .scholarship-badge {
            background: #28a745;
            color: white;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            margin-left: 5px;
        }
        
        .year-header {
            background: #e3f2fd;
            color: #2c3e50;
            padding: 10px 20px;
            font-weight: 600;
            border-left: 4px solid #202342;
        }
        
        .btn-download {
            background: #202342;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            font-size: 13px;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            transition: all 0.3s;
            text-decoration: none;
        }
        
        .btn-download:hover {
            background: #b83544;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 3px 10px rgba(208, 63, 77, 0.3);
            text-decoration: none;
        }
        
        .btn-download-all {
            background: #28a745;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }
        
        .btn-download-all:hover {
            background: #218838;
            transform: translateY(-2px);
            box-shadow: 0 3px 10px rgba(40, 167, 69, 0.3);
        }
        
        .bank-info {
            background: #e8f4ff;
            border-radius: 8px;
            padding: 20px;
            margin-top: 30px;
            border-left: 5px solid #202342;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #6c757d;
        }
        
        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
        }
        
        .print-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            background: #202342;
            color: white;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            cursor: pointer;
            z-index: 1000;
            transition: all 0.3s;
        }
        
        .print-btn:hover {
            background: #b83544;
            transform: scale(1.1);
        }
        
        .scholarship-header {
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
            color: #155724;
            padding: 10px 20px;
            border-radius: 8px;
            margin-bottom: 15px;
            border-left: 5px solid #28a745;
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            
            .print-btn {
                display: none !important;
            }
        }
        
        @media (max-width: 768px) {
            .content {
                margin-left: 0;
                padding: 15px;
            }
            
            .invoice-item {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .amount-section {
                margin: 10px 0;
                text-align: left;
            }
        }
        .content{
            padding: 15px !important;
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php";?> 
    <div class="content">
        <!-- Header -->
        <div class="header-section">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h4 class="mb-2"><i class="fas fa-file-invoice me-2"></i>Fee Invoices</h4>
                    <p class="mb-0">
                        <strong>Student:</strong> <?php echo htmlspecialchars($student['studentname']); ?> | 
                        <strong>ID:</strong> <?php echo $student['studentid']; ?> | 
                        <strong>Program:</strong> <?php echo htmlspecialchars($program); ?>
                        <?php if ($scholarshipPercentage > 0): ?>
                            | <strong>Scholarship:</strong> <?php echo $scholarshipPercentage; ?>%
                        <?php endif; ?>
                    </p>
                </div>
                
            </div>
        </div>

        <!-- Scholarship Info Banner -->
        <?php if ($scholarshipPercentage > 0): ?>
        <div class="scholarship-header">
            <div class="d-flex align-items-center">
                <i class="fas fa-award fa-2x me-3"></i>
                <div>
                    <h5 class="mb-1"><?php echo $scholarshipPercentage; ?>% Scholarship Applied</h5>
                    <p class="mb-0">Your scholarship discount has been applied to all fee invoices below.</p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Invoices List -->
        <div class="invoice-card">
            <?php if (mysqli_num_rows($allBalancesResult) > 0): ?>
                <?php
                mysqli_data_seek($allBalancesResult, 0);
                $currentYear = '';
                while ($balance = mysqli_fetch_assoc($allBalancesResult)) {
                    // Apply scholarship discount
                    $originalAmount = $balance['amount'];
                    if ($scholarshipPercentage > 0) {
                        $scholarshipAmount = ($originalAmount * $scholarshipPercentage) / 100;
                        $netAmount = $originalAmount - $scholarshipAmount;
                    } else {
                        $scholarshipAmount = 0;
                        $netAmount = $originalAmount;
                    }
                    
                    $paymentQuery = "SELECT SUM(amount) as paid_amount FROM payments WHERE studentid = '$userlogin' AND fee_type = '{$balance['fee_type']}' AND year = '{$balance['year']}' AND period = '{$balance['period']}'";
                    $paymentResult = mysqli_query($conn, $paymentQuery);
                    $paymentData = mysqli_fetch_assoc($paymentResult);
                    $paidAmount = $paymentData['paid_amount'] ?? 0;
                    
                    $remainingAmount = max(0, $netAmount - $paidAmount);
                    $status = ($paidAmount >= $netAmount) ? 'PAID' : 'PENDING';
                    $statusClass = ($status == 'PAID') ? 'status-paid' : 'status-pending';
                    
                    if ($currentYear != $balance['year']) {
                        $currentYear = $balance['year'];
                        echo '<div class="year-header">
                            <i class="fas fa-calendar-alt me-2"></i>ACADEMIC YEAR ' . $currentYear . '
                        </div>';
                    }
                    
                    echo '<div class="invoice-item">
                        <div class="fee-info">
                            <div class="fee-type">
                                ' . strtoupper(htmlspecialchars($balance['fee_type'])) . '
                                <span class="status-badge ' . $statusClass . '">' . $status . '</span>';
                    
                    if ($scholarshipPercentage > 0) {
                        echo '<span class="scholarship-badge">' . $scholarshipPercentage . '% Scholarship</span>';
                    }
                    
                    echo '</div>
                            <div class="fee-meta">
                                Semester ' . htmlspecialchars($balance['period']) . ' | ' . getFeeDescription($balance['fee_type']) . '
                            </div>
                        </div>
                        <div class="amount-section">
                            <div class="amount">';
                    
                    if ($scholarshipPercentage > 0) {
                        echo '<span class="original-amount">ZMW ' . number_format($originalAmount, 2) . '</span>';
                        echo 'ZMW ' . number_format($netAmount, 2);
                    } else {
                        echo 'ZMW ' . number_format($netAmount, 2);
                    }
                    
                    echo '</div>
                            <div class="payment-details">
                                Paid: <span style="color: #28a745;">ZMW ' . number_format($paidAmount, 2) . '</span> | 
                                Balance: <span style="color: #dc3545;">ZMW ' . number_format($remainingAmount, 2) . '</span>
                            </div>
                        </div>
                        <div>
                            <a href="?download_invoice&id=' . $balance['id'] . '" class="btn-download">
                                <i class="fas fa-file-pdf"></i> PDF
                            </a>
                        </div>
                    </div>';
                }
                ?>
            <?php else: ?>
                <div class="empty-state">
                    <i class="fas fa-file-invoice-dollar"></i>
                    <h5>No invoices found</h5>
                    <p>No fee invoices for <?php echo htmlspecialchars($program); ?> - <?php echo htmlspecialchars($intake); ?></p>
                </div>
            <?php endif; ?>
        </div>

        <!-- Bank Information -->
        <div class="bank-info">
            <h5><i class="fas fa-university me-2"></i>Bank Payment Information</h5>
            <div class="row mt-3">
                <div class="col-md-6">
                    <p><strong>Bank Name:</strong> <?php echo $bankDetails['bank_name']; ?></p>
                    <p><strong>Account Name:</strong> <?php echo $bankDetails['account_name']; ?></p>
                    <p><strong>Account Number:</strong> <?php echo $bankDetails['account_number']; ?></p>
                </div>
                <div class="col-md-6">
                    <p><strong>Branch:</strong> <?php echo $bankDetails['branch']; ?></p>
                    <p><strong>Branch Code:</strong> <?php echo $bankDetails['branch_code']; ?></p>
                    <p><strong>Reference:</strong> Your Student ID: <strong><?php echo $student['studentid']; ?></strong></p>
                </div>
            </div>
            <div class="alert alert-warning mt-3 mb-0">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <strong>Important:</strong> Always use your Student ID as payment reference.
            </div>
        </div>
    </div>

    <!-- Print Button -->
    <div class="print-btn no-print" onclick="window.print()" title="Print Page">
        <i class="fas fa-print"></i>
    </div>
                <br><br><br><br>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        window.onbeforeprint = function() {
            document.querySelectorAll('.no-print').forEach(el => el.style.display = 'none');
        };
        window.onafterprint = function() {
            document.querySelectorAll('.no-print').forEach(el => el.style.display = '');
        };
    </script>
</body>
</html>