<?php
// save_inspection_test_results.php

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

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

// 2) Required IDs
$master_report_id = $_POST['master_report_id'] ?? null;
$board_id         = $_POST['board_id']        ?? null;
$clientnumber     = $_POST['clientnumber']    ?? null;

// New inputs
$surveyor_id      = $_POST['surveyor_id']     ?? null;
$inspection_date  = $_POST['inspection_date'] ?? null;

if (!$master_report_id || !$board_id) {
    echo json_encode(['success'=>false,'message'=>'Master report or board ID missing.']);
    exit;
}

// 3) Build circuit_results exactly as before
if (empty($_POST['circuit_results'])) {
    echo json_encode(['success'=>false,'message'=>'No circuit data provided.']);
    exit;
}

$circuit_results = [];
foreach ($_POST['circuit_results'] as $cno => $data) {
    $circuit_results[$cno] = [
        'pe'              => $data['pe']              ?? '-',
        'pp'              => $data['pp']              ?? '-',
        'r1'              => $data['r1']              ?? '-',
        'rn'              => $data['rn']              ?? '-',
        'r2'              => $data['r2']              ?? '-',
        'r1_r2'           => $data['r1_r2']           ?? '-',
        'r2_continuity'   => $data['r2_continuity']   ?? '-',
        'polarity'        => (isset($data['polarity']) && $data['polarity']==1) ? 1 : 0,
        'zs'              => $data['zs']              ?? '-',
        'earth_leakage'   => $data['earth_leakage']   ?? '-',
        'rcd_trip_time'   => $data['rcd_trip_time']   ?? '-',
        'rcd_functional'  => (isset($data['rcd_functional']) && $data['rcd_functional']==1) ? 1 : 0,
        'afdd_functional' => (isset($data['afdd_functional']) && $data['afdd_functional']==1) ? 1 : 0,
    ];
}
$circuit_results_json = json_encode($circuit_results, JSON_UNESCAPED_UNICODE);

// 4) Process Observations (drop “C1 + empty + fi=0” rows)
$postedObs = $_POST['observations'] ?? [];
$toSaveObs = [];

foreach ($postedObs as $cno => $rows) {
    $filtered = [];
    foreach ($rows as $r) {
        $isDefaultFault = ($r['fault_code'] === 'C1');
        $isDefaultText  = (trim($r['text']) === '');
        $isDefaultFI    = empty($r['fi']);
        if (!($isDefaultFault && $isDefaultText && $isDefaultFI)) {
            $r['fi'] = !empty($r['fi']) ? 1 : 0;
            $filtered[] = $r;
        }
    }
    if (count($filtered) > 0) {
        $toSaveObs[$cno] = array_values($filtered);
    }
}

$obsJson = json_encode($toSaveObs, JSON_UNESCAPED_UNICODE);

// 5) Build or update stage_status JSON
$is_update = (($_POST['is_update'] ?? '') === 'true');
$existing   = [];
if ($is_update) {
    $q = "SELECT stage_status 
            FROM elec_report 
           WHERE master_report_id = ? 
             AND board_id = ?";
    $st = $con->prepare($q);
    $st->bind_param("si", $master_report_id, $board_id);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    $st->close();
    $existing = json_decode($row['stage_status'] ?? '[]', true) ?: [];
}

// Overwrite only stage “5” to “ongoing”
$existing[5] = 'ongoing';
$stage_status = json_encode($existing, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

// 6) INSERT or UPDATE elec_report
if ($is_update) {
    $sql = "
      UPDATE elec_report
         SET circuit_results   = ?,
             stage_status      = ?,
             observation_data  = ?,
             surveyor_id       = ?,
             inspection_date   = ?
       WHERE master_report_id = ?
         AND board_id         = ?
    ";
    $stmt = $con->prepare($sql);
    $stmt->bind_param(
      'ssssssi',
      $circuit_results_json,
      $stage_status,
      $obsJson,
      $surveyor_id,
      $inspection_date,
      $master_report_id,
      $board_id
    );
} else {
    $sql = "
      INSERT INTO elec_report
        (board_id, clientnumber, circuit_results, stage_status, observation_data, surveyor_id, inspection_date, status, master_report_id)
      VALUES (?, ?, ?, ?, ?, ?, ?, 'active', ?)
    ";
    $stmt = $con->prepare($sql);
    $stmt->bind_param(
      'isssssss',
      $board_id,
      $clientnumber,
      $circuit_results_json,
      $stage_status,
      $obsJson,
      $surveyor_id,
      $inspection_date,
      $master_report_id
    );
}

if ($stmt->execute()) {
    echo json_encode([
        'success'           => true,
        'message'           => 'Data saved successfully.',
        'observation_data'  => $toSaveObs
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to save inspection results.',
        'error'   => $stmt->error
    ]);
}

$stmt->close();
exit;
?>