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

$date = $_GET['date'] ?? date('Y-m-d');
$current_session_id = defined('APP_YEAR_ID') ? APP_YEAR_ID : 0;

// 1. Fetch School Details
$school = $pdo->query("SELECT * FROM school_settings LIMIT 1")->fetch();

// 2. Summary Query (Grouped by Mode)
$summaryQuery = $pdo->prepare("
    SELECT payment_mode, COUNT(id) as transactions, SUM(discount_amount) as total_discount, SUM(amount_paid) as net_cash
    FROM fee_payments WHERE DATE(payment_date) = ? GROUP BY payment_mode
");
$summaryQuery->execute([$date]);
$breakdown = $summaryQuery->fetchAll();

// 3. Class-wise Summary Query
$classSummaryQuery = $pdo->prepare("
    SELECT c.class_name, COUNT(fp.id) as transactions, SUM(fp.amount_paid) as class_total
    FROM fee_payments fp
    LEFT JOIN enrollments e ON fp.student_id = e.student_id AND e.academic_year_id = ?
    LEFT JOIN classes c ON e.class_id = c.id
    WHERE DATE(fp.payment_date) = ?
    GROUP BY c.id, c.class_name
    ORDER BY c.id ASC
");
$classSummaryQuery->execute([$current_session_id, $date]);
$class_breakdown = $classSummaryQuery->fetchAll();

// 4. Transaction Detail Query (Stream Join Removed)
$detailQuery = $pdo->prepare("
    SELECT 
        fp.*, 
        s.student_name, 
        e.roll_no,
        c.class_name
    FROM fee_payments fp
    LEFT JOIN students s ON fp.student_id = s.id
    LEFT JOIN enrollments e ON fp.student_id = e.student_id AND e.academic_year_id = ?
    LEFT JOIN classes c ON e.class_id = c.id
    WHERE DATE(fp.payment_date) = ?
    ORDER BY fp.id ASC
");
$detailQuery->execute([$current_session_id, $date]);
$transactions = $detailQuery->fetchAll();

ob_start();
?>
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: 'DejaVu Sans', sans-serif; font-size: 11px; color: #333; }
        .header { text-align: center; border-bottom: 2px solid #444; padding-bottom: 10px; margin-bottom: 20px; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
        th { background-color: #f2f2f2; border: 1px solid #ccc; padding: 6px; text-align: left; }
        td { border: 1px solid #ccc; padding: 6px; }
        .text-right { text-align: right; }
        .text-center { text-align: center; }
        .section-title { background: #444; color: white; padding: 5px 10px; margin: 20px 0 10px 0; font-size: 13px; }
        .rs { font-family: DejaVu Sans; }
    </style>
</head>
<body>

<div class="header">
    <h2 style="margin:0;"><?php echo strtoupper($school['school_name']); ?></h2>
    <p style="margin:5px 0;">Daily Revenue & Transaction Report</p>
    <strong>Date: <?php echo date('d-M-Y', strtotime($date)); ?></strong>
</div>

<div class="section-title">Collection Summary (By Mode)</div>
<table>
    <thead>
        <tr>
            <th>Payment Mode</th>
            <th class="text-right">Transactions</th>
            <th class="text-right">Total Discount</th>
            <th class="text-right">Net Collection</th>
        </tr>
    </thead>
    <tbody>
        <?php $tN = 0; foreach($breakdown as $row): $tN += $row['net_cash']; ?>
        <tr>
            <td><?php echo strtoupper($row['payment_mode']); ?></td>
            <td class="text-right"><?php echo $row['transactions']; ?></td>
            <td class="text-right"><span class="rs">₹</span><?php echo number_format($row['total_discount'], 2); ?></td>
            <td class="text-right"><span class="rs">₹</span><?php echo number_format($row['net_cash'], 2); ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
    <tr style="background:#eee; font-weight:bold;">
        <td colspan="3">GRAND TOTAL COLLECTION</td>
        <td class="text-right"><span class="rs">₹</span><?php echo number_format($tN, 2); ?></td>
    </tr>
</table>

<div class="section-title">Class-wise Revenue Summary</div>
<table>
    <thead>
        <tr>
            <th>Class Name</th>
            <th class="text-center">Transactions</th>
            <th class="text-right">Amount Collected</th>
        </tr>
    </thead>
    <tbody>
        <?php if(empty($class_breakdown)): ?>
            <tr><td colspan="3" class="text-center">No class-wise data.</td></tr>
        <?php else: ?>
            <?php foreach($class_breakdown as $cb): ?>
            <tr>
                <td>Class: <?php echo $cb['class_name'] ?: 'Unassigned'; ?></td>
                <td class="text-center"><?php echo $cb['transactions']; ?></td>
                <td class="text-right"><span class="rs">₹</span><?php echo number_format($cb['class_total'], 2); ?></td>
            </tr>
            <?php endforeach; ?>
        <?php endif; ?>
    </tbody>
</table>

<div class="section-title">Transaction Details</div>
<table>
    <thead>
        <tr>
            <th>Receipt</th>
            <th>Roll</th>
            <th>Student Name</th>
            <th>Class</th>
            <th>Mode</th>
            <th class="text-right">Paid</th>
        </tr>
    </thead>
    <tbody>
        <?php if(empty($transactions)): ?>
            <tr><td colspan="6" style="text-align:center;">No transactions recorded for this day.</td></tr>
        <?php else: ?>
            <?php foreach($transactions as $t): ?>
            <tr>
                <td><?php echo $t['receipt_number']; ?></td>
                <td><?php echo $t['roll_no']; ?></td>
                <td><?php echo $t['student_name']; ?></td>
                <td><?php echo $t['class_name']; ?></td>
                <td><?php echo strtoupper($t['payment_mode']); ?></td>
                <td class="text-right" style="font-weight:bold;"><span class="rs">₹</span><?php echo number_format($t['amount_paid'], 2); ?></td>
            </tr>
            <?php endforeach; ?>
        <?php endif; ?>
    </tbody>
</table>

<div style="margin-top: 30px; text-align: right;">
    <p>Report Generated On: <?php echo date('d-M-Y H:i:s'); ?></p>
    <br><br>
    <span style="border-top: 1px solid #000; padding: 5px 20px;">Authorized Signatory</span>
</div>

</body>
</html>
<?php
$html = ob_get_clean();
$options = new Options();
$options->set('defaultFont', 'DejaVu Sans');
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("Daily_Report_$date.pdf", ["Attachment" => false]);
?>