<?php
session_start();
// Database connection
$con = new mysqli("localhost", "transpa2_uplinepj", "Police2345@1", "transpa2_jetinstantTQ");
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}

if (isset($_POST['search'])) {
    $PID = $_POST['pid'];
}

// Fetch project info
$project_info_query = "SELECT * FROM upline_app_project_info WHERE project_ref = '$PID'";
$project_result = $con->query($project_info_query);
$project_info = $project_result->fetch_assoc();

// Fetch data
$materials = $con->query("SELECT * FROM foundation_materials WHERE PID = '$PID'");
$labours = $con->query("SELECT * FROM foundation_labourer WHERE PID = '$PID'");
$equipments = $con->query("SELECT * FROM foundation_equipment WHERE PID = '$PID'");
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Foundation Report</title>
  <script src="https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.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/html2canvas/1.4.1/html2canvas.min.js"></script>
	<style>
@media print {
  .no-print {
    display: none;
  }
}
</style>

  <script>
    function exportToExcel() {
      const tables = document.querySelectorAll('.exportable-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, table.getAttribute('data-sheet-name') || `Sheet${index+1}`);
      });

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

    async function exportToPDF() {
      const exportButtons = document.getElementById("exportButtons");
      exportButtons.style.display = "none"; // Hide export buttons

      const element = document.getElementById("reportContent");
      const canvas = await html2canvas(element);
      const imgData = canvas.toDataURL("image/png");
      const { jsPDF } = window.jspdf;
      const pdf = new jsPDF("p", "pt", "a4");
      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = (canvas.height * pdfWidth) / canvas.width;

      pdf.addImage(imgData, "PNG", 0, 0, pdfWidth, pdfHeight);
      pdf.save("foundation_report.pdf");

      exportButtons.style.display = "block"; // Show export buttons again
    }
  </script>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 p-6">
  <div class="max-w-6xl mx-auto bg-white shadow-md rounded-xl p-6" 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 text-center">Foundation Report</h2>
    <div class="mb-4">
      <p><strong>Project Name:</strong> <?= $project_info['project_name'] ?></p>
      <p><strong>Project Type:</strong> <?= $project_info['project_type'] ?></p>
      <p><strong>Developer:</strong> <?= $project_info['project_developer'] ?></p>
      <p><strong>Location:</strong> <?= $project_info['project_address'] ?></p>
    </div>

    <?php
    function renderTable($result, $title, $descField, $qtyField, $extraField, $priceField, $totalField) {
        $subtotal = 0;
        $itemNo = 1;
        echo "<h3 class='text-xl font-bold mb-2 mt-6'>$title</h3>";
        echo "<table class='table-auto w-full border border-gray-300 mb-6 text-sm exportable-table' data-sheet-name='$title'>
              <thead>
              <tr class='bg-gray-200 text-left'>
                  <th class='border px-2 py-1'>SN</th>
                  <th class='border px-2 py-1'>Description</th>
                  <th class='border px-2 py-1'>Quantity</th>
                  <th class='border px-2 py-1'>Extra</th>
                  <th class='border px-2 py-1'>Price</th>
                  <th class='border px-2 py-1'>Total</th>
              </tr>
              </thead>
              <tbody>";
        while ($row = $result->fetch_assoc()) {
            $subtotal += $row[$totalField];
            echo "<tr>
                    <td class='border px-2 py-1'>". $itemNo++ ."</td>
                    <td class='border px-2 py-1'>{$row[$descField]}</td>
                    <td class='border px-2 py-1'>{$row[$qtyField]}</td>
                    <td class='border px-2 py-1'>{$row[$extraField]}</td>
                    <td class='border px-2 py-1'>{$row[$priceField]}</td>
                    <td class='border px-2 py-1'>".number_format($row[$totalField], 2)."</td>
                  </tr>";
        }
        $contingency = 0.05 * $subtotal;
        $total = $subtotal + $contingency;
        echo "<tr><td colspan='5' class='border px-2 py-1 text-right font-semibold'>Subtotal</td><td class='border px-2 py-1'>".number_format($subtotal,2)."</td></tr>";
        echo "<tr><td colspan='5' class='border px-2 py-1 text-right font-semibold'>Contingency (5%)</td><td class='border px-2 py-1'>".number_format($contingency,2)."</td></tr>";
        echo "<tr><td colspan='5' class='border px-2 py-1 text-right font-bold'>Total</td><td class='border px-2 py-1 font-bold'>".number_format($total,2)."</td></tr>";
        echo "</tbody></table>";
        return $total;
    }

    $total1 = renderTable($materials, 'MATERIALS', 'MaterialDescription', 'COEQuantity', 'Extra', 'Price', 'CETotalAmount');
    $total2 = renderTable($labours, 'LABOUR', 'LabourerDescription', 'COEQuantity', 'Extra', 'Price', 'COETotal');
    $total3 = renderTable($equipments, 'EQUIPMENT', 'EquipmentDescription', 'Quantity', 'Extra', 'Price', 'Total');
    $grandTotal = $total1 + $total2 + $total3;
    ?>

    <div class="mt-8">
      <h3 class="text-2xl font-bold text-center">FOUNDATION TOTAL: NGN <?= number_format($grandTotal, 2) ?></h3>
    </div>

    <div class="mt-6 text-center" id="exportButtons">
      <button onclick="exportToExcel()" class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700 mr-2">Export to Excel</button>
      <button onclick="exportToPDF()" class="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700">Export to PDF</button>
    </div>

  </div>
</body>
</html>
