<?php
require_once("../../dompdf/vendor/autoload.php"); 
require_once("../../includes/config.php");
use Dompdf\Dompdf;
use Dompdf\Options;

$sid = $_GET['student_id'] ?? null;
$yid = $_GET['academic_year_id'] ?? (defined('APP_YEAR_ID') ? APP_YEAR_ID : null);

// 1. Fetch Student & School Details (Stream Join Removed)
$school = $pdo->query("SELECT * FROM school_settings LIMIT 1")->fetch();
$student = $pdo->prepare("SELECT s.*, e.roll_no, c.class_name, m.medium_name 
    FROM students s 
    JOIN enrollments e ON s.id = e.student_id 
    JOIN classes c ON e.class_id = c.id 
    LEFT JOIN mediums m ON e.medium_id = m.id
    WHERE s.id = ? AND e.academic_year_id = ?");
$student->execute([$sid, $yid]);
$sInfo = $student->fetch();

// 2. Fetch History
$history = $pdo->prepare("SELECT fa.*, ft.fee_title,
    IFNULL((SELECT SUM(amount_paid) FROM fee_payments WHERE fee_assign_id = fa.id), 0) as paid,
    IFNULL((SELECT SUM(discount_amount) FROM fee_payments WHERE fee_assign_id = fa.id), 0) as discount
    FROM fee_assign fa 
    JOIN fee_types ft ON fa.fee_type_id = ft.id
    JOIN enrollments e ON fa.student_id = e.student_id
    WHERE fa.student_id = ? AND e.academic_year_id = ?
    ORDER BY fa.id ASC");
$history->execute([$sid, $yid]);
$rows = $history->fetchAll();

ob_start();
?>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style>
        body { font-family: 'Helvetica', sans-serif; font-size: 11px; color: #333; }
        .header { text-align: center; margin-bottom: 20px; border-bottom: 2px solid #444; padding-bottom: 10px; }
        .student-info { margin-bottom: 20px; width: 100%; border-bottom: 1px solid #eee; padding-bottom: 10px; }
        .student-info td { padding: 4px 0; }
        
        table.data-table { width: 100%; border-collapse: collapse; }
        table.data-table th { background-color: #f2f2f2; border: 1px solid #ccc; padding: 8px; font-weight: bold; }
        table.data-table td { border: 1px solid #ccc; padding: 8px; }
        
        .text-left { text-align: left; }
        .text-right { text-align: right; }
        .text-center { text-align: center; }
        .footer-row { background: #eeeeee; font-weight: bold; }
        .rs-symbol { font-family: DejaVu Sans, sans-serif; } 
    </style>
</head>
<body>

<div class="header">
    <h2 style="margin:0;"><?php echo strtoupper($school['school_name']); ?></h2>
    <p style="margin:5px 0;">Student Fee Ledger Statement</p>
</div>

<table class="student-info">
    <tr>
        <td width="50%"><strong>Student:</strong> <?php echo $sInfo['student_name']; ?></td>
        <td width="50%" class="text-right"><strong>Roll No:</strong> <?php echo $sInfo['roll_no']; ?></td>
    </tr>
    <tr>
        <td><strong>Class:</strong> <?php echo $sInfo['class_name']; ?></td>
        <td class="text-right"><strong>Medium:</strong> <?php echo $sInfo['medium_name'] ?? 'N/A'; ?></td>
    </tr>
    <tr>
        <td><strong>Father's Name:</strong> <?php echo $sInfo['father_name'] ?? 'N/A'; ?></td>
        <td class="text-right"><strong>Date:</strong> <?php echo date('d-M-Y'); ?></td>
    </tr>
</table>

<table class="data-table">
    <thead>
        <tr>
            <th class="text-left">Month</th>
            <th class="text-left">Fee Type</th>
            <th class="text-right">Amount</th>
            <th class="text-right">Discount</th>
            <th class="text-right">Paid</th>
            <th class="text-right">Balance</th>
        </tr>
    </thead>
    <tbody>
        <?php 
        $tA = 0; $tD = 0; $tP = 0;
        foreach($rows as $r): 
            $bal = $r['total_amount'] - ($r['paid'] + $r['discount']);
            $tA += $r['total_amount']; $tD += $r['discount']; $tP += $r['paid'];
        ?>
        <tr>
            <td class="text-left"><?php echo $r['due_month']; ?></td>
            <td class="text-left"><?php echo $r['fee_title']; ?></td>
            <td class="text-right"><span class="rs-symbol">₹</span><?php echo number_format($r['total_amount'], 2); ?></td>
            <td class="text-right"><span class="rs-symbol">₹</span><?php echo number_format($r['discount'], 2); ?></td>
            <td class="text-right"><span class="rs-symbol">₹</span><?php echo number_format($r['paid'], 2); ?></td>
            <td class="text-right"><span class="rs-symbol">₹</span><?php echo number_format(max(0, $bal), 2); ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
    <tfoot>
        <tr class="footer-row">
            <td colspan="2" class="text-center">TOTALS</td>
            <td class="text-right"><span class="rs-symbol">₹</span><?php echo number_format($tA, 2); ?></td>
            <td class="text-right"><span class="rs-symbol">₹</span><?php echo number_format($tD, 2); ?></td>
            <td class="text-right"><span class="rs-symbol">₹</span><?php echo number_format($tP, 2); ?></td>
            <td class="text-right"><span class="rs-symbol">₹</span><?php echo number_format(max(0, $tA - ($tP + $tD)), 2); ?></td>
        </tr>
    </tfoot>
</table>

</body>
</html>
<?php
$html = ob_get_clean();

$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true);
$options->set('defaultFont', 'DejaVu Sans'); 

$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

$dompdf->stream("Statement_{$sInfo['student_name']}.pdf", ["Attachment" => false]);
?>