<?php
require_once('includes/auth_check.php');
require("includes/config.php");
$receipt_no = $_GET['receipt_no'] ?? '';

// 1. Get the year_id from URL, fallback to global APP_YEAR_ID if missing
$year_id = isset($_GET['year_id']) ? (int) $_GET['year_id'] : (defined('APP_YEAR_ID') ? APP_YEAR_ID : 0);

// 3. Fetch School Details
$sStmt = $pdo->prepare("SELECT * FROM school_settings WHERE id = 1 LIMIT 1");
$sStmt->execute();
$school = $sStmt->fetch(PDO::FETCH_ASSOC);

$upload_path = "uploads/settings/";

// Fetch Year Name
$yStmt = $pdo->prepare("SELECT year_name FROM academic_years WHERE id = ?");
$yStmt->execute([$year_id]);
$session_name = $yStmt->fetchColumn() ?: date('Y') . '-' . (date('y') + 1);

// 2. Updated SQL Query (Removed Stream Join)
$sql = "SELECT fp.*, ft.fee_title, fa.due_month as due_month, s.student_name, s.father_name, 
               c.class_name, e.roll_no, sec.section_name, m.medium_name 
        FROM fee_payments fp
        JOIN fee_assign fa ON fp.fee_assign_id = fa.id
        JOIN fee_types ft ON fa.fee_type_id = ft.id
        JOIN students s ON fp.student_id = s.id
        JOIN enrollments e ON s.id = e.student_id AND e.academic_year_id = ?
        JOIN classes c ON e.class_id = c.id
        LEFT JOIN sections sec ON e.section_id = sec.id
        LEFT JOIN mediums m ON e.medium_id = m.id
        WHERE fp.receipt_number = ?";

$stmt = $pdo->prepare($sql);
$stmt->execute([$year_id, $receipt_no]);
$payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$payments) {
    die("Invalid Receipt Signature or Record not found.");
}

$first = $payments[0];
$verify_url = "http://localhost/LMS/Admin/verify.php?no=" . $receipt_no;

