<?php
// clear_stage.php

require_once('../../../' . $_REQUEST['tenant'] . '/config.php');

if (!isset($_POST['master_report_id'], $_POST['stage'])) {
    echo json_encode(['success'=>false,'message'=>'Missing required parameters.']);
    exit;
}

$mrid  = $_POST['master_report_id'];
$stage = intval($_POST['stage']);
$board = isset($_POST['board_id']) ? intval($_POST['board_id']) : null;

// decide which column to clear
switch ($stage) {
  case 1: $col = 'installation_details';      break;
  case 2: $col = 'schedule_of_inspection';    break;
  case 3: $col = 'condition_schedule';        break;
  case 4: $col = 'circuit_results';           break;
  default:
    echo json_encode(['success'=>false,'message'=>'Invalid stage.']);
    exit;
}

// start transaction
$con->begin_transaction();

try {
    // 1) Clear the data column
    if ($stage < 4) {
        // clear for every board row of this report
        $sql = "UPDATE elec_report SET `$col` = NULL WHERE master_report_id = ?";
        $stmt= $con->prepare($sql);
        $stmt->bind_param("s", $mrid);
        $stmt->execute();
        $stmt->close();
    } else {
        // stage 4: must have board_id
        if (!$board) {
            throw new Exception("Board ID missing for stage 4.");
        }
        // clear only the one row’s circuit_results and observation_data
        $sql = "UPDATE elec_report
                   SET circuit_results  = NULL,
                       observation_data = NULL
                 WHERE master_report_id = ?
                   AND board_id         = ?";
        $stmt= $con->prepare($sql);
        $stmt->bind_param("si", $mrid, $board);
        $stmt->execute();
        $stmt->close();

        // also delete ALL its obs images
        $pattern = TENANT_DEFER."/images/report_images/{$mrid}_{$board}_*.jpg";
        foreach (glob($pattern) as $file) {
            @unlink($file);
        }
    }

    // 2) Fix up each affected row’s stage_status JSON
    if ($stage < 4) {
        // load & update every row for this report
        $sql = "SELECT board_id, stage_status FROM elec_report WHERE master_report_id = ?";
        $stmt= $con->prepare($sql);
        $stmt->bind_param("s", $mrid);
        $stmt->execute();
        $res = $stmt->get_result();
        $stmt->close();

        while ($row = $res->fetch_assoc()) {
            $sJson = json_decode($row['stage_status'], true) ?: [];
            unset($sJson[$stage]);
            $new = json_encode($sJson, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

            $u = $con->prepare(
                "UPDATE elec_report
                    SET stage_status = ?
                  WHERE master_report_id = ?
                    AND board_id = ?"
            );
            $u->bind_param("ssi", $new, $mrid, $row['board_id']);
            $u->execute();
            $u->close();
        }
    } else {
        // only that one board row
        $sql = "SELECT stage_status FROM elec_report WHERE master_report_id = ? AND board_id = ?";
        $stmt= $con->prepare($sql);
        $stmt->bind_param("si", $mrid, $board);
        $stmt->execute();
        $r = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        $sJson = json_decode($r['stage_status'], true) ?: [];
        unset($sJson[$stage]);
        $new = json_encode($sJson, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);

        $u = $con->prepare(
            "UPDATE elec_report
                SET stage_status = ?
              WHERE master_report_id = ?
                AND board_id = ?"
        );
        $u->bind_param("ssi", $new, $mrid, $board);
        $u->execute();
        $u->close();
    }

    $con->commit();
    echo json_encode(['success'=>true,'message'=>'Stage cleared successfully.']);
}
catch (Exception $e) {
    $con->rollback();
    echo json_encode(['success'=>false,'message'=>'Error clearing stage: '.$e->getMessage()]);
}
exit;