<?php
// delete_observation.php
require_once('../../../' . $_POST['tenant'] . '/config.php');

header('Content-Type: application/json');

// 1) pull params
$mrid  = $_POST['master_report_id'] ?? null;
$board = $_POST['board_id']        ?? null;
$grp   = $_POST['group']           ?? null;
$obs   = isset($_POST['obs'])      ? intval($_POST['obs']) : null;

if (!$mrid || !$board || $grp === null || $obs === null) {
  echo json_encode(['success'=>false,'message'=>'Missing parameters.']);
  exit;
}

// 2) delete images
$dir = "../../../" . $_POST['tenant'] . "/images/report_images/";
for ($i=1; $i<=6; $i++) {
  $fn = "{$mrid}_{$board}_{$grp}_{$obs}_{$i}.jpg";
  $path = $dir . $fn;
  if (file_exists($path)) unlink($path);
}

// 3) load current observation_data
$sql = "SELECT observation_data FROM elec_report 
        WHERE master_report_id=? AND board_id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param('ii',$mrid,$board);
$stmt->execute();
$od = $stmt->get_result()->fetch_assoc()['observation_data'] ?? '[]';
$stmt->close();

$data = json_decode($od,true);

// 4) remove the single observation
if (isset($data[$grp]) && is_array($data[$grp])) {
  array_splice($data[$grp], $obs, 1);
  // if no more entries, you can choose to unset the group:
  if (count($data[$grp])===0) {
    unset($data[$grp]);
  }
}

// 5) write back
$newJson = json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
$sql = "UPDATE elec_report 
        SET observation_data = ? 
        WHERE master_report_id=? AND board_id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param('sii',$newJson,$mrid,$board);
$ok = $stmt->execute();
$stmt->close();

if ($ok) {
  echo json_encode(['success'=>true]);
} else {
  echo json_encode(['success'=>false,'message'=>'DB update failed']);
}