<?php
session_start();
$con = new mysqli("localhost", "underwat_transparentqdb", "Police2345@1", "underwat_transparentqdb");
/* $con = new mysqli("localhost", "underwat_uplinepj", "Police2345@1", "underwat_jetinstantTQ"); */
if ($con->connect_error) die("Connection failed: " . $con->connect_error);

$PID = $_GET['project_ref'] ?? $_POST['pid'] ?? $_SESSION['pid'] ?? '';
if (!empty($PID)) {
    $_SESSION['pid'] = $PID;
}

/* ---------- Handle inline updates (unchanged) ---------- */
if (isset($_POST['update_materials'])) {
    foreach ($_POST['materials_id'] as $i => $id) {
        $qty = $_POST['materials_qty'][$i];
        $extra = $_POST['materials_extra'][$i];
        $price = $_POST['materials_price'][$i];
        $con->query("UPDATE foundation_materials SET COEQuantity='$qty', Extra='$extra', Price='$price' WHERE PID='$id'");
    }
}
if (isset($_POST['update_labour'])) {
    foreach ($_POST['labour_id'] as $i => $id) {
        $qty = $_POST['labour_qty'][$i];
        $price = $_POST['labour_price'][$i];
        $con->query("UPDATE foundation_labourer SET COEQuantity='$qty', Price='$price' WHERE PID='$id'");
    }
}
if (isset($_POST['update_equipment'])) {
    foreach ($_POST['equipment_id'] as $i => $id) {
        $qty = $_POST['equipment_qty'][$i];
        $price = $_POST['equipment_price'][$i];
        $con->query("UPDATE foundation_equipment SET Quantity='$qty', Price='$price' WHERE PID='$id'");
    }
}

/* ---------- Fetch data for page and PDF ---------- */
$project_info = $con->query("SELECT * FROM upline_app_project_info WHERE project_ref='$PID'")->fetch_assoc();
$materials_result = $con->query("SELECT * FROM foundation_materials WHERE PID='$PID'");
$labour_result = $con->query("SELECT * FROM foundation_labourer WHERE PID='$PID'");
$equipment_result = $con->query("SELECT * FROM foundation_equipment WHERE PID='$PID'");

$material_data = $materials_result->fetch_all(MYSQLI_ASSOC);
$labour_data = $labour_result->fetch_all(MYSQLI_ASSOC);
$equipment_data = $equipment_result->fetch_all(MYSQLI_ASSOC);

