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

/* ---------- Default contingency % ---------- */
$contingency_percent_default = 5;

/* ---------- Resolve project ID ---------- */
$PID = $_GET['project_ref'] ?? $_POST['pid'] ?? $_SESSION['pid'] ?? '';
if (!empty($PID)) {
    $_SESSION['pid'] = $PID;
}

/* ---------- Handle inline updates (safe with SN + PID) ---------- */
$didUpdate = false;

if (isset($_POST['update_materials'])) {
    foreach ($_POST['materials_id'] as $i => $id) {
        $id    = $con->real_escape_string($id);
        // posted qty is the current DB qty (readonly in UI), extra is typed by user
        $qty   = $con->real_escape_string($_POST['materials_qty'][$i] ?? 0);
        $extra = $con->real_escape_string($_POST['materials_extra'][$i] ?? 0);
        $price = $con->real_escape_string($_POST['materials_price'][$i] ?? 0);

        $check = $con->query("SELECT SN FROM foundation_materials WHERE SN='$id' AND PID='$PID'");
        if ($check && $check->num_rows > 0) {
            // Add extra to qty and store new quantity, reset Extra column to 0
            $newQty = floatval($qty) + floatval($extra);
            $con->query("UPDATE foundation_materials 
                         SET COEQuantity='$newQty', Extra='0', Price='$price' 
                         WHERE SN='$id' AND PID='$PID'");
            $didUpdate = true;
        }
    }
}

if (isset($_POST['update_labour'])) {
    foreach ($_POST['labour_id'] as $i => $id) {
        $id    = $con->real_escape_string($id);
        $qty   = $con->real_escape_string($_POST['labour_qty'][$i] ?? 0);
        $price = $con->real_escape_string($_POST['labour_price'][$i] ?? 0);

        $check = $con->query("SELECT SN FROM foundation_labourer WHERE SN='$id' AND PID='$PID'");
        if ($check && $check->num_rows > 0) {
            $con->query("UPDATE foundation_labourer 
                         SET COEQuantity='$qty', Price='$price' 
                         WHERE SN='$id' AND PID='$PID'");
            $didUpdate = true;
        }
    }
}

if (isset($_POST['update_equipment'])) {
    foreach ($_POST['equipment_id'] as $i => $id) {
        $id    = $con->real_escape_string($id);
        $qty   = $con->real_escape_string($_POST['equipment_qty'][$i] ?? 0);
        $price = $con->real_escape_string($_POST['equipment_price'][$i] ?? 0);

        $check = $con->query("SELECT SN FROM foundation_equipment WHERE SN='$id' AND PID='$PID'");
        if ($check && $check->num_rows > 0) {
            $con->query("UPDATE foundation_equipment 
                         SET Quantity='$qty', Price='$price' 
                         WHERE SN='$id' AND PID='$PID'");
            $didUpdate = true;
        }
    }
}

if ($didUpdate) {
    // redirect back to avoid resubmission and to refresh displayed data
    $redirectUrl = $_SERVER['PHP_SELF'] . (!empty($PID) ? '?project_ref=' . urlencode($PID) : '');
    header("Location: $redirectUrl");
    exit;
}

/* ---------- Server-side PDF Export (your original formatted FPDF block) ----------
   NOTE: I preserved your FPDF block exactly and only used the posted contingency_percent
--------------------------------------------------------------------------------- */
if (isset($_POST['export_pdf_v2'])) {

    // Watermark toggle (new)
    $watermark_enabled = isset($_POST['enable_watermark']) && $_POST['enable_watermark'] == "1";

    // Normalize contingency percent from POST
    $contingency_percent = isset($_POST['contingency_percent']) ? floatval($_POST['contingency_percent']) : $contingency_percent_default;

    // Fetch fresh data (so export reflects latest DB)
    $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);

    // Prepare arrays for PDF renderer (same shape as your original)
    $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 (same file path as your original)
    require_once __DIR__ . '/fpdf/fpdf.php';

    // Load logo image (same as your original)
    $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 FPDF class (your original)
    class PDF_WithAlpha extends FPDF {
        protected $extgstates = array();
        protected $extgstateobj = array();
        function SetAlpha($alpha, $bm='Normal') {
            if ($alpha < 0) $alpha = 0;
            if ($alpha > 1) $alpha = 1;
            $gs = $this->AddExtGState(array('ca'=>$alpha, 'CA'=>$alpha, 'BM'=>'/'.$bm));
            $this->SetExtGState($gs);
        }
        function AddExtGState($parms) {
            $n = count($this->extgstates) + 1;
            $this->extgstates[$n] = $parms;
            return $n;
        }
        function SetExtGState($gs) {
            $this->_out(sprintf('/GS%d gs', $gs));
        }
        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');
            }
        }
        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('>>');
            }
        }
        function _enddoc() {
            if (!empty($this->extgstateobj) && $this->PDFVersion < '1.4') {
                $this->PDFVersion = '1.4';
            }
            parent::_enddoc();
        }
    }

    // PDF generator (modified only to accept watermark toggle)
    function exportToPDFv2_server($projectInfo, $materials, $equipment, $labourers, $logo_b64, $contingency_percent, $watermark_enabled) {
        $tmpLogo = sys_get_temp_dir() . '/upline_logo_tmp.jpg';
        if (!empty($logo_b64)) {
            $clean = preg_replace('#^data:image/\w+;base64,#i', '', $logo_b64);
            file_put_contents($tmpLogo, base64_decode($clean));
        } else {
            $tmpLogo = '';
        }

        // make tmp logo path available for new-page drawing as well
        $GLOBALS['__tmp_logo_for_pdf'] = $tmpLogo;

        $pdf = new PDF_WithAlpha('P', 'mm', 'A4');
        $pdf->SetAutoPageBreak(true, 15);
        $pdf->AddPage();

        // ---------- Full-page watermark (faded) - draw BEFORE header so header is on top ----------
        if ($watermark_enabled && !empty($tmpLogo) && file_exists($tmpLogo)) {
            $pdf->SetAlpha(0.02); // very faint
            $pdf->Image($tmpLogo, 0, 0, $pdf->GetPageWidth(), $pdf->GetPageHeight());
            $pdf->SetAlpha(1); // reset alpha so header/logo prints sharp
        }

        // Draw logo (top-left) and left-aligned header text (no overlap)
        $marginLeft = 12;
        if (!empty($tmpLogo) && file_exists($tmpLogo)) {
            // header logo stays sharp
            $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);

        // (previously centered watermark removed â€” full-page watermark already drawn before header)

        $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);

        $renderTable = function($pdf, $title, $rows) use ($contingency_percent, $watermark_enabled) {
            $pdf->SetFont('Arial','B',11);
            $pdf->SetLineWidth(0.15); // thinner table lines(default wasthicker)
            $pdf->SetFillColor(30,144,255);
            $pdf->SetTextColor(255,255,255);
            $pdf->Cell(0, 8, '  ' . strtoupper($title), 0, 1, 'L', true);

            $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) {
                    $pdf->AddPage();
                    if ($watermark_enabled && !empty($GLOBALS['__tmp_logo_for_pdf']) && file_exists($GLOBALS['__tmp_logo_for_pdf'])) {
                        $pdf->SetAlpha(0.02);
                        $pdf->Image($GLOBALS['__tmp_logo_for_pdf'], 0, 0, $pdf->GetPageWidth(), $pdf->GetPageHeight());
                        $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();
            }

            $contingency = $subtotal * ($contingency_percent / 100.0);
            $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, $contingency_percent . '% 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;
        };

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

        $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);

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

        $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);

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

        $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);
    }

    $logo_b64_for_func = '';
    if (!empty($logo_b64_string)) {
        $logo_b64_for_func = $logo_b64_string;
    }

    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'] = '';
    }

    exportToPDFv2_server($pdf_project, $materials_for_pdf, $equipment_for_pdf, $labour_for_pdf, $logo_b64_for_func, $contingency_percent, $watermark_enabled);

    exit; // PDF sent
}
/* ---------- End server-side PDF export block ---------- */

