<?php
header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input'), true);
$master_report_id = $input['master_report_id'] ?? null;
$tenant           = $input['tenant']          ?? null;

if (!$master_report_id) {
  echo json_encode(['success'=>false,'message'=>'Master report ID is missing.']);
  exit;
}
require_once("../../../{$tenant}/config.php");

$stmt = $con->prepare("
  SELECT
    installation_details,
    general_condition,
    summary_condition,
    overall_recommendation,
    surveyor_id
  FROM elec_report
  WHERE master_report_id = ?
  LIMIT 1
") or die(json_encode(['success'=>false,'message'=>$con->error]));

$stmt->bind_param("s", $master_report_id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$row) {
  echo json_encode(['success'=>false,'message'=>'Report not found.']);
  exit;
}

// Decode the JSON blob for the things you already stored there
$details = json_decode($row['installation_details'], true) ?: [];

// Pull in the four separately-stored columns
$details['generalCondition']      = $row['general_condition'];
$details['installationSummary']   = $row['summary_condition'];
$details['recommendations']       = $row['overall_recommendation'];
$details['surveyor']              = $row['surveyor_id'];

// And look up the surveyor’s name
$stmt = $con->prepare("SELECT forename, surname FROM surveyor WHERE id = ?") 
       or die(json_encode(['success'=>false,'message'=>$con->error]));
$stmt->bind_param("i", $row['surveyor_id']);
$stmt->execute();
$sv = $stmt->get_result()->fetch_assoc();
$stmt->close();

$details['surveyorName'] = trim(($sv['forename'] ?? '') . ' ' . ($sv['surname'] ?? ''));

// Finally, return it all in one go:
echo json_encode(['success'=>true,'data'=>$details]);
exit;