<?php
// finalise_report.php
// Generates the Electrical Installation Condition Report PDF for a given master_report_id

require_once __DIR__ . '/vendor/autoload.php'; // mPDF autoloader
require_once __DIR__ . '/enrepco_dev.php';     // DB connection settings & sample data arrays

use Mpdf\Mpdf;

// 1. Get master_report_id from request
if (!isset($_GET['master_report_id'])) {
    http_response_code(400);
    echo 'Missing master_report_id';
    exit;
}
$masterId = (int) $_GET['master_report_id'];

// 2. Database connection (mysqli)
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($db->connect_error) {
    die('Connection error: ' . $db->connect_error);
}

// 3. Fetch all rows for this master_report_id
$sql = "SELECT * FROM inspection_reports WHERE master_report_id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param('i', $masterId);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
    die('No report found for master_report_id ' . $masterId);
}

// 4. Process common data (first row) and board-specific results
$rows = $result->fetch_all(MYSQLI_ASSOC);
$common = $rows[0];
$boardResults = array_map(function($r) { return json_decode($r['circuit_results'], true); }, $rows);

// 5. Start HTML output buffering
ob_start();
include __DIR__ . '/templates/blank_report_template.php';
$html = ob_get_clean();

// 6. Instantiate mPDF and write HTML
$mpdf = new Mpdf([
    'mode' => 'utf-8',
    'format' => 'A4',
    'default_font_size' => 10,
]);

// If template has both portrait and landscape sections, you can switch orientation:
// $mpdf->AddPage('L'); // landscape
// $mpdf->WriteHTML($landscapeHtml);
// $mpdf->AddPage('P'); // portrait
// $mpdf->WriteHTML($portraitHtml);

$mpdf->WriteHTML($html);

// 7. Output PDF to browser
$filename = 'EICR_Report_' . $masterId . '.pdf';
$mpdf->Output($filename, \Mpdf\Output\Destination::INLINE);
exit;