<?php
// observations.php

// Decode parameters
$tenant        = $_REQUEST['tenant']           ?? '';
$stage         = $_REQUEST['stage']            ?? '';    // e.g. '4'
$master_report = $report_id        ?? '';
$board_list    = json_decode($_REQUEST['board_list'] ?? '[]', true) ?: [];

// Fetch existing observations JSON from one of the elec_report rows
$stmt = $con->prepare("
    SELECT observations 
      FROM elec_report 
     WHERE master_report_id = ? 
     LIMIT 1
");
$stmt->bind_param("s", $master_report);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Decode into PHP array (empty if none saved yet)
$observations = json_decode($row['observations'] ?? '[]', true);
?>
<form id="observationsForm" enctype="multipart/form-data">
    <input type="hidden" name="tenant" value="<?= htmlspecialchars($tenant, ENT_QUOTES) ?>">
    <input type="hidden" name="stage" value="save_stage_4">
    <input type="hidden" name="master_report_id" value="<?= htmlspecialchars($master_report, ENT_QUOTES) ?>">
    <input type="hidden" name="board_list" value='<?= htmlspecialchars(json_encode($board_list), ENT_QUOTES) ?>'>

    <div id="observationsContainer">
        <?php foreach ($observations as $idx => $obs): ?>
        <div class="card mb-3 observation-entry" data-index="<?= $idx ?>">
            <div class="card-header d-flex justify-content-between">
                <strong>Observation #<?= $idx + 1 ?></strong>
                <button type="button"
                        class="btn btn-sm btn-danger"
                        onclick="removeObservation(<?= $idx ?>)">
                    <i class="fad fa-times"></i>
                </button>
            </div>
            <div class="card-body">
                <div class="row mb-2">
                    <div class="col-md-4">
                        <label>Category</label>
                        <select name="observations[<?= $idx ?>][category]" class="form-control">
                            <?php foreach (['General','Operational Limitation','Agreed Limitation'] as $cat): ?>
                            <option value="<?= $cat ?>"
                                    <?= (($obs['category'] ?? '') === $cat) ? 'selected' : '' ?>>
                                <?= $cat ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label>Location</label>
                        <input type="text"
                               name="observations[<?= $idx ?>][location]"
                               class="form-control"
                               value="<?= htmlspecialchars($obs['location'] ?? '', ENT_QUOTES) ?>">
                    </div>
                    <div class="col-md-4">
                        <label>Fault Code</label>
                        <input type="text"
                               name="observations[<?= $idx ?>][fault_code]"
                               class="form-control"
                               value="<?= htmlspecialchars($obs['fault_code'] ?? '', ENT_QUOTES) ?>">
                    </div>
                </div>

                <div class="mb-3">
                    <label>Observation</label>

                    <div class="d-flex">
                        <textarea id="observations[<?= $idx ?>][notes]" name="observations[<?= $idx ?>][notes]" class="form-control form-control-sm"
                                  rows="2"><?= htmlspecialchars($obs['notes'], ENT_QUOTES) ?></textarea>
                        <div class="d-flex flex-column">
                            <button type="button" class="btn btn-secondary mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clear Field"
                                    onClick="clearbox('observations[<?= $idx ?>][notes]')">
                                <i class="fad fa-eraser"></i>
                            </button>
                            <?php if($_SESSION['usertype']=="admins"){ ?>
                            <button type="button" class="btn btn-info mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View List"
                                    onClick="autofillElec('formComplete','observations[<?= $idx ?>][notes]','elecphrases')">
                                <i class="fad fa-edit"></i>
                            </button>
                            <button type="button" class="btn btn-success mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save field as new entry"
                                    onClick="savebox('observations[<?= $idx ?>][notes]','elecphrases')">
                                <i class="fad fa-save"></i>
                            </button>
                            <?php } else { ?>
                            <button type="button" class="btn btn-success mb-1 ms-4" onClick="javascript:void(0)"></button>
                            <button type="button" class="btn btn-info mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View List"
                                    onClick="autofillElec('formComplete','observations[<?= $idx ?>][notes]','elecphrases')">
                                <i class="fad fa-edit"></i>
                            </button>
                            <?php } ?>
                            <button type="button" class="btn btn-danger btn-info-alt ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Reset FIeld"
                                    onClick="resetBox('observations[<?= $idx ?>][notes]')">
                                <i class="fad fa-refresh"></i>
                            </button>
                        </div>
                    </div>
                </div>

                <?php
            // Each observation’s six images are named: <master_report>_obs_<idx>_<j>.jpg
            $grp = 'obs';
          ?>
                <div class="row mb-3 img-row">
                    <div class="col-12">
                        <label>Upload Images</label>
                        <div class="row image-uploads"
                             data-group="<?= $grp ?>"
                             data-obs="<?= $idx ?>">
                            <?php for ($j = 1; $j <= 6; $j++):
                  $fn   = "{$master_report}_X_{$grp}_{$idx}_{$j}.jpg";
                  $path = TENANT_DEFER . "/images/report_images/{$fn}";
                  $src  = "images/report_images/{$fn}?" . rand();
                ?>
                            <div class="col-lg-2 col-md-4 col-6 mb-2">
                                <div class="imup"
                                     data-service="images/elec_save.php"
                                     data-target="<?= $fn ?>"
                                     title="<?= $fn ?>"
                                     data-meta-reportid="<?= $master_report ?>"
                                     data-meta-boardid="X"
                                     data-meta-group="<?= $grp ?>"
                                     data-meta-observation="<?= $idx ?>"
                                     data-meta-imagenum="<?= $j ?>"
                                     data-crop-ratio="1.3333"
                                     <?php if (file_exists($path)): ?>
                                     data-initial-image="<?= $src ?>"
                                     <?php endif; ?>>
                                </div>
                                <small class="form-text text-muted">Image <?= $j ?></small>
                            </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <div class="mb-3">
        <button type="button"
                class="btn btn-outline-primary"
                onclick="addObservation()">
            Add Observation
        </button>
    </div>
</form>

<div class="row mt-4">
    <div class="d-flex justify-content-between align-items-center">
        <!-- Save Progress invokes the parent’s saveReportStage(4) -->
        <button type="button"
                class="btn btn-success"
                onclick="alertMessage(
              'Confirm Save',
              'Are you sure you want to save this stage?',
              () => saveReportStage(4)
            )">
            Save Progress
        </button>

        <!-- Mark Complete calls parent’s markStageComplete(4) -->
        <button id="markCompleteBtn"
                type="button"
                class="btn btn-info mx-3"
                onclick="alertMessage(
              'Confirm Completion',
              'Are you sure you want to mark this stage as complete?',
              () => markStageComplete(4)
            )">
            Mark Complete
        </button>

        <!-- Clear All calls parent’s clearStage(4) -->
        <button id="clearStageBtn"
                type="button"
                class="btn btn-danger"
                onclick="alertMessage(
              'Confirm Clear',
              'This will reset all data for this stage. Are you sure?',
              () => clearStage(4)
            )">
            Clear All
        </button>
    </div>
</div>

<script>
// Make PHP’s master_report_id available to JavaScript
var mr = <?= json_encode($master_report) ?>;
if (typeof obsIndex === 'undefined') {
    window.obsIndex = <?= count($observations) ?>;
} else {
    obsIndex = <?= count($observations) ?>;
}

// 1) Initialize all existing <div class="imup"> uploaders
initializeImageUploaders({
    uploadUrl: 'images/elec_save.php',
    cropRatio: 1,
    removeUrl: 'images/elec_remove.php'
});

// 2) Append a new blank observation card
function addObservation() {
    const container = document.getElementById('observationsContainer');
    const idx = obsIndex++;
    const grp = 'obs';

    // Use a proper JavaScript template literal so ${…} is substituted at runtime
    const tpl = `
      <div class="card mb-3 observation-entry" data-index="${idx}">
        <div class="card-header d-flex justify-content-between">
          <strong>Observation #${idx + 1}</strong>
          <button type="button"
                  class="btn btn-sm btn-danger"
                  onclick="removeObservation(${idx})">
            <i class="fad fa-times"></i>
          </button>
        </div>
        <div class="card-body">
          <div class="row mb-2">
            <div class="col-md-4">
              <label>Category</label>
              <select name="observations[${idx}][category]" class="form-control">
                <option>General</option>
                <option>Operational Limitation</option>
                <option>Agreed Limitation</option>
              </select>
            </div>
            <div class="col-md-4">
              <label>Location</label>
              <input type="text" name="observations[${idx}][location]" class="form-control">
            </div>
            <div class="col-md-4">
              <label>Fault Code</label>
              <input type="text" name="observations[${idx}][fault_code]" class="form-control">
            </div>
          </div>

          <div class="mb-3">
            <label>Observation</label>
            <div class="d-flex">
            <textarea id="observations[${idx}][notes]" name="observations[${idx}][notes]" class="form-control form-control-sm" rows="2"></textarea>
                                    <div class="d-flex flex-column">
                                        <button type="button" class="btn btn-secondary mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clear Field"
                                                onClick="clearbox('observations[${idx}][notes]')">
                                            <i class="fad fa-eraser"></i>
                                        </button>
                                        <?php if($_SESSION['usertype']=="admins"){ ?>
                                        <button type="button" class="btn btn-info mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View List"
                                                onClick="autofillElec('formComplete','observations[${idx}][notes]','elecphrases')">
                                            <i class="fad fa-edit"></i>
                                        </button>
                                        <button type="button" class="btn btn-success mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save field as new entry"
                                                onClick="savebox('observations[${idx}][notes]','elecphrases')">
                                            <i class="fad fa-save"></i>
                                        </button>
                                        <?php } else { ?>
                                        <button type="button" class="btn btn-success mb-1 ms-4" onClick="javascript:void(0)"></button>
                                        <button type="button" class="btn btn-info mb-1 ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View List"
                                                onClick="autofillElec('formComplete','observations[${idx}][notes]','elecphrases')">
                                            <i class="fad fa-edit"></i>
                                        </button>
                                        <?php } ?>
                                        <button type="button" class="btn btn-danger btn-info-alt ms-4" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Reset FIeld"
                                                onClick="resetBox('observations[<?= $grp ?>][<?= $idx ?>][text]')">
                                            <i class="fad fa-refresh"></i>
                                        </button>
                                    </div>
          </div>

          <div class="row mb-3 img-row">
            <div class="col-12">
              <label>Upload Images</label>
              <div class="row image-uploads"
                   data-group="${grp}"
                   data-obs="${idx}">
                ${[1,2,3,4,5,6].map(j => `
                  <div class="col-lg-2 col-md-4 col-6 mb-2">
                    <div class="imup"
                         data-service="images/elec_save.php"
                          title="${mr}_X_${grp}_${idx}_${j}.jpg"
                         data-target="${mr}_X_${grp}_${idx}_${j}.jpg"
                         data-meta-reportid="${mr}"
                         data-meta-boardid="X"
                         data-meta-group="${grp}"
                         data-meta-observation="${idx}"
                         data-meta-imagenum="${j}"
                         data-crop-ratio="1.3333">
                    </div>
                    <small class="form-text text-muted">Image ${j}</small>
                  </div>
                `).join('')}
              </div>
            </div>
          </div>
        </div>
      </div>
    `;

    container.insertAdjacentHTML('beforeend', tpl);

    // Re‐initialize newly inserted <div class="imup"> elements
    initializeImageUploaders({
        uploadUrl: 'images/elec_save.php',
        cropRatio: 1,
        removeUrl: 'images/elec_remove.php'
    });
}

// 3) Remove one observation card from DOM
function removeObservation(i) {
    const el = document.querySelector(`.observation-entry[data-index="${i}"]`);
    if (el) el.remove();
}
</script>