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

// 1. SET PARAMETERS & FETCH DYNAMIC SESSION START
$current_session_id = defined('APP_YEAR_ID') ? APP_YEAR_ID : 0;

// Fetch the actual start date of the current academic year from the database
$sessionStmt = $pdo->prepare("SELECT start_date FROM academic_years WHERE id = ?");
$sessionStmt->execute([$current_session_id]);
$sessionData = $sessionStmt->fetch();

// Logic: Use DB start_date if found, otherwise fallback to URL param, otherwise fallback to Jan 1st
$startDate = $sessionData['start_date'] ?? ($_GET['start_date'] ?? date('Y-01-01'));
$endDate = date('Y-m-d');

// 2. FETCH SCHOOL INFO
$school = $pdo->query("SELECT * FROM school_settings LIMIT 1")->fetch();

// 3. COLLECTION SUMMARY (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) BETWEEN ? AND ? 
    GROUP BY payment_mode
");
$summaryQuery->execute([$startDate, $endDate]);
$breakdown = $summaryQuery->fetchAll();

// 4. CLASS-WISE REVENUE SUMMARY
$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) BETWEEN ? AND ?
    GROUP BY c.id, c.class_name
    ORDER BY c.id ASC
");
$classSummaryQuery->execute([$current_session_id, $startDate, $endDate]);
$class_breakdown = $classSummaryQuery->fetchAll();

// 5. TRANSACTION DETAILS (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) BETWEEN ? AND ?
    ORDER BY fp.payment_date ASC, fp.id ASC
");
$detailQuery->execute([$current_session_id, $startDate, $endDate]);
$transactions = $detailQuery->fetchAll();

ob_start();
?>
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: 'DejaVu Sans', sans-serif; font-size: 11px; color: #333; line-height: 1.4; }
        .header { text-align: center; border-bottom: 2px solid #444; padding-bottom: 10px; margin-bottom: 20px; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 25px; }
        th { background-color: #f2f2f2; border: 1px solid #ccc; padding: 7px; text-align: left; text-transform: uppercase; font-size: 10px; }
        td { border: 1px solid #ccc; padding: 7px; vertical-align: middle; }
        .text-right { text-align: right; }
        .text-center { text-align: center; }
        .section-title { background: #444; color: white; padding: 6px 10px; margin-bottom: 10px; font-weight: bold; font-size: 12px; }
        .rs { font-family: DejaVu Sans; }
        .grand-total { background: #eee; font-weight: bold; font-size: 12px; }
    </style>
</head>
<body>

<div class="header">
    <h2 style="margin:0;"><?php echo strtoupper($school['school_name']); ?></h2>
    <p style="margin:5px 0; font-weight: bold; color: #d63384;">SESSION REVENUE REPORT (UP-TO-DATE)</p>
    <strong>Period: <?php echo date('d-M-Y', strtotime($startDate)); ?> to <?php echo date('d-M-Y', strtotime($endDate)); ?></strong>
</div>

<div class="section-title">1. 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 $totalNet = 0; $totalDisc = 0; $totalTx = 0;
        foreach($breakdown as $row): 
            $totalNet += $row['net_cash']; 
            $totalDisc += $row['total_discount'];
            $totalTx += $row['transactions'];
        ?>
        <tr>
            <td><strong><?php echo strtoupper($row['payment_mode']); ?></strong></td>
            <td class="text-right"><?php echo $row['transactions']; ?></td>
            <td class="text-right text-danger"><span class="rs">₹</span><?php echo number_format($row['total_discount'], 2); ?></td>
            <td class="text-right"><strong><span class="rs">₹</span><?php echo number_format($row['net_cash'], 2); ?></strong></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
    <tr class="grand-total">
        <td>GRAND TOTAL</td>
        <td class="text-right"><?php echo $totalTx; ?></td>
        <td class="text-right"><span class="rs">₹</span><?php echo number_format($totalDisc, 2); ?></td>
        <td class="text-right"><span class="rs">₹</span><?php echo number_format($totalNet, 2); ?></td>
    </tr>
</table>

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

<div class="section-title">3. Detailed Transaction Log</div>
<table>
    <thead>
        <tr>
            <th style="width: 12%;">Date</th>
            <th style="width: 15%;">Receipt #</th>
            <th>Student Name</th>
            <th>Class</th>
            <th style="width: 10%;">Mode</th>
            <th style="width: 15%;" class="text-right">Amount</th>
        </tr>
    </thead>
    <tbody>
        <?php if(empty($transactions)): ?>
            <tr><td colspan="6" class="text-center">No records found for the selected period.</td></tr>
        <?php else: ?>
            <?php foreach($transactions as $t): ?>
            <tr>
                <td style="font-size: 9px;"><?php echo date('d-m-Y', strtotime($t['payment_date'])); ?></td>
                <td style="font-weight: bold;"><?php echo $t['receipt_number']; ?></td>
                <td><?php echo strtoupper($t['student_name']); ?></td>
                <td><?php echo $t['class_name']; ?></td>
                <td class="text-center"><?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: 40px; 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 30px; font-weight: bold;">Authorized Signature</span>
</div>

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