<?php
include 'db.php';

if (isset($_GET['id'])) {
    $id = $_GET['id'];
    $sql = "SELECT * FROM Report WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    $divisions = [];
    $divisionQuery = "SELECT DISTINCT division FROM Report";
    $divisionResult = $conn->query($divisionQuery);
    while ($division = $divisionResult->fetch_assoc()) {
        $divisions[] = $division['division'];
    }

    $blocks = [];
    $blockQuery = "SELECT DISTINCT block FROM Report WHERE division = ?";
    $blockStmt = $conn->prepare($blockQuery);
    $blockStmt->bind_param("s", $row['division']);
    $blockStmt->execute();
    $blockResult = $blockStmt->get_result();
    while ($block = $blockResult->fetch_assoc()) {
        $blocks[] = $block['block'];
    }

    $classifications = ['Kecil', 'Sedang', 'Besar'];

    $damageTypes = [];
    $damageTypeQuery = "SELECT DISTINCT damageType FROM Report";
    $damageTypeResult = $conn->query($damageTypeQuery);
    while ($damageType = $damageTypeResult->fetch_assoc()) {
        $damageTypes[] = $damageType['damageType'];
    }    

    $clean_time = trim($row['waktu_temuan']);
    $formatted = date('Y-m-d\TH:i', strtotime($clean_time));
}
?>