/* ---------- Server-side PDF Export (FPDF) ---------- */
if (isset($_POST['export_pdf_v2'])) {

    // Normalize data to simple arrays for PDF renderer
    $materials_for_pdf = [];
    foreach ($material_data as $r) {
        $materials_for_pdf[] = [
            'description' => $r['MaterialDescription'] ?? '',
            'quantity' => floatval($r['COEQuantity'] ?? 0),
            'price' => floatval($r['Price'] ?? 0)
        ];
    }
    $equipment_for_pdf = [];
    foreach ($equipment_data as $r) {
        $equipment_for_pdf[] = [
            'description' => $r['EquipmentDescription'] ?? '',
            'quantity' => floatval($r['Quantity'] ?? 0),
            'price' => floatval($r['Price'] ?? 0)
        ];
    }
    $labour_for_pdf = [];
    foreach ($labour_data as $r) {
        $labour_for_pdf[] = [
            'description' => $r['LabourerDescription'] ?? '',
            'quantity' => floatval($r['COEQuantity'] ?? 0),
            'price' => floatval($r['Price'] ?? 0)
        ];
    }

    $pdf_project = [
        'name' => $project_info['project_name'] ?? '',
        'type' => $project_info['project_type'] ?? '',
        'developer' => $project_info['project_developer'] ?? '',
        'location' => $project_info['project_address'] ?? '',
        'reference' => $project_info['project_ref'] ?? '',
        'client_name' => $project_info['client_name'] ?? ''
    ];

    // Ensure FPDF is available
    require_once __DIR__ . '/fpdf/fpdf.php'; // adjust path if needed

    // Load logo image and convert to base64 string
    $imgPath = __DIR__ . '/WhatsApp Image 2025-09-25 at 12.16.46.jpeg';
    $logo_b64_string = '';
    if (file_exists($imgPath)) {
        $logo_b64_string = base64_encode(file_get_contents($imgPath));
    }

    /* ----------------- Extended PDF class with alpha (transparency) support -----------------
       This class adds SetAlpha() and the necessary PDF resource entries so we can render
       a faint watermark (FPDF doesn't support transparency out of the box).
       Source pattern is common for FPDF alpha extensions.
    --------------------------------------------------------------------------------------- */
    class PDF_WithAlpha extends FPDF {
        protected $extgstates = array();
        protected $extgstateobj = array();

        // Set transparency: $alpha between 0 (transparent) and 1 (opaque)
        function SetAlpha($alpha, $bm='Normal') {
            // ensure alpha range
            if ($alpha < 0) $alpha = 0;
            if ($alpha > 1) $alpha = 1;
            $gs = $this->AddExtGState(array('ca'=>$alpha, 'CA'=>$alpha, 'BM'=>'/'.$bm));
            $this->SetExtGState($gs);
        }

        // Add an extended graphic state
        function AddExtGState($parms) {
            $n = count($this->extgstates) + 1;
            $this->extgstates[$n] = $parms;
            return $n;
        }

        // Output command to set extgstate
        function SetExtGState($gs) {
            $this->_out(sprintf('/GS%d gs', $gs));
        }

        // write extgstate objects
        function _putextgstates() {
            for ($i = 1; $i <= count($this->extgstates); $i++) {
                $this->_newobj();
                $this->extgstateobj[$i] = $this->n;
                $this->_out('<<');
                foreach ($this->extgstates[$i] as $k => $v) {
                    if ($k == 'BM') {
                        $this->_out('/' . $k . ' ' . $v);
                    } else {
                        $this->_out('/' . $k . ' ' . sprintf('%.3F', $v));
                    }
                }
                $this->_out('>>');
                $this->_out('endobj');
            }
        }

        // add extgstates to resource dictionary
        function _putresourcedict() {
            parent::_putresourcedict();
            if (!empty($this->extgstateobj)) {
                $this->_out('/ExtGState <<');
                for ($i = 1; $i <= count($this->extgstateobj); $i++) {
                    $this->_out('/GS' . $i . ' ' . $this->extgstateobj[$i] . ' 0 R');
                }
                $this->_out('>>');
            }
        }

        // ensure PDF version supports extgstate
        function _enddoc() {
            if (!empty($this->extgstateobj) && $this->PDFVersion < '1.4') {
                $this->PDFVersion = '1.4';
            }
            parent::_enddoc();
        }
    }

    /* ----------------- PDF generation using the extended class ----------------- */
    function exportToPDFv2_server($projectInfo, $materials, $equipment, $labourers, $logo_b64) {
        // Prepare temporary logo file from base64
        $tmpLogo = sys_get_temp_dir() . '/upline_logo_tmp.jpg';
        if (!empty($logo_b64)) {
            // some inputs may be raw base64 without data: prefix, handle both
            $clean = preg_replace('#^data:image/\w+;base64,#i', '', $logo_b64);
            file_put_contents($tmpLogo, base64_decode($clean));
        } else {
            $tmpLogo = '';
        }

        // Create PDF object (extended)
        $pdf = new PDF_WithAlpha('P', 'mm', 'A4');
        $pdf->SetAutoPageBreak(true, 15);
        $pdf->AddPage();

        // ---------- Watermark on every page ----------
        // We'll draw the watermark by adding it in Header for each page.
        // To do that we use a closure to add watermark after creating pages.
        // Simpler approach: draw watermark now (works for single page) and for subsequent pages we add before adding content.
        // We'll implement watermark by setting alpha, drawing image centered, then resetting alpha on each page when needed.

        // Draw logo (top-left) and left-aligned header text (no overlap)
        $marginLeft = 12;
        if (!empty($tmpLogo) && file_exists($tmpLogo)) {
            // Logo at top-left
            $pdf->Image($tmpLogo, $marginLeft, 12, 30);
            // Start header text to the right of the logo
            $textX = $marginLeft + 36; // give some space after logo
        } else {
            // no logo; start at left margin
            $textX = $marginLeft;
        }

        // Header text (left-aligned, not centered)
        $pdf->SetXY($textX, 12);
        $pdf->SetFont('Arial', 'B', 14);
        $pdf->Cell(0, 6, 'UPLINE INNOVATION CYCLE LTD.', 0, 1, 'L');

        $pdf->SetX($textX);
        $pdf->SetFont('Arial', '', 9);
        $pdf->Cell(0, 5, 'No.1 Boundary Between Otokutu & Egbo Uvwie Communities, Along Otokutu - Egbo Road, Delta State, Nigeria', 0, 1, 'L');

        $pdf->SetX($textX);
        $pdf->Cell(0, 5, 'Email: we@upline.works   |   Website: www.upline.works', 0, 1, 'L');

        $pdf->SetX($textX);
        $pdf->SetFont('Arial','I',9);
        $pdf->Cell(0, 5, 'Building the Future with Innovation and Integrity', 0, 1, 'L');

        // Divider
        $pdf->Ln(3);
        $pdf->SetDrawColor(30, 144, 255); // blue
        $pdf->SetLineWidth(0.6);
        $pdf->Line($marginLeft, $pdf->GetY(), 210 - $marginLeft, $pdf->GetY());
        $pdf->Ln(6);

        // ----------------- WATERMARK (centered, faint) -----------------
        if (!empty($tmpLogo) && file_exists($tmpLogo)) {
            // Set low alpha
            $pdf->SetAlpha(0.05);
            // Calculate centered X for a wide watermark (140mm width)
            $wmWidth = 140;
            $wmX = (210 - $wmWidth) / 2;
            $wmY = 80; // vertical placement
            $pdf->Image($tmpLogo, $wmX, $wmY, $wmWidth);
            // reset alpha back to opaque
            $pdf->SetAlpha(1);
        }

        // ----------------- Project Info Block -----------------
        $pdf->SetFont('Arial','B',12);
        $pdf->Cell(0, 6, 'FOUNDATION REPORT', 0, 1, 'L');
        $pdf->Ln(2);
        $pdf->SetFont('Arial','',11);
        $pdf->Cell(45, 6, 'Project Name:', 0, 0);
        $pdf->Cell(0, 6, $projectInfo['name'] ?? '', 0, 1);
        $pdf->Cell(45, 6, 'Project Type:', 0, 0);
        $pdf->Cell(0, 6, $projectInfo['type'] ?? '', 0, 1);
        $pdf->Cell(45, 6, 'Developer:', 0, 0);
        $pdf->Cell(0, 6, $projectInfo['developer'] ?? '', 0, 1);
        $pdf->Cell(45, 6, 'Location:', 0, 0);
        $pdf->Cell(0, 6, $projectInfo['location'] ?? '', 0, 1);
        $pdf->Cell(45, 6, 'Project REF:', 0, 0);
        $pdf->Cell(0, 6, $projectInfo['reference'] ?? '', 0, 1);
        $pdf->Ln(4);

        // ----------------- Table renderer (blue headers) -----------------
        $renderTable = function($pdf, $title, $rows) {
            // Title band
            $pdf->SetFont('Arial','B',11);
            $pdf->SetFillColor(30,144,255);
            $pdf->SetTextColor(255,255,255);
            $pdf->Cell(0, 8, '  ' . strtoupper($title), 0, 1, 'L', true);

            // Column headers
            $pdf->SetFont('Arial','B',10);
            $pdf->SetFillColor(240,240,240);
            $pdf->SetTextColor(0,0,0);
            $pdf->Cell(10, 7, '#', 1, 0, 'C', true);
            $pdf->Cell(90, 7, 'Description', 1, 0, 'L', true);
            $pdf->Cell(20, 7, 'Qty', 1, 0, 'C', true);
            $pdf->Cell(30, 7, 'Unit Price', 1, 0, 'R', true);
            $pdf->Cell(40, 7, 'Total', 1, 0, 'R', true);
            $pdf->Ln();

            $pdf->SetFont('Arial','',10);
            $subtotal = 0;
            $i = 1;
            foreach ($rows as $r) {
                if ($pdf->GetY() > 260) { 
                    // If we need a new page, draw watermark on next page too
                    $pdf->AddPage();
                    // After AddPage(), re-draw the watermark on the new page:
                    if (!empty($GLOBALS['__tmp_logo_for_pdf']) && file_exists($GLOBALS['__tmp_logo_for_pdf'])) {
                        $pdf->SetAlpha(0.05);
                        $wmWidth = 140;
                        $wmX = (210 - $wmWidth) / 2;
                        $wmY = 80;
                        $pdf->Image($GLOBALS['__tmp_logo_for_pdf'], $wmX, $wmY, $wmWidth);
                        $pdf->SetAlpha(1);
                    }
                }
                $total = floatval($r['quantity']) * floatval($r['price']);
                $subtotal += $total;

                $pdf->Cell(10, 7, $i++, 1, 0, 'C');
                $pdf->Cell(90, 7, (strlen($r['description'])>60?substr($r['description'],0,57).'...':$r['description']), 1, 0, 'L');
                $pdf->Cell(20, 7, (int)$r['quantity'], 1, 0, 'C');
                $pdf->Cell(30, 7, number_format($r['price'],2), 1, 0, 'R');
                $pdf->Cell(40, 7, number_format($total,2), 1, 0, 'R');
                $pdf->Ln();
            }

            // Totals
            $contingency = $subtotal * 0.05;
            $totalWithCont = $subtotal + $contingency;

            $pdf->SetFont('Arial','B',10);
            $pdf->Cell(150, 7, 'Subtotal', 1);
            $pdf->Cell(40, 7, number_format($subtotal,2), 1, 0, 'R');
            $pdf->Ln();
            $pdf->Cell(150, 7, '5% Contingency', 1);
            $pdf->Cell(40, 7, number_format($contingency,2), 1, 0, 'R');
            $pdf->Ln();
            $pdf->Cell(150, 7, 'Total', 1);
            $pdf->Cell(40, 7, number_format($totalWithCont,2), 1, 0, 'R');
            $pdf->Ln(10);

            return $totalWithCont;
        };

        // Render sections
        $matTotal = $renderTable($pdf, 'Materials', $materials);
        $eqpTotal = $renderTable($pdf, 'Equipment', $equipment);
        $labTotal = $renderTable($pdf, 'Labourers', $labourers);

        // Grand total
        $grand = $matTotal + $eqpTotal + $labTotal;
        $pdf->SetFont('Arial','B',12);
        $pdf->Cell(150, 10, 'FOUNDATION TOTAL', 1);
        $pdf->Cell(40, 10, number_format($grand,2), 1, 0, 'R');
        $pdf->Ln(14);

        // Client dynamic
        $pdf->SetFont('Arial','',11);
        $pdf->Cell(0, 6, 'Client: ' . (!empty($projectInfo['client_name']) ? $projectInfo['client_name'] : '______________________________'), 0, 1);
        $pdf->Ln(6);

        // Terms & Conditions (exact sample wording)
        $pdf->SetFont('Arial','B',11);
        $pdf->Cell(0, 6, 'TERMS AND CONDITIONS:', 0, 1);
        $pdf->SetFont('Arial','',10);
        $terms = "1. This Cost Estimate Should be Updated After 7 Days if Not Signed, Due to Market Updates.\n" .
                 "2. All materials supplied and work executed are subject to standard quality control and safety protocols.\n" .
                 "3. Any additional work or modification requested by the client after contract agreement shall attract additional cost.\n" .
                 "4. Payment terms are as stipulated in the signed agreement between the client and Upline Innovation Cycle Ltd.\n" .
                 "5. Upline Innovation Cycle Ltd. shall not be held liable for delays caused by factors beyond its control.\n" .
                 "6. This document is confidential and intended solely for the client listed above.";
        $pdf->MultiCell(0, 6, $terms);

        // Footer
        $pdf->SetY(-25);
        $pdf->SetFont('Arial','I',9);
        $pdf->Cell(0, 5, 'Generated by Upline Innovation Cycle Ltd. — Confidential Document', 0, 1, 'C');

        // Output
        $outputName = 'Foundation_Report_' . (!empty($projectInfo['reference']) ? $projectInfo['reference'] : 'report') . '.pdf';
        $pdf->Output('I', $outputName);

        // cleanup tmp logo
        if (!empty($tmpLogo) && file_exists($tmpLogo)) @unlink($tmpLogo);
    }

    // Prepare base64 string (without data:image prefix)
    $logo_b64_for_func = '';
    if (!empty($logo_b64_string)) {
        $logo_b64_for_func = $logo_b64_string; // already base64 string from file_get_contents
    }

    // store tmp logo path in global (used when creating new pages)
    if (!empty($logo_b64_for_func)) {
        $tmpLogoGlobal = sys_get_temp_dir() . '/upline_logo_tmp.jpg';
        $cleang = preg_replace('#^data:image/\w+;base64,#i', '', $logo_b64_for_func);
        file_put_contents($tmpLogoGlobal, base64_decode($cleang));
        $GLOBALS['__tmp_logo_for_pdf'] = $tmpLogoGlobal;
    } else {
        $GLOBALS['__tmp_logo_for_pdf'] = '';
    }

    // Call generator
    exportToPDFv2_server($pdf_project, $materials_for_pdf, $equipment_for_pdf, $labour_for_pdf, $logo_b64_for_func);

    exit; // stop further output since PDF already sent
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Foundation Report</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>
</head>
<body class="bg-gray-100 p-6">
<form method="POST">
<div class="max-w-6xl mx-auto bg-white shadow p-6 rounded-xl" id="reportContent">
    <div class="flex justify-end mb-4">
      <a href="dashboard.php" class="no-print text-blue-600 hover:underline text-sm font-semibold">← Back to Dashboard</a>
    </div>

    <h2 class="text-2xl font-bold mb-4">Foundation Report</h2>

    <?php if ($project_info): ?>
        <div class="mb-4">
            <p><strong>Project Name:</strong> <?= htmlspecialchars($project_info['project_name'] ?? '') ?></p>
            <p><strong>Project Type:</strong> <?= htmlspecialchars($project_info['project_type'] ?? '') ?></p>
            <p><strong>Developer:</strong> <?= htmlspecialchars($project_info['project_developer'] ?? '') ?></p>
            <p><strong>Location:</strong> <?= htmlspecialchars($project_info['project_address'] ?? '') ?></p>
            <p><strong>Project REF:</strong> <?= htmlspecialchars($project_info['project_ref'] ?? '') ?></p>
        </div>
    <?php endif; ?>

    <?php
    function render_editable_section($section, $data, $desc_key, $qty_key, $extra_key, $price_key, $id_key) {
        $subtotal = 0;
        $html = "<h3 class='text-xl font-semibold mt-6 mb-2'>$section</h3><table class='w-full text-sm border' id='{$section}Table'><thead><tr class='bg-gray-200'>
                <th class='border px-2 py-1'>Description</th>
                <th class='border px-2 py-1'>Quantity</th>";
        if ($extra_key) $html .= "<th class='border px-2 py-1'>Extra</th>";
        $html .= "<th class='border px-2 py-1'>Price</th><th class='border px-2 py-1'>Total</th></tr></thead><tbody>";

        foreach ($data as $i => $row) {
            $qty = $row[$qty_key];
            $extra = $extra_key ? $row[$extra_key] : 0;
            $price = $row[$price_key];
            $total = ($qty + $extra) * $price;
            $subtotal += $total;

            $html .= "<tr>
                <td class='border px-2 py-1'>".htmlspecialchars($row[$desc_key])."</td>
                <td class='border px-2 py-1'><input name='{$section}_qty[]' value='".htmlspecialchars($qty)."' class='w-full border rounded px-1'/></td>";
            if ($extra_key) $html .= "<td class='border px-2 py-1'><input name='{$section}_extra[]' value='".htmlspecialchars($extra)."' class='w-full border rounded px-1'/></td>";
            $html .= "<td class='border px-2 py-1'><input name='{$section}_price[]' value='".htmlspecialchars($price)."' class='w-full border rounded px-1'/></td>
                      <td class='border px-2 py-1 text-right'>".number_format($total,2)."</td>
            </tr>";
            $html .= "<input type='hidden' name='{$section}_id[]' value='".htmlspecialchars($row[$id_key])."' />";
        }

        $contingency = $subtotal * 0.05;
        $grand = $subtotal + $contingency;
        $html .= "</tbody></table>
                  <div class='text-right mt-2 font-medium'>Subtotal: NGN ".number_format($subtotal, 2)."</div>
                  <div class='text-right font-medium'>5% Contingency: NGN ".number_format($contingency, 2)."</div>
                  <div class='text-right font-bold'>Total ($section): NGN ".number_format($grand, 2)."</div>
                  <div class='text-right mt-2'><button name='update_$section' class='bg-yellow-500 text-white px-4 py-1 rounded'>Save $section</button></div>";
        echo $html;
        return $grand;
    }

    $total_material = render_editable_section('materials', $material_data, 'MaterialDescription', 'COEQuantity', 'Extra', 'Price', 'PID');
    $total_labour = render_editable_section('labour', $labour_data, 'LabourerDescription', 'COEQuantity', null, 'Price', 'PID');
    $total_equipment = render_editable_section('equipment', $equipment_data, 'EquipmentDescription', 'Quantity', null, 'Price', 'PID');

    $foundation_total = $total_material + $total_labour + $total_equipment;
    ?>
    <div class="mt-6 text-right text-xl font-bold" id="foundation-total">FOUNDATION TOTAL: NGN <?= number_format($foundation_total, 2) ?></div>
</div>
</form>

<div class="mt-6 text-right print:hidden">
    <button onclick="exportToExcel()" class="bg-green-600 text-white px-4 py-2 rounded">Export to Excel</button>
    <button onclick="exportToPDF()" class="bg-blue-600 text-white px-4 py-2 rounded">Export to PDF</button>

    <!-- NEW: server-side styled export -->
    <form method="POST" style="display:inline-block">
      <input type="hidden" name="pid" value="<?= htmlspecialchars($PID) ?>">
      <button type="submit" name="export_pdf_v2" class="bg-indigo-600 text-white px-4 py-2 rounded ml-2">
        Export to PDF v2 (Styled)
      </button>
    </form>
</div>

<script>
function exportToExcel() {
    const tables = document.querySelectorAll("#reportContent table");
    const wb = XLSX.utils.book_new();

    tables.forEach((table, index) => {
        const ws = XLSX.utils.table_to_sheet(table);
        XLSX.utils.book_append_sheet(wb, ws, `Section ${index + 1}`);
    });

    XLSX.writeFile(wb, "Foundation_Report.xlsx");
}

async function exportToPDF() {
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF('p', 'pt', 'a4');
    let y = 40;

    // Project Info
    const projectInfo = [
        "Project Name: " + document.querySelector("p:nth-child(1)")?.innerText,
        "Project Type: " + document.querySelector("p:nth-child(2)")?.innerText,
        "Developer: " + document.querySelector("p:nth-child(3)")?.innerText,
        "Location: " + document.querySelector("p:nth-child(4)")?.innerText,
        "Project REF: " + document.querySelector("p:nth-child(5)")?.innerText
    ];

    doc.setFontSize(12);
    projectInfo.forEach(line => {
        doc.text(line, 40, y);
        y += 15;
    });
    y += 10;

    const tables = document.querySelectorAll("#reportContent table");

    for (const table of tables) {
        const sectionTitle = table.previousElementSibling?.innerText || "Section";
        doc.setFontSize(13);
        doc.text(sectionTitle, 40, y);
        y += 10;

        // Clone table & replace inputs with text
        const clone = table.cloneNode(true);
        clone.querySelectorAll("input").forEach(input => {
            const text = document.createTextNode(input.value);
            input.parentNode.replaceChild(text, input);
        });

        await doc.autoTable({
            html: clone,
            startY: y,
            theme: 'grid',
            headStyles: { fillColor: [100, 149, 237] },
            styles: { fontSize: 9, cellPadding: 3 },
            didDrawPage: function (data) {
                y = data.cursor.y + 10;
            }
        });

        // ONLY get summary for THIS section — the next 3 divs after the table
        let next = table.nextElementSibling;
        let count = 0;
        while (next && count < 3) {
            if (next.tagName === 'DIV' && next.innerText.includes("NGN")) {
                const text = next.innerText;
                doc.setFontSize(text.includes("Total") ? 11 : 10);
                const textWidth = doc.getTextWidth(text);
                doc.text(text, doc.internal.pageSize.getWidth() - 40 - textWidth, y);
                y += 14;
                count++;
            }
            next = next.nextElementSibling;
        }

        y += 20;
    }

    // Add FOUNDATION TOTAL at the end
    const finalTotal = document.getElementById("foundation-total")?.innerText;
    if (finalTotal) {
        doc.setFontSize(13);
        const textWidth = doc.getTextWidth(finalTotal);
        doc.text(finalTotal, doc.internal.pageSize.getWidth() - 40 - textWidth, y + 20);
    }

    doc.save("Foundation_Report.pdf");
}
</script>
</body>
</html>