function getAmountInWords($number) {
    $decimal = round($number - ($no = floor($number)), 2) * 100;
    $hundred = null; $digits_length = strlen($no); $i = 0; $str = array();
    $words = array(0 => '', 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten', 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen', 19 => 'nineteen', 20 => 'twenty', 30 => 'thirty', 40 => 'forty', 50 => 'fifty', 60 => 'sixty', 70 => 'seventy', 80 => 'eighty', 90 => 'ninety');
    $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
    while ($i < $digits_length) {
        $divider = ($i == 2) ? 10 : 100;
        $number = floor($no % $divider);
        $no = floor($no / $divider);
        $i += $divider == 10 ? 1 : 2;
        if ($number) {
            $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
            $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
            $str[] = ($number < 21) ? $words[$number] . ' ' . $digits[$counter] . $plural . ' ' . $hundred : $words[floor($number / 10) * 10] . ' ' . $words[$number % 10] . ' ' . $digits[$counter] . $plural . ' ' . $hundred;
        } else $str[] = null;
    }
    $Rupees = implode('', array_reverse($str));
    $paise = ($decimal > 0) ? "." . ($words[$decimal / 10] . " " . $words[$decimal % 10]) . ' Paise' : '';
    return ucwords(($Rupees ? $Rupees . 'Rupees ' : '') . $paise) . " Only";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Receipt_<?php echo $receipt_no; ?></title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <style>
        @page { size: A5 landscape; margin: 0; }
        body { margin: 0; padding: 0; background: #eee; font-family: 'Segoe UI', Tahoma, sans-serif; }
        .no-print { text-align: center; padding: 10px; background: #333; }
        .btn-print { padding: 8px 20px; background: #27ae60; color: white; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; margin: 0 5px;}
        .receipt-card { width: 210mm; height: 148mm; margin: 0 auto; padding: 10mm; background: #fff; border: 1px solid #000; position: relative; box-sizing: border-box; overflow: hidden; page-break-after: always; }
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px; }
        .school-info h2 { margin: 0; color: #1a237e; font-size: 20px; text-transform: uppercase; }
        .school-info p { margin: 2px 0; font-size: 10px; color: #444; }
        .student-box { width: 100%; margin: 10px 0; font-size: 11px; border-bottom: 1px solid #eee; padding-bottom: 5px; line-height: 1.6; border-collapse: collapse; }
        .fee-table { width: 100%; border-collapse: collapse; font-size: 11px; margin: 10px 0; }
        .fee-table th { background: #f8f9fa; padding: 6px; border: 1px solid #000; text-align: left; }
        .fee-table td { padding: 6px; border: 1px solid #000; }
        .total-section { text-align: right; margin-top: 5px; }
        .words { font-size: 10px; font-style: italic; color: #333; margin-top: 2px; }
        .footer { position: absolute; bottom: 15mm; left: 10mm; right: 10mm; display: flex; justify-content: space-between; align-items: flex-end; }
        .sig-box { text-align: center; width: 180px; }
        .sig-line { border-top: 1px solid #000; margin-bottom: 5px; }
        .sig-text { font-size: 10px; font-weight: bold; }
        .watermark { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(-30deg); font-size: 60px; color: rgba(0, 0, 0, 0.03); font-weight: 900; z-index: 0; pointer-events: none; }
        @media print { body { background: #fff; } .receipt-card { margin: 0; border: 1px solid #000; } .no-print { display: none; } }
    </style>
</head>
<body>
    <div class="no-print">
        <button class="btn-print" onclick="window.print()">Print Receipt</button>
        <button class="btn-print" style="background: #2980b9;" onclick="downloadPDF()">Download PDF</button>
    </div>

    <?php
    $copies = ['OFFICE COPY', 'STUDENT COPY'];
    foreach ($copies as $copy_title):
    ?>
    <div class="receipt-card">
        <div class="watermark"><?php echo $copy_title; ?></div>
        <div class="header">
            <div style="display: flex; align-items: center; gap: 15px;">
                <div class="school-logo">
                    <?php if (!empty($school['school_logo'])): ?>
                        <img src="<?php echo $upload_path . $school['school_logo']; ?>" alt="Logo" style="width: 60px; height: 60px; object-fit: contain;">
                    <?php endif; ?>
                </div>
                <div class="school-info">
                    <h2><?php echo $school['school_name'] ?? 'SCHOOL NAME'; ?></h2>
                    <p><?php echo $school['school_address'] ?? ''; ?></p>
                    <p>Contact: <?php echo $school['phone_number'] ?? ''; ?> | Email: <?php echo $school['email'] ?? ''; ?></p>
                    <p><strong><?php echo $copy_title; ?></strong></p>
                </div>
            </div>
            <div style="text-align: right;">
                <div style="font-size: 10px; color: #666; font-weight: bold;">OFFICIAL RECORD</div>
                <div style="font-size: 18px; font-weight: bold; color: #1a237e;"><?php echo $session_name; ?></div>
            </div>
        </div>

        <table class="student-box">
            <tr>
                <td width="35%"><strong>Student:</strong> <?php echo strtoupper($first['student_name']); ?></td>
                <td width="40%"><strong>Class:</strong> 
                    <?php 
                        echo $first['class_name']; 
                        if ($first['section_name']) echo " (" . $first['section_name'] . ")";
                        if ($first['medium_name']) echo " [" . $first['medium_name'] . "]"; 
                        // REMOVED: stream_name display
                    ?>
                </td>
                <td width="25%" align="right"><strong>Roll No:</strong> <?php echo $first['roll_no']; ?></td>
            </tr>
            <tr>
                <td><strong>Father:</strong> <?php echo $first['father_name']; ?></td>
                <td><strong>Date:</strong> <?php echo date('d-M-Y', strtotime($first['payment_date'])); ?></td>
                <td align="right"><strong>Receipt:</strong> <?php echo $receipt_no; ?></td>
            </tr>
        </table>

        <table class="fee-table">
            <thead>
                <tr>
                    <th>Description</th>
                    <th>Due month</th>
                    <th style="text-align: right;">Original Amount</th>
                    <th style="text-align: right;">Discount</th>
                    <th style="text-align: right;">Net Paid</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $total_paid = 0; $total_discount = 0;
                foreach ($payments as $p):
                    $original_line_total = $p['amount_paid'] + $p['discount_amount'];
                    $total_paid += $p['amount_paid'];
                    $total_discount += $p['discount_amount'];
                ?>
                <tr>
                    <td><?php echo $p['fee_title']; ?></td>
                    <td><?php echo $p['due_month']; ?></td>
                    <td align="right">₹<?php echo number_format($original_line_total, 2); ?></td>
                    <td align="right" style="color: #c0392b;">- ₹<?php echo number_format($p['discount_amount'], 2); ?></td>
                    <td align="right"><strong>₹<?php echo number_format($p['amount_paid'], 2); ?></strong></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="total-section">
            <div style="font-size: 16px;">
                <strong>Net Amount Received: ₹<?php echo number_format($total_paid, 2); ?></strong>
            </div>
            <div class="words">In Words: <?php echo getAmountInWords($total_paid); ?></div>
        </div>

        <div class="footer">
            <div class="sig-box">
                <div class="sig-line"></div>
                <div class="sig-text">Student/Parent</div>
            </div>
            <div style="text-align: center;">
                <img src="https://api.qrserver.com/v1/create-qr-code/?size=60x60&data=<?php echo urlencode($verify_url); ?>" style="opacity: 0.5; width: 45px;" alt="qr">
                <div style="font-size: 8px; color: #999;">Scan to Verify</div>
            </div>
            <div class="sig-box">
                <?php if (!empty($school['principal_signature'])): ?>
                    <img src="<?php echo $upload_path . $school['principal_signature']; ?>" style="max-height: 40px; margin-bottom: -10px;">
                <?php endif; ?>
                <div class="sig-line"></div>
                <div class="sig-text">Accounts Officer</div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>

    <script>
        function downloadPDF() {
            const element = document.querySelector('.receipt-card');
            const opt = {
                margin: 0,
                filename: 'Receipt_<?php echo $receipt_no; ?>.pdf',
                image: { type: 'jpeg', quality: 1 },
                html2canvas: { scale: 3, useCORS: true },
                jsPDF: { unit: 'mm', format: 'a5', orientation: 'landscape' }
            };
            html2pdf().set(opt).from(element).save();
        }
    </script>
</body>
</html>