<form id="reportForm" action="update_report.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
    
    <!-- Fase Temuan Awal -->
    <h4 class="mt-4 mb-2">Fase Temuan Awal</h4>
    <div class="form-group">
        <label for="waktu_temuan">Waktu Temuan</label>
        <input 
            type="datetime-local" 
            id="waktu_temuan" 
            name="waktu_temuan" 
            class="form-control" 
            value="<?php echo date('Y-m-d\TH:i', strtotime($formatted)); ?>">
    </div>
    <div class="custom-file mb-3">
        <input type="file" id="initialPhoto-update" name="initialPhoto-update" class="custom-file-input" accept="image/*" data-file="<?php echo isset($row['initialPhoto']) ? $row['initialPhoto'] : ''; ?>">
        <label for="initialPhoto-update" class="custom-file-label" data-default="Upload Foto Awal">Upload Foto Awal</label>
        <p>Foto saat ini: <a href="<?php echo $row['initialPhoto']; ?>" target="_blank">Lihat Foto</a></p>
    </div>

    <!-- Fase Perlakuan -->
    <h4 class="mt-4 mb-2">Fase Perlakuan</h4>
    <div class="form-group">
        <label for="waktu_perlakuan">Waktu Perlakuan</label>
        <input 
            type="datetime-local" 
            id="waktu_perlakuan" 
            name="waktu_perlakuan" 
            class="form-control"
            value="<?php echo isset($row['waktu_perlakuan']) ? date('Y-m-d\TH:i', strtotime($row['waktu_perlakuan'])) : ''; ?>">
    </div>
    <div class="custom-file mb-3">
        <input type="file" id="photo_perlakuan-update" name="photo_perlakuan-update" class="custom-file-input" accept="image/*" data-file="<?php echo isset($row['photo_perlakuan']) ? $row['photo_perlakuan'] : ''; ?>">
        <label for="photo_perlakuan-update" class="custom-file-label" data-default="Upload Foto Perlakuan">Upload Foto Perlakuan</label>
        <p>Foto saat ini: <?php if (!empty($row['photo_perlakuan'])): ?><a href="<?php echo $row['photo_perlakuan']; ?>" target="_blank">Lihat Foto</a><?php else: ?>Belum ada foto<?php endif; ?></p>
    </div>

    <!-- Fase Verifikasi -->
    <h4 class="mt-4 mb-2">Fase Verifikasi</h4>
    <div class="form-group">
        <label for="waktu_verifikasi">Waktu Verifikasi</label>
        <input 
            type="datetime-local" 
            id="waktu_verifikasi" 
            name="waktu_verifikasi" 
            class="form-control"
            value="<?php echo isset($row['waktu_verifikasi']) ? date('Y-m-d\TH:i', strtotime($row['waktu_verifikasi'])) : ''; ?>">
    </div>
    <div class="custom-file mb-3">
        <input type="file" id="photo_verifikasi-update" name="photo_verifikasi-update" class="custom-file-input" accept="image/*" data-file="<?php echo isset($row['photo_verifikasi']) ? $row['photo_verifikasi'] : ''; ?>">
        <label for="photo_verifikasi-update" class="custom-file-label" data-default="Upload Foto Verifikasi">Upload Foto Verifikasi</label>
        <p>Foto saat ini: <?php if (!empty($row['photo_verifikasi'])): ?><a href="<?php echo $row['photo_verifikasi']; ?>" target="_blank">Lihat Foto</a><?php else: ?>Belum ada foto<?php endif; ?></p>
    </div>

    <!-- Fase Setelah Penanggulangan -->
    <h4 class="mt-4 mb-2">Fase Setelah Penanggulangan</h4>
    <div class="form-group">
        <label for="waktu_update_manual">Waktu Update</label>
        <input 
            type="datetime-local" 
            id="waktu_update_manual" 
            name="waktu_update_manual" 
            class="form-control">
    </div>
    <div class="custom-file mb-3">
        <input type="file" id="updatedPhoto-update" name="updatedPhoto-update" class="custom-file-input" accept="image/*" data-file="<?php echo isset($row['updatedPhoto']) ? $row['updatedPhoto'] : ''; ?>">
        <label for="updatedPhoto-update" class="custom-file-label" data-default="Upload Foto Setelah Penanggulangan">Upload Foto Setelah Penanggulangan</label>
        <p>Foto saat ini: <a href="<?php echo $row['updatedPhoto']; ?>" target="_blank">Lihat Foto</a></p>
    </div>

    <!-- Data Lainnya -->
    <h4 class="mt-4 mb-2">Data Lainnya</h4>
    <div class="form-group">
        <label for="status-update">Status</label>
        <select id="status-update" name="status-update" class="form-control">
            <option value="Belum Ditangani" <?php echo ($row['status'] == 'Belum Ditangani') ? 'selected' : ''; ?>>Belum Ditangani</option>
            <option value="Sedang Ditangani" <?php echo ($row['status'] == 'Sedang Ditangani') ? 'selected' : ''; ?>>Sedang Ditangani</option>
            <option value="Selesai" <?php echo ($row['status'] == 'Selesai') ? 'selected' : ''; ?>>Selesai</option>
        </select>
    </div>
    <div class="form-group">
        <label for="division-update">Afdeling</label>
        <select id="division-update" name="division-update" required>
            <option value="null">Pilih Afdeling</option>
            <?php foreach ($divisions as $division): ?>
                <option value="<?php echo $division; ?>" <?php echo ($division == $row['division']) ? 'selected' : ''; ?>>
                    <?php echo $division; ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="form-group">
        <label for="block-update">Blok</label>
        <select id="block-update" name="block-update" required>
            <option value="null">Pilih Blok</option>
            <?php foreach ($blocks as $block): ?>
                <option value="<?php echo $block; ?>" <?php echo ($block == $row['block']) ? 'selected' : ''; ?>>
                    <?php echo $block; ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="form-group">
        <label for="classification-update">Klasifikasi Kubangan</label>
        <select id="classification-update" name="classification-update" class="form-control" required>
            <option value="null">Pilih Klasifikasi</option>
            <?php foreach ($classifications as $classification): ?>
                <option value="<?php echo $classification; ?>" <?php echo ($classification == $row['classification']) ? 'selected' : ''; ?>>
                    <?php echo $classification; ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="form-group">
        <label for="damageType-update">Potensi Penyebab Kerusakan</label>
        <select id="damageType-update" name="damageType-update" required>
            <option value="null">Pilih Potensi Penyebab Kerusakan</option>
            <?php foreach ($damageTypes as $damageType): ?>
                <option value="<?php echo $damageType; ?>" <?php echo ($damageType == $row['damageType']) ? 'selected' : ''; ?>>
                    <?php echo $damageType; ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="form-group">
        <label for="mitigationPlan-update">Penanggulangan</label>
        <textarea id="mitigationPlan-update" name="mitigationPlan-update" class="form-control" rows="2" required><?php echo $row['mitigationPlan']; ?></textarea>
    </div>
    <div class="form-group">
        <label for="notes-update">Catatan</label>
        <textarea id="notes-update" name="notes-update" class="form-control" rows="4" required><?php echo $row['notes']; ?></textarea>
    </div>
    <button type="submit" class="btn btn-primary mt-4 mb-4">Update Data</button>
</form>

<!-- Script update label input file custom Bootstrap -->
<script>
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.custom-file-input').forEach(function(input) {
    var label = input.nextElementSibling;
    var filePath = input.getAttribute('data-file');
    var defaultText = label.getAttribute('data-default') || label.textContent;
    // Set label ke nama file lama saat load
    if (filePath) {
      var fileName = filePath.split('/').pop();
      label.textContent = fileName;
    } else {
      label.textContent = defaultText;
    }
    // Saat file dipilih
    input.addEventListener('change', function(e) {
      var fileName = '';
      if (this.files && this.files.length > 0) {
        fileName = this.files[0].name;
      }
      label.textContent = fileName || defaultText;
    });
  });
});
</script>