<?php
// save_installation_details.php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

$return = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $clientnumber = $_POST['clientnumber'] ?? '';
        $locnumber = $_POST['locnumber'] ?? '';
        $new_installation_details = $_POST['installation_details'] ?? [];
        $is_update = isset($_POST['is_update']) ? $_POST['is_update'] : false; // Determine if it's update mode
        $master_report_id = $_POST['master_report_id'] ?? null; // Pass the master_report_id if available
        $new_stage_status = "ongoing"; // Default stage status for Stage 1
        
        // Check if it's update mode or new report
        if ($_POST['is_update']=="true") {
            // Update existing report
            $response = updateExistingReport($master_report_id, $clientnumber, $locnumber, $new_installation_details, $new_stage_status);
        }
        if ($_POST['is_update']=="false") {
            // Create new report
            $response = createNewReport($clientnumber, $locnumber, $new_installation_details, $new_stage_status);
        }

        // Return response
        echo json_encode($response);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'An unexpected error occurred: ' . $e->getMessage()]);
    }
}

// Function to create a new report
function createNewReport($clientnumber, $locnumber, $new_installation_details, $new_stage_status) {
    global $con;
    // Generate a new master_report_id
    $master_report_id = uniqid('mr_', true);
    $installation_details_json = json_encode($new_installation_details, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    
    // Insert new report into the database
    $board_list_json = $_POST['board_list'] ?? '';
    $board_list = json_decode($board_list_json, true);
    
    if (!is_array($board_list) || empty($board_list)) {
        return ['success' => false, 'message' => 'Invalid 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, installation_details, status, master_report_id, stage_status)
                        VALUES (?, ?, ?, ?, 'active', ?, JSON_OBJECT('1', ?))";
        $stmt = $con->prepare($insert_query);
        if (!$stmt) {
            $errors[] = "Board $b_id: DB error during insert preparation: " . $con->error;
            continue;
        }
        $stmt->bind_param("isssss", $b_id, $clientnumber, $locnumber, $installation_details_json, $master_report_id, $new_stage_status);
        if (!$stmt->execute()) {
            $errors[] = "Board $b_id: " . $stmt->error;
        }
        $stmt->close();
    }

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

    // Retrieve one report_id from the newly inserted rows
    $query = "SELECT report_id FROM elec_report WHERE master_report_id = ? LIMIT 1";
    $stmt = $con->prepare($query);
    if (!$stmt) {
        return ['success' => false, 'message' => 'Database error during retrieval.'];
    }
    $stmt->bind_param("s", $master_report_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();

    return [
        'success' => true,
        'message' => 'Installation Details saved and new report created successfully.',
        'master_report_id' => $master_report_id // Return the master_report_id for the new report
    ];
}

// Function to update an existing report
function updateExistingReport($master_report_id, $clientnumber, $locnumber, $new_installation_details, $new_stage_status) {
    global $con;

    // If no master_report_id is provided, return an error
    if (empty($master_report_id)) {
        return ['success' => false, 'message' => 'Master report ID is required for updating.'];
    }

    // Fetch the existing installation details and stage_status from the database for updating
    $existing_details = [];
    $query = "SELECT installation_details, stage_status FROM elec_report WHERE master_report_id = ? AND locnumber = ?";
    $stmt = $con->prepare($query);
    if (!$stmt) {
        return ['success' => false, 'message' => 'Database error during retrieval.'];
    }
    $stmt->bind_param("si", $master_report_id, $locnumber);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();

    // If installation details exist, merge with new details
    if (!empty($row['installation_details'])) {
        $existing_details = json_decode($row['installation_details'], true);
        if (!is_array($existing_details)) {
            $existing_details = [];
        }
    }

    // Merge new details with existing ones
    $merged_details = array_merge($existing_details, $new_installation_details);
    $installation_details_json = json_encode($merged_details, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    // If stage_status is empty, initialize it
    $stage_status = !empty($row['stage_status']) ? json_decode($row['stage_status'], true) : [];

    // Ensure that stages 1-3 are handled properly
    if ($new_stage_status) {
        if ($new_stage_status === "ongoing") {
            $stage_status[1] = "ongoing";
        } elseif ($new_stage_status === "complete") {
            $stage_status[1] = "complete";
        }
    }

    // Update the report in the database
    $update_query = "UPDATE elec_report
                    SET installation_details = ?,
                        stage_status = ?
                    WHERE master_report_id = ? AND locnumber = ?";
    $stmt = $con->prepare($update_query);
    if (!$stmt) {
        return ['success' => false, 'message' => 'Database error during update.'];
    }

    $stage_status_json = json_encode($stage_status, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $stmt->bind_param("ssss", $installation_details_json, $stage_status_json, $master_report_id, $locnumber);

    if ($stmt->execute()) {
        return [
            'success' => true,
            'message' => 'Installation Details updated successfully.',
            'master_report_id' => $master_report_id // Return the master_report_id for the update
        ];
    } else {
        return ['success' => false, 'message' => 'Failed to update installation details.'];
    }
}