/* ---------- Fetch display data for page ---------- */
$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);
?>
<!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://cdn.tailwindcss.com"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<style>
/* === COLOR PALETTE STYLES (unchanged visual) === */
#palette-toggle {
  position: fixed; bottom: 20px; right: 20px;
  background: #444; color: #fff;
  border: none; border-radius: 50%;
  width: 50px; height: 50px;
  font-size: 20px; cursor: pointer;
  box-shadow: 0 4px 6px rgba(0,0,0,0.2);
  z-index: 1001;
}
#palette-panel {
  position: fixed; bottom: 80px; right: 20px;
  background: #fff; border: 1px solid #ccc;
  border-radius: 12px; padding: 15px;
  width: 260px; box-shadow: 0 4px 10px rgba(0,0,0,0.3);
  display: none; z-index: 1000; cursor: default;
}
#palette-panel h4 {
  margin: 0 0 10px; font-size: 14px; text-align: center;
}
.color-swatch {
  width: 30px; height: 30px; border-radius: 50%;
  display: inline-block; margin: 5px; cursor: pointer;
  border: 2px solid transparent;
}
.color-swatch:hover { border: 2px solid #000; }
#palette-panel button,
#palette-panel select,
#palette-panel input[type=color] {
  margin-top: 10px; width: 100%; padding: 6px;
  border-radius: 6px; border: 1px solid #ccc;
  cursor: pointer;
}

/* === FONT PALETTE STYLES (isolated) === */
#font-toggle {
  position: fixed; bottom: 20px; right: 80px;
  background: #444; color: #fff;
  border: none; border-radius: 50%;
  width: 50px; height: 50px;
  font-size: 16px; cursor: pointer;
  box-shadow: 0 4px 6px rgba(0,0,0,0.2);
  z-index: 1001;
}
#font-panel {
  position: fixed; bottom: 80px; right: 80px;
  background: #fff; border: 1px solid #ccc;
  border-radius: 12px; padding: 15px;
  width: 260px; box-shadow: 0 4px 10px rgba(0,0,0,0.3);
  display: none; z-index: 1000; cursor: default;
}
#font-panel h4 {
  margin: 0 0 10px; font-size: 14px; text-align: center;
}
#font-panel select, #font-panel button {
  margin-top: 10px; width: 100%; padding: 6px;
  border-radius: 6px; border: 1px solid #ccc;
  cursor: pointer;
}

/* small fix for numbers alignment */
input[readonly] { background:#f8fafc; }
  </style>
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Roboto&family=Open+Sans&family=Poppins&family=Lato&family=Montserrat&family=Oswald&family=Raleway&family=Ubuntu&family=Merriweather&family=Playfair+Display&family=Inter&family=Noto+Sans&family=Source+Sans+Pro&family=Nunito&family=Work+Sans&family=Karla&family=Quicksand&family=Rubik&family=Fira+Sans&family=Josefin+Sans&display=swap" rel="stylesheet">
</head>
<body class="bg-gray-100 p-6">
<!-- MAIN update form (contains Save buttons and editable Extra fields) -->
<form method="POST" id="mainForm">
<input type="hidden" name="contingency_percent" id="contingencyHidden" value="<?= htmlspecialchars($contingency_percent_default) ?>">

<div class="max-w-6xl mx-auto bg-white shadow p-6 rounded-xl" id="reportContent">
  <!-- Back to Dashboard button (top-right corner) -->
  <div class="flex justify-end mb-4">
      <a href="javascript:history.back()" class="bg-blue-600 text-white px-3 py-2 rounded hover:bg-blue-700">
    ← Go Back
</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; ?>

  <label class="text-sm font-semibold">Contingency %:</label>
  <input type="number" id="contingencyInput" value="<?= htmlspecialchars($contingency_percent_default) ?>" step="0.1" min="0" class="border rounded px-2 py-1 w-20 text-sm"/>

  <?php
  function render_editable_section($section, $data, $desc_key, $qty_key, $extra_key, $price_key, $contingency_percent) {
      $subtotal = 0;
      $out = "<div class='section mb-4' data-section='".htmlspecialchars($section)."'>";
      $out .= "<h3 class='text-xl font-semibold mt-6 mb-2'>".htmlspecialchars(ucfirst($section))."</h3>";
      $out .= "<table class='w-full text-sm border 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) $out .= "<th class='border px-2 py-1'>Extra</th>";
      $out .= "<th class='border px-2 py-1'>Price</th><th class='border px-2 py-1'>Total</th></tr></thead><tbody>";

      foreach ($data as $row) {
          $qty   = $row[$qty_key];
          // reset displayed Extra to 0 on load (per your requirement)
          $extra = $extra_key ? 0 : 0;
          $price = $row[$price_key];
          $total = ($qty + $extra) * $price;
          $subtotal += $total;

          $out .= "<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-none text-center qty-input' 
    style='background:white; outline:none;' 
    readonly
  />
</td>";
          if ($extra_key) $out .= "<td class='border px-2 py-1'><input name='{$section}_extra[]' value='0' class='w-full border rounded px-1 extra-input'/></td>";
          $out .= "<td class='border px-2 py-1'>
  <input 
    name='{$section}_price[]' 
    value='".htmlspecialchars($price)."' 
    class='w-full border-none text-center price-input' 
    style='background:white; outline:none;' 
    readonly
  />
</td>
                    <td class='border px-2 py-1 text-right total-cell'>".number_format($total,2)."</td>
          </tr>";
          $out .= "<input type='hidden' name='{$section}_id[]' value='".htmlspecialchars($row['SN'])."' />";
      }

      $contingency = $subtotal * ($contingency_percent / 100);
      $grand = $subtotal + $contingency;

      $out .= "</tbody></table>";
      $out .= "<div class='text-right mt-2 font-medium subtotal'>Subtotal: NGN ".number_format($subtotal, 2)."</div>";
      $out .= "<div class='text-right font-medium contingency'>{$contingency_percent}% Contingency: NGN ".number_format($contingency, 2)."</div>";
      $out .= "<div class='text-right font-bold section-total'>Total ($section): NGN ".number_format($grand, 2)."</div>";
      $out .= "<div class='text-right mt-2'><button name='update_{$section}' class='bg-yellow-500 text-white px-4 py-1 rounded'>Save ".htmlspecialchars(ucfirst($section))."</button></div>";
      $out .= "</div>";

      echo $out;
      return $grand;
  }

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

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

</div>
</form> <!-- MAIN FORM CLOSED HERE (so export form won't be nested) -->

<!-- Export form (server-side FPDF) - separate form so it posts correctly -->
<div class="max-w-6xl mx-auto mt-6 text-right">
  <form method="POST" id="exportPdfForm">
    <input type="hidden" name="pid" value="<?= htmlspecialchars($PID) ?>">
    <input type="hidden" name="contingency_percent" id="exportContingencyHidden" value="<?= htmlspecialchars($contingency_percent_default) ?>">

    <label class="mr-2" style="font-size:0.95rem; vertical-align:middle;">
      <input type="checkbox" name="enable_watermark" value="1" checked>
      Include Watermark
    </label>

    <button type="submit" name="export_pdf_v2"  onclick="openPdfPopup()" class="bg-indigo-600 text-white px-4 py-2 rounded ml-2">
      Export to PDF
          </button><script>
function openPdfPopup() {
  // Open a popup window (not full tab)
  const popup = window.open('', 'pdfPopup', 'width=1000,height=800,scrollbars=yes,resizable=yes');
  
  // Get the export form and target it to the popup
  const form = document.getElementById('exportPdfForm');
  form.target = 'pdfPopup';
  
  // Submit to export_pdf.php, which generates and displays the PDF
  form.submit();
}
</script>
  </form>
</div>

<script>
// sync export contingency hidden field when user changes contingency input
$(document).ready(function() {
    $("#contingencyInput").on("input", function() {
        let v = $(this).val();
        $("#contingencyHidden").val(v); // main form (kept for completeness)
        $("#exportContingencyHidden").val(v); // export form
        recalcAll();
    });

    // recalc when user types into Extra only (qty & price are readonly)
    $(document).on("input", ".extra-input", recalcAll);

    recalcAll();
});

function getContingencyPercent() {
  let v = parseFloat($("#contingencyInput").val());
  return isNaN(v) ? 0 : v;
}

function recalcSection($sectionDiv) {
  let subtotal = 0;
  let percent = getContingencyPercent();
  $sectionDiv.find("tbody tr").each(function() {
    let qty   = parseFloat($(this).find(".qty-input").val()) || 0;
    let extra = parseFloat($(this).find(".extra-input").val()) || 0;
    let price = parseFloat($(this).find(".price-input").val()) || 0;
    let total = (qty + extra) * price;
    $(this).find(".total-cell").text(total.toFixed(2));
    subtotal += total;
  });
  let contingency = subtotal * (percent / 100);
  let grand = subtotal + contingency;
  $sectionDiv.find(".subtotal").text("Subtotal: NGN " + subtotal.toFixed(2));
  $sectionDiv.find(".contingency").text(percent + "% Contingency: NGN " + contingency.toFixed(2));
  $sectionDiv.find(".section-total").text("Total (" + $sectionDiv.data("section") + "): NGN " + grand.toFixed(2));
  return grand;
}

function recalcAll() {
  let grandTotal = 0;
  $(".section").each(function() {
    grandTotal += recalcSection($(this));
  });
  $(".foundation-total").text("FOUNDATION TOTAL: NGN " + grandTotal.toFixed(2));
}
</script>

	<!-- ðŸŽ¨ Color + Font Palette (section-targeting integrated) -->
<button id="palette-toggle">ðŸŽ¨</button>
<div id="palette-panel">
  <h4>Customize Page</h4>

  <!-- Target selector (starts with no selection) -->
  <label style="display:block; font-weight:600; margin-bottom:6px;">Target Section:</label>
  <select id="paletteTarget" style="width:100%; padding:6px; border-radius:6px; border:1px solid #ccc;">
    <option value="" selected disabled>â€” choose section â€”</option>
    <option value="all">All (Global)</option>
    <option value="header">Header</option>
    <option value="materials">Materials</option>
    <option value="labour">Labour</option>
    <option value="equipment">Equipment</option>
  </select>

  <div style="margin-top:8px;">
    <div class="color-swatch" style="background:#3498db" data-color="#3498db"></div>
    <div class="color-swatch" style="background:#e74c3c" data-color="#e74c3c"></div>
    <div class="color-swatch" style="background:#2ecc71" data-color="#2ecc71"></div>
    <div class="color-swatch" style="background:#f1c40f" data-color="#f1c40f"></div>
    <div class="color-swatch" style="background:#9b59b6" data-color="#9b59b6"></div>
  </div>

  <input type="color" id="customColor" style="margin-top:8px; width:100%; padding:6px; border-radius:6px; border:1px solid #ccc;">

  <label style="display:block; font-weight:600; margin-top:8px;">Apply To:</label>
  <select id="applyTo" style="width:100%; padding:6px; border-radius:6px; border:1px solid #ccc;">
    <option value="background">Background</option>
    <option value="font">Font color</option>
  </select>

  <div style="margin-top:8px;">
    <button id="resetPalette" style="width:100%; padding:8px; border-radius:6px; border:1px solid #ccc; background:#fff; cursor:pointer;">Reset (selected / all)</button>
  </div>
</div>

<!-- ðŸ”¤ Font Palette -->
<button id="font-toggle">ðŸ”¤</button>
<div id="font-panel">
  <h4>Choose Font</h4>

  <!-- Target selector for fonts (starts with no selection) -->
  <label style="display:block; font-weight:600; margin-bottom:6px;">Target Section:</label>
  <select id="fontTarget" style="width:100%; padding:6px; border-radius:6px; border:1px solid #ccc;">
    <option value="" selected disabled>â€” choose section â€”</option>
    <option value="all">All (Global)</option>
    <option value="header">Header</option>
    <option value="materials">Materials</option>
    <option value="labour">Labour</option>
    <option value="equipment">Equipment</option>
  </select>

  <select id="fontSelector" style="margin-top:8px; width:100%; padding:6px; border-radius:6px; border:1px solid #ccc;">
    <option value="" selected>Default</option>
    <option value="Arial, sans-serif">Arial</option>
    <option value="'Times New Roman', serif">Times New Roman</option>
    <option value="'Poppins', sans-serif">Poppins</option>
    <option value="'Roboto', sans-serif">Roboto</option>
    <option value="'Open Sans', sans-serif">Open Sans</option>
    <option value="'Lato', sans-serif">Lato</option>
    <option value="'Montserrat', sans-serif">Montserrat</option>
    <option value="'Oswald', sans-serif">Oswald</option>
    <option value="'Raleway', sans-serif">Raleway</option>
    <option value="'Ubuntu', sans-serif">Ubuntu</option>
    <option value="'Merriweather', serif">Merriweather</option>
    <option value="'Inter', sans-serif">Inter</option>
    <option value="'Noto Sans', sans-serif">Noto Sans</option>
    <option value="'Source Sans Pro', sans-serif">Source Sans Pro</option>
    <option value="'Nunito', sans-serif">Nunito</option>
    <option value="'Work Sans', sans-serif">Work Sans</option>
    <option value="'Karla', sans-serif">Karla</option>
    <option value="'Quicksand', sans-serif">Quicksand</option>
    <option value="'Rubik', sans-serif">Rubik</option>
    <option value="'Fira Sans', sans-serif">Fira Sans</option>
    <option value="'Josefin Sans', sans-serif">Josefin Sans</option>
  </select>

  <div style="margin-top:8px;">
    <button id="resetFontBtn" style="width:100%; padding:8px; border-radius:6px; border:1px solid #ccc; background:#fff; cursor:pointer;">Reset Font (selected / all)</button>
  </div>
</div>

<script>
/* === SECTION-AWARE PALETTE SCRIPT (integrated) === */

/* ----------------- Utilities ----------------- */
function getSectionElementByKey(key) {
  // header -> the project info block (first .mb-4 inside reportContent)
  if (!key || key === 'all') return document.body;
  if (key === 'header') {
    // prefer the project info block inside #reportContent
    const headerBlock = document.querySelector('#reportContent .mb-4');
    return headerBlock || document.body;
  }
  // materials, labour, equipment are rendered with data-section="{name}"
  const el = document.querySelector('[data-section="' + key + '"]');
  return el || document.body;
}

function loadJSON(key, fallback = {}) {
  try {
    const s = localStorage.getItem(key);
    return s ? JSON.parse(s) : fallback;
  } catch (e) {
    return fallback;
  }
}
function saveJSON(key, obj) {
  try { localStorage.setItem(key, JSON.stringify(obj)); } catch(e) {}
}

/* ----------------- Color Palette ----------------- */
const paletteToggle = document.getElementById('palette-toggle');
const palettePanel = document.getElementById('palette-panel');
const swatches = palettePanel.querySelectorAll('.color-swatch');
const customColor = document.getElementById('customColor');
const applyTo = document.getElementById('applyTo');
const paletteTarget = document.getElementById('paletteTarget');
const resetPalette = document.getElementById('resetPalette');

paletteToggle.addEventListener('click', () => {
  palettePanel.style.display = palettePanel.style.display === 'block' ? 'none' : 'block';
});

// Apply color when swatch clicked or color input changed
swatches.forEach(s => s.addEventListener('click', () => applyColor(s.dataset.color)));
customColor.addEventListener('input', () => applyColor(customColor.value));

// Apply color function â€” will only apply if user chose a target (or chosen 'all')
function applyColor(color) {
  const targetKey = paletteTarget.value;
  if (!targetKey) {
    // no selection: do nothing â€” user must pick a target before applying
    alert('Please choose a "Target Section" first.');
    return;
  }
  const targetEl = getSectionElementByKey(targetKey);
  if (applyTo.value === 'background') {
    targetEl.style.backgroundColor = color;
  } else {
    targetEl.style.color = color;
  }

  // persist per-section
  const saved = loadJSON('palette_colors', {});
  saved[targetKey] = { type: applyTo.value, color: color };
  saveJSON('palette_colors', saved);
}

// Reset palette: if a section is selected, reset only that; otherwise reset all
resetPalette.addEventListener('click', () => {
  const targetKey = paletteTarget.value;
  if (!targetKey) {
    // clear all
    const keys = ['all','header','materials','labour','equipment'];
    keys.forEach(k => {
      const el = getSectionElementByKey(k);
      if (el) {
        el.style.backgroundColor = '';
        el.style.color = '';
      }
    });
    localStorage.removeItem('palette_colors');
    alert('All palette customizations cleared.');
  } else {
    // clear only chosen
    const el = getSectionElementByKey(targetKey);
    if (el) { el.style.backgroundColor = ''; el.style.color = ''; }
    const saved = loadJSON('palette_colors', {});
    delete saved[targetKey];
    saveJSON('palette_colors', saved);
    alert('Cleared customization for "' + targetKey + '".');
  }
});

/* Load saved colors on startup */
(function loadSavedPaletteColors(){
  const saved = loadJSON('palette_colors', {});
  for (const [section, cfg] of Object.entries(saved)) {
    const { type, color } = cfg || {};
    const el = getSectionElementByKey(section);
    if (!el) continue;
    if (type === 'background') el.style.backgroundColor = color;
    else el.style.color = color;
  }

  // restore palette panel position if present (keeps your existing palettePosition behavior)
  try {
    const savedPos = JSON.parse(localStorage.getItem("palettePosition"));
    if (savedPos && savedPos.left && savedPos.top) {
      palettePanel.style.left = savedPos.left;
      palettePanel.style.top = savedPos.top;
      palettePanel.style.bottom = "auto";
      palettePanel.style.right = "auto";
    }
  } catch(e){}
})();

/* palette draggable (preserve original behavior) */
let isDragging = false, offsetX = 0, offsetY = 0;
palettePanel.addEventListener("mousedown", (e) => {
  if (["BUTTON","SELECT","INPUT"].includes(e.target.tagName)) return;
  isDragging = true;
  offsetX = e.clientX - palettePanel.offsetLeft;
  offsetY = e.clientY - palettePanel.offsetTop;
  palettePanel.style.cursor = "move";
});
document.addEventListener("mousemove", (e) => {
  if (isDragging) {
    palettePanel.style.left = e.clientX - offsetX + "px";
    palettePanel.style.top = e.clientY - offsetY + "px";
    palettePanel.style.bottom = "auto";
    palettePanel.style.right = "auto";
  }
});
document.addEventListener("mouseup", () => {
  if (isDragging) {
    isDragging = false;
    palettePanel.style.cursor = "default";
    localStorage.setItem("palettePosition", JSON.stringify({
      left: palettePanel.style.left, top: palettePanel.style.top
    }));
  }
});

/* ----------------- Font Palette ----------------- */
const fontToggle = document.getElementById('font-toggle');
const fontPanel = document.getElementById('font-panel');
const fontSelector = document.getElementById('fontSelector');
const fontTarget = document.getElementById('fontTarget');
const resetFontBtn = document.getElementById('resetFontBtn');

fontToggle.addEventListener('click', () => {
  fontPanel.style.display = fontPanel.style.display === 'block' ? 'none' : 'block';
});

// Font change handler â€” only applies when user has chosen a target
fontSelector.addEventListener('change', () => {
  const targetKey = fontTarget.value;
  if (!targetKey) {
    alert('Please choose a "Target Section" for fonts first.');
    return;
  }
  const el = getSectionElementByKey(targetKey);
  if (!el) return;
  el.style.fontFamily = fontSelector.value || '';
  // persist per-section
  const saved = loadJSON('palette_fonts', {});
  saved[targetKey] = fontSelector.value || '';
  saveJSON('palette_fonts', saved);
});

// Reset font per-target or all
resetFontBtn.addEventListener('click', () => {
  const targetKey = fontTarget.value;
  if (!targetKey) {
    // clear all
    const keys = ['all','header','materials','labour','equipment'];
    keys.forEach(k => {
      const el = getSectionElementByKey(k);
      if (el) el.style.fontFamily = '';
    });
    localStorage.removeItem('palette_fonts');
    alert('All font customizations cleared.');
  } else {
    const el = getSectionElementByKey(targetKey);
    if (el) el.style.fontFamily = '';
    const saved = loadJSON('palette_fonts', {});
    delete saved[targetKey];
    saveJSON('palette_fonts', saved);
    alert('Cleared font customization for "' + targetKey + '".');
  }
});

/* Load saved fonts on startup */
(function loadSavedFonts(){
  const savedFonts = loadJSON('palette_fonts', {});
  for (const [section, font] of Object.entries(savedFonts)) {
    const el = getSectionElementByKey(section);
    if (el) el.style.fontFamily = font || '';
  }

  // restore font panel position if present
  try {
    const fp = JSON.parse(localStorage.getItem("fontPanelPosition"));
    if (fp && fp.left && fp.top) {
      fontPanel.style.left = fp.left;
      fontPanel.style.top = fp.top;
      fontPanel.style.bottom = "auto";
      fontPanel.style.right = "auto";
    }
  } catch(e){}
})();

/* draggable font panel (preserve behavior) */
(function dragElement(elmnt){
  let pos1=0,pos2=0,pos3=0,pos4=0;
  elmnt.onmousedown = dragMouseDown;
  function dragMouseDown(e){
    if (["BUTTON","SELECT","INPUT"].includes(e.target.tagName)) return;
    e.preventDefault();
    pos3 = e.clientX; pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }
  function elementDrag(e){
    e.preventDefault();
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }
  function closeDragElement(){
    document.onmouseup = null;
    document.onmousemove = null;
    // store position for font panel as well (optional)
    localStorage.setItem("fontPanelPosition", JSON.stringify({
      left: fontPanel.style.left, top: fontPanel.style.top
    }));
  }
})(fontPanel);
</script>
</body>
</html>
