<?php

if (!isset($_SESSION['id_user'])) {
    die("Akses ditolak");
}

$id_user_login = (int)$_SESSION['id_user'];
$id_task = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Path absolut untuk tampil di browser
$base_bukti = '/checklist_harian_harita/modules/urgent/bukti/';

$q = mysqli_query($conn, "SELECT * FROM urgent_task WHERE id = '$id_task' LIMIT 1");
$task = mysqli_fetch_assoc($q);

if (!$task) {
    die("Urgent task tidak ditemukan.");
}

// Pastikan user login ini memang salah satu penerima
$q_penerima = mysqli_query($conn, "
    SELECT * FROM urgent_penerima
    WHERE urgent_id = '$id_task' AND id_user = '$id_user_login'
    LIMIT 1
");
$penerima = mysqli_fetch_assoc($q_penerima);

if (!$penerima) {
    die("Akses ditolak. Anda bukan penerima urgent task ini.");
}

$upload_dir = __DIR__ . '/bukti/';
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

$error = null;

if (isset($_POST['kirim_bukti'])) {

    if ($penerima['status'] === 'Selesai') {
        $error = "Task ini sudah ditandai selesai.";
    } else {

        $allowed_ext    = ['jpg', 'jpeg', 'png', 'webp'];
        $uploaded_files = [];
        $upload_error   = null;

        // Proses multi-file (opsional — boleh kosong)
        $files = $_FILES['bukti_foto'] ?? null;

        if ($files && is_array($files['name'])) {
            foreach ($files['name'] as $i => $orig_name) {

                // Lewati slot kosong
                if ($files['error'][$i] === UPLOAD_ERR_NO_FILE) continue;

                if ($files['error'][$i] !== UPLOAD_ERR_OK) {
                    $upload_error = "Gagal mengunggah salah satu file.";
                    break;
                }

                $ext = strtolower(pathinfo($orig_name, PATHINFO_EXTENSION));

                if (!in_array($ext, $allowed_ext)) {
                    $upload_error = "Format file tidak didukung: $orig_name. Gunakan JPG, PNG, atau WEBP.";
                    break;
                }

                if ($files['size'][$i] > 5 * 1024 * 1024) {
                    $upload_error = "Ukuran file maksimal 5MB per foto.";
                    break;
                }

                $nama_file = 'bukti_' . $id_task . '_' . $id_user_login . '_' . time() . '_' . $i . '.' . $ext;
                $target    = $upload_dir . $nama_file;

                if (move_uploaded_file($files['tmp_name'][$i], $target)) {
                    $uploaded_files[] = $nama_file;
                } else {
                    $upload_error = "Gagal menyimpan file ke server.";
                    break;
                }
            }
        }

        if ($upload_error) {
            $error = $upload_error;

            // Hapus file yang sudah terlanjur diupload jika ada error
            foreach ($uploaded_files as $f) {
                @unlink($upload_dir . $f);
            }

        } else {

            // Simpan nama file pertama di kolom bukti_foto (kompatibilitas kolom lama)
            $bukti_utama = !empty($uploaded_files) ? $uploaded_files[0] : ($penerima['bukti_foto'] ?? '');

            mysqli_query($conn, "
                UPDATE urgent_penerima
                SET status          = 'Selesai',
                    bukti_foto      = '" . mysqli_real_escape_string($conn, $bukti_utama) . "',
                    tanggal_selesai = NOW()
                WHERE id = '" . (int)$penerima['id'] . "'
            ");

            // Catat di urgent_dikerjakan jika belum ada
            $cek_kerja = mysqli_query($conn, "
                SELECT id FROM urgent_dikerjakan
                WHERE urgent_id = '$id_task' AND id_user = '$id_user_login'
                LIMIT 1
            ");
            if (mysqli_num_rows($cek_kerja) === 0) {
                mysqli_query($conn, "
                    INSERT INTO urgent_dikerjakan (urgent_id, id_user)
                    VALUES ('$id_task', '$id_user_login')
                ");
            }

            // Simpan semua foto ke tabel urgent_foto
            foreach ($uploaded_files as $nama_file) {
                mysqli_query($conn, "
                    INSERT INTO urgent_foto (urgent_id, nama_file, upload_at)
                    VALUES ('$id_task', '" . mysqli_real_escape_string($conn, $nama_file) . "', NOW())
                ");
            }

            echo "<script>alert('Berhasil! Task ditandai selesai.'); window.location='urgent_list.php';</script>";
            exit;
        }
    }
}

// Ambil foto-foto yang sudah diupload sebelumnya untuk ditampilkan
$foto_lama = [];
$q_foto = mysqli_query($conn, "
    SELECT * FROM urgent_foto
    WHERE urgent_id = '$id_task'
    ORDER BY id ASC
");
while ($f = mysqli_fetch_assoc($q_foto)) {
    $foto_lama[] = $f;
}
?>

<div class="card shadow-sm" style="border-radius:14px; border:1px solid var(--mint-border);">
    <div class="card-body p-4">

        <h6 class="fw-bold mb-3" style="color:var(--text-primary);">🛠️ Kerjakan Urgent Task</h6>

        <div class="mb-3 p-3" style="background:#f9fafb; border-radius:10px;">
            <div class="fw-bold mb-1"><?= htmlspecialchars($task['judul']) ?></div>
            <div class="text-muted small"><?= nl2br(htmlspecialchars($task['deskripsi'])) ?></div>
            <?php if ($task['deadline']): ?>
                <div class="small mt-2">📅 Deadline: <?= date('d-m-Y', strtotime($task['deadline'])) ?></div>
            <?php endif; ?>
        </div>

        <?php if (isset($error)): ?>
            <div class="alert alert-danger py-2"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <?php if ($penerima['status'] === 'Selesai'): ?>

            <div class="alert alert-success">
                ✅ Anda sudah menyelesaikan task ini pada
                <?= date('d-m-Y H:i', strtotime($penerima['tanggal_selesai'])) ?>.
            </div>

            <?php if (!empty($foto_lama)): ?>
                <label class="form-label fw-semibold">Bukti Foto:</label>
                <div class="d-flex flex-wrap gap-2 mb-3">
                    <?php foreach ($foto_lama as $f): ?>
                        <a href="<?= $base_bukti . htmlspecialchars($f['nama_file']) ?>" target="_blank">
                            <img src="<?= $base_bukti . htmlspecialchars($f['nama_file']) ?>"
                                 style="width:120px; height:120px; object-fit:cover; border-radius:8px; border:1px solid #ddd;">
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <a href="urgent_list.php" class="btn btn-outline-secondary">Kembali</a>

        <?php else: ?>

            <form method="POST" enctype="multipart/form-data" id="kerjakan-form">

                <div class="mb-3">
                    <label class="form-label fw-semibold">
                        Lampirkan Bukti Foto
                        <span class="text-muted fw-normal">(opsional, bisa lebih dari 1)</span>
                    </label>

                    <div class="d-flex gap-2 flex-wrap mb-2">
                        <label class="btn btn-success mb-0" for="input-kamera">
                            📷 Ambil Foto (Kamera)
                        </label>
                        <label class="btn btn-outline-success mb-0" for="input-galeri">
                            🖼️ Pilih dari Galeri
                        </label>
                    </div>

                    <input type="file" id="input-kamera"
                           accept="image/*" capture="environment"
                           style="display:none;" multiple>

                    <input type="file" id="input-galeri"
                           accept="image/*"
                           style="display:none;" multiple>

                    <!-- Input tersembunyi yang dikirim ke server -->
                    <input type="file" name="bukti_foto[]" id="bukti_foto_final"
                           style="display:none;" multiple>

                    <!-- Area preview thumbnail -->
                    <div id="preview-area" class="d-flex flex-wrap gap-2 mt-2"></div>
                    <div id="foto-count" class="small text-muted mt-1"></div>
                </div>

                <button type="submit" name="kirim_bukti" class="btn btn-primary fw-bold px-4">
                    ✅ Tandai Selesai &amp; Kirim
                </button>
                <a href="urgent_list.php" class="btn btn-outline-secondary px-4">Batal</a>

            </form>

        <?php endif; ?>

    </div>
</div>

<script>
const inputKamera = document.getElementById('input-kamera');
const inputGaleri = document.getElementById('input-galeri');
const inputFinal  = document.getElementById('bukti_foto_final');
const previewArea = document.getElementById('preview-area');
const fotoCount   = document.getElementById('foto-count');

// Simpan semua File yang dipilih di sini
let selectedFiles = [];

function updatePreview() {
    previewArea.innerHTML = '';

    if (selectedFiles.length === 0) {
        fotoCount.textContent = '';
        return;
    }

    fotoCount.textContent = selectedFiles.length + ' foto dipilih';

    selectedFiles.forEach((file, idx) => {
        const reader = new FileReader();
        reader.onload = function (e) {
            const wrapper = document.createElement('div');
            wrapper.style.cssText = 'position:relative; display:inline-block;';
            wrapper.innerHTML = `
                <img src="${e.target.result}"
                     style="width:90px; height:90px; object-fit:cover;
                            border-radius:8px; border:1px solid #ddd;">
                <button type="button"
                        onclick="removeFile(${idx})"
                        style="position:absolute; top:-6px; right:-6px;
                               background:#dc2626; color:#fff; border:none;
                               border-radius:50%; width:20px; height:20px;
                               font-size:12px; cursor:pointer; line-height:1;">
                    ✕
                </button>
                <div style="font-size:10px; color:#6b7280; max-width:90px;
                            overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
                    ${file.name}
                </div>
            `;
            previewArea.appendChild(wrapper);
        };
        reader.readAsDataURL(file);
    });

    // Sync ke input file tersembunyi menggunakan DataTransfer
    const dt = new DataTransfer();
    selectedFiles.forEach(f => dt.items.add(f));
    inputFinal.files = dt.files;
}

function addFiles(fileList) {
    for (let i = 0; i < fileList.length; i++) {
        selectedFiles.push(fileList[i]);
    }
    updatePreview();
}

window.removeFile = function(idx) {
    selectedFiles.splice(idx, 1);
    updatePreview();
};

inputKamera?.addEventListener('change', function () {
    addFiles(this.files);
    this.value = ''; // reset agar bisa pilih file sama lagi
});

inputGaleri?.addEventListener('change', function () {
    addFiles(this.files);
    this.value = '';
});

// Sync ulang file sebelum submit
document.getElementById('kerjakan-form')?.addEventListener('submit', function () {
    const dt = new DataTransfer();
    selectedFiles.forEach(f => dt.items.add(f));
    inputFinal.files = dt.files;
});
</script>