<?php
// save_observations.php

// 1) Load config
if (file_exists('../../../' . $_POST['tenant'] . '/config.php')) {
    require_once('../../../' . $_POST['tenant'] . '/config.php');
} elseif (file_exists('/config.php')) {
    require_once('/config.php');
} else {
    die(json_encode(['success' => false, 'message' => 'Configuration file not found.']));
}

// 2) Must be POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
    exit;
}

// 3) Validate inputs
$master_report_id = $_POST['master_report_id'] ?? '';
$board_list_json  = $_POST['board_list'] ?? '';
$observations     = $_POST['observations'] ?? [];

if (!$master_report_id || !$board_list_json) {
    echo json_encode(['success' => false, 'message' => 'Missing report or board list.']);
    exit;
}

$board_list = json_decode($board_list_json, true);
if (!is_array($board_list)) {
    echo json_encode(['success' => false, 'message' => 'Invalid board list JSON.']);
    exit;
}

// 3a) Filter out any observations that are “completely blank”
//     We'll consider an observation blank if location, fault_code and notes are all empty strings.
//     (If you also want to check for uploaded images, you'd need to examine $_FILES; in this snippet
//     we're only checking those three fields.)
$filtered = [];
foreach ($observations as $idx => $obs) {
    $loc      = trim($obs['location']   ?? '');
    $fault    = trim($obs['fault_code'] ?? '');
    $notes    = trim($obs['notes']      ?? '');
    // If any of these three fields is non-empty, keep this observation
    if ($loc !== '' || $fault !== '' || $notes !== '') {
        $filtered[] = $obs;
    }
}
// If all entries were blank, refuse to save
if (count($filtered) === 0) {
    echo json_encode([
        'success' => false,
        'message' => 'You must provide at least one non‐blank observation before saving.'
    ]);
    exit;
}

// 4) Encode filtered observations into JSON
$obs_json = json_encode($filtered);

// 5) Update every board’s row sharing this master_report_id
$errors = [];
foreach ($board_list as $b) {
    $bid = intval($b['board_id']);

    // 5a) Fetch existing `stage_status` JSON for this board
    $stmt = $con->prepare("
        SELECT stage_status
          FROM elec_report
         WHERE master_report_id = ?
           AND board_id = ?
         LIMIT 1
    ");
    if (!$stmt) {
        $errors[] = "Prepare failed (SELECT): " . $con->error;
        continue;
    }
    $stmt->bind_param("si", $master_report_id, $bid);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    // 5b) Decode existing JSON (or start fresh if none)
    $current_status = [];
    if (!empty($row['stage_status'])) {
        $decoded = json_decode($row['stage_status'], true);
        if (is_array($decoded)) {
            $current_status = $decoded;
        }
    }

    // 5c) Set stage "4" => "ongoing" (observations is considered stage 4)
    $current_status["4"] = "ongoing";

    // 5d) Re‐encode as JSON
    $new_status_json = json_encode($current_status);

    // 5e) Update both `observations` and `stage_status`
    $upd = $con->prepare("
        UPDATE elec_report
           SET observations  = ?,
               stage_status  = ?
         WHERE master_report_id = ?
           AND board_id = ?
    ");
    if (!$upd) {
        $errors[] = "Prepare failed (UPDATE): " . $con->error;
        continue;
    }
    $upd->bind_param("sssi", $obs_json, $new_status_json, $master_report_id, $bid);
    if (!$upd->execute()) {
        $errors[] = "Execute failed (UPDATE for board {$bid}): " . $upd->error;
    }
    $upd->close();
}

if (count($errors) > 0) {
    echo json_encode([
        'success' => false,
        'message' => 'One or more updates failed: ' . implode("; ", $errors)
    ]);
} else {
    echo json_encode([
        'success' => true,
        'message' => 'Observations saved successfully.'
    ]);
}