<?php
// save_inspection_test_results.php

// Load configuration using the tenant parameter
require_once('../../../' . $_REQUEST['tenant'] . '/config.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Ensure board_id is provided
        $board_id = $_POST['board_id'] ?? null;
        $clientnumber = $_POST['clientnumber'] ?? '';
        if (!$board_id) {
            echo json_encode(['success' => false, 'message' => 'Board ID is missing.']);
            exit;
        }

        // Check for posted circuit results
        if (!isset($_POST['circuit_results']) || empty($_POST['circuit_results'])) {
            echo json_encode(['success' => false, 'message' => 'No circuit data provided.']);
            exit;
        }

        // Build the circuit_results array from the POST data
        $circuit_results = [];
        foreach ($_POST['circuit_results'] as $circuit_id => $data) {
            $circuit_results[$circuit_id] = [
                'pe'              => $data['pe'] ?? '-',
                'pp'              => $data['pp'] ?? '-',
                'r1'              => $data['r1'] ?? '-',
                'r2'              => $data['r2'] ?? '-',
                'rn'              => $data['rn'] ?? '-',
                'zs'              => $data['zs'] ?? '-',
                'r1_r2'           => $data['r1_r2'] ?? '-',
                'polarity'        => (isset($data['polarity']) && $data['polarity'] == 1) ? 1 : 0,
                'observations'    => $data['observations'] ?? '-',
                'earth_leakage'   => $data['earth_leakage'] ?? '-',
                'r2_continuity'   => $data['r2_continuity'] ?? '-',
                '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,
            ];
        }

        // Encode the array to JSON
        $circuit_results_json = json_encode($circuit_results);
        if ($circuit_results_json === false) {
            echo json_encode(['success' => false, 'message' => 'Failed to encode circuit results.']);
            exit;
        }

        // Get the master_report_id and is_update from POST data
        $master_report_id = $_POST['master_report_id'] ?? null;
        $is_update = $_POST['is_update'] == "true"; // Check if it's an update

        if (!$master_report_id) {
            echo json_encode(['success' => false, 'message' => 'master_report_id is missing.']);
            exit;
        }

        // Stage 4: Set stage status as 'ongoing'
        $stage_status = json_encode([4 => 'ongoing'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        // If updating, we need to fetch the existing stage_status and add/update the stage 4 entry
        if ($is_update) {
            // Fetch the current stage_status for the master_report_id and board_id
            $query = "SELECT stage_status FROM elec_report WHERE master_report_id = ? AND board_id = ?";
            $stmt = $con->prepare($query);
            $stmt->bind_param("si", $master_report_id, $board_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_assoc();
            $stmt->close();

            $current_stage_status = !empty($row['stage_status']) ? json_decode($row['stage_status'], true) : [];

            // If stage_status is empty, initialize it
            if (empty($current_stage_status)) {
                $current_stage_status = [];
            }

            // Update the stage 4 status without overwriting existing stages
            $current_stage_status[4] = 'ongoing'; // Set stage 4 to ongoing

            // Convert updated stage status to JSON
            $updated_stage_status = json_encode($current_stage_status, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

            // Now update the row
            $update_query = "UPDATE elec_report 
                                SET circuit_results = ?, stage_status = ? 
                                WHERE master_report_id = ? AND board_id = ?";
            $stmt = $con->prepare($update_query);
            if (!$stmt) {
                echo json_encode(['success' => false, 'message' => 'Database error during update.']);
                exit;
            }

            // Now bind the updated variables
            $stmt->bind_param("ssss", $circuit_results_json, $updated_stage_status, $master_report_id, $board_id);
        } else {
            // Insert a new report for the specific board and master_report_id
            $insert_query = "INSERT INTO elec_report (board_id, clientnumber, circuit_results, stage_status, status, master_report_id) 
                             VALUES (?, ?, ?, ?, 'active', ?)";
            $stmt = $con->prepare($insert_query);
            if (!$stmt) {
                echo json_encode(['success' => false, 'message' => 'Database error during insert.']);
                exit;
            }
            $stmt->bind_param("iisss", $board_id, $clientnumber, $circuit_results_json, $stage_status, $master_report_id);
        }

        // Execute the query
        if ($stmt->execute()) {
            $new_report_id = isset($report_id) ? $report_id : $stmt->insert_id;
            echo json_encode([
                'success'   => true,
                'message'   => 'Data saved successfully.',
                'report_id' => $new_report_id,
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to save inspection results.']);
        }

        $stmt->close();
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'An unexpected error occurred.']);
    }
}
exit;
?>