<?php
// save_condition_report.php

// Enable error reporting (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Load configuration using the tenant parameter
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
} elseif (file_exists('/config.php')) {
    require_once('/config.php');
} else {
    die("Configuration file not found.");
}

$return = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Collect condition schedule data from POST
        $condition_schedule = [];
        if (isset($_POST['outcome'])) {
            foreach ($_POST['outcome'] as $item_no => $outcome) {
                $condition_schedule[$item_no] = [
                    'outcome' => $outcome,
                    'further_investigation' => !empty($_POST['further_investigation'][$item_no]) ? 1 : 0
                ];
            }
        }

        // Collect test instruments data from POST
        $test_instruments = [];
        if (isset($_POST['instrument'])) {
            foreach ($_POST['instrument'] as $index => $instrument) {
                if (!empty($instrument) || !empty($_POST['maker'][$index]) || !empty($_POST['serial_no'][$index]) || !empty($_POST['last_calibration'][$index]) || !empty($_POST['next_calibration'][$index])) {
                    $test_instruments[] = [
                        'instrument' => trim($instrument),
                        'maker' => trim($_POST['maker'][$index] ?? ''),
                        'serial_no' => trim($_POST['serial_no'][$index] ?? ''),
                        'last_calibration' => trim($_POST['last_calibration'][$index] ?? ''),
                        'next_calibration' => trim($_POST['next_calibration'][$index] ?? '')
                    ];
                }
            }
        }

        // Encode the collected data to JSON
        $condition_schedule_json = json_encode($condition_schedule, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $test_instruments_json = json_encode($test_instruments, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        // Get common parameters
        $clientnumber = $_POST['clientnumber'] ?? '';
        $locnumber = $_POST['locnumber'] ?? '';
        $master_report_id = $_POST['master_report_id'] ?? null;

        // Check if master_report_id exists when updating
        if ($_POST['is_update'] == "true" && !$master_report_id) {
            echo json_encode(['success' => false, 'message' => 'Master report ID is missing.']);
            exit;
        }

        // If updating an existing report
        if ($_POST['is_update'] == "true") {
            // Get the current stage status JSON
            $get_query = "SELECT stage_status FROM elec_report WHERE master_report_id = ? LIMIT 1";
            $stmt = $con->prepare($get_query);
            if (!$stmt) {
                echo json_encode(['success' => false, 'message' => 'Database error during retrieval.']);
                exit;
            }
            $stmt->bind_param("s", $master_report_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_assoc();
            $stmt->close();

            // Decode the current stage_status if exists
            $stage_status = json_decode($row['stage_status'], true) ?? [];

            // Add or update the current stage status (Stage 3 in this case) to 'ongoing'
            $current_stage = 3;
            $stage_status[$current_stage] = 'ongoing'; // Update stage 3 status

            // Convert the updated stage_status back to JSON
            $updated_stage_status = json_encode($stage_status, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

            // Update the condition schedule and test instruments for the specific master_report_id
            $update_query = "UPDATE elec_report SET condition_schedule = ?, test_instruments = ?, stage_status = ? WHERE master_report_id = ?";
            $stmt = $con->prepare($update_query);
            if (!$stmt) {
                echo json_encode(['success' => false, 'message' => 'Database error during update.']);
                exit;
            }
            $stmt->bind_param("ssss", $condition_schedule_json, $test_instruments_json, $updated_stage_status, $master_report_id);

            // Execute the prepared statement
            if (!$stmt->execute()) {
                echo json_encode(['success' => false, 'message' => 'Failed to update condition report.']);
                exit;
            }

            echo json_encode([
                'success' => true,
                'message' => 'Condition report updated successfully.',
                'master_report_id' => $master_report_id
            ]);
            $stmt->close();
        }
        // If creating a new report
        else {
            // Expect a board_list JSON string to be provided
            $board_list_json = $_POST['board_list'] ?? '';
            if (empty($board_list_json)) {
                echo json_encode(['success' => false, 'message' => 'Board list is missing for new report creation.']);
                exit;
            }
            $board_list = json_decode($board_list_json, true);
            if (!is_array($board_list) || empty($board_list)) {
                echo json_encode(['success' => false, 'message' => 'Invalid board list.']);
                exit;
            }

            // Generate a new master_report_id to group all boards together
            $master_report_id = uniqid('mr_', true);

            // Create the stage_status for stage 3 only
            $stage_status = json_encode([
                "3" => "ongoing"  // For stage 3
            ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

            // Insert one row for each board in the board list
            $errors = [];
            foreach ($board_list as $board_item) {
                $b_id = (is_array($board_item) && isset($board_item['board_id'])) ? intval($board_item['board_id']) : intval($board_item);
                $insert_query = "INSERT INTO elec_report (board_id, clientnumber, locnumber, condition_schedule, test_instruments, status, master_report_id, stage_status) 
                                 VALUES (?, ?, ?, ?, ?, 'active', ?, ?)";
                $stmt = $con->prepare($insert_query);
                if (!$stmt) {
                    $errors[] = "Board $b_id: DB error during insert preparation: " . $con->error;
                    continue;
                }
                $stmt->bind_param("iiissss", $b_id, $clientnumber, $locnumber, $condition_schedule_json, $test_instruments_json, $master_report_id, $stage_status);
                if (!$stmt->execute()) {
                    $errors[] = "Board $b_id: " . $stmt->error;
                }
                $stmt->close();
            }

            if (!empty($errors)) {
                echo json_encode(['success' => false, 'message' => "Errors during insert: " . implode("; ", $errors)]);
                exit;
            }

            echo json_encode([
                'success' => true,
                'message' => 'Condition report saved and new report created successfully.',
                'master_report_id' => $master_report_id
            ]);
        }

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