<?php

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

$id_user_login = (int)$_SESSION['id_user'];
$nama_login = $_SESSION['nama'];
$is_admin_direktur = ($_SESSION['role'] == 'admin' || $_SESSION['role'] == 'direktur');

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

$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.");
}

// Map id_user => nama, untuk menjaga kompatibilitas data lama
// yang kolom dibuat_oleh-nya berisi angka (id_user) bukan nama.
$map_user = [];
$q_map_user = mysqli_query($conn, "SELECT id_user, nama FROM users");
while ($u = mysqli_fetch_assoc($q_map_user)) {
    $map_user[(int)$u['id_user']] = $u['nama'];
}

function nama_pembuat_urgent($dibuat_oleh, $map_user) {
    $val = trim($dibuat_oleh);
    if ($val !== '' && ctype_digit($val) && isset($map_user[(int)$val])) {
        return $map_user[(int)$val];
    }
    return $val;
}

$nama_pembuat = nama_pembuat_urgent($task['dibuat_oleh'], $map_user);
$is_pembuat = (trim($nama_pembuat) === trim($nama_login));

if (isset($_GET['debug'])) {
    echo "<pre style='background:#fff3cd;padding:15px;border:1px solid #ffc107;'>";
    echo "DEBUG INFO\n";
    echo "----------\n";
    echo "session id_user   : " . var_export($_SESSION['id_user'] ?? null, true) . "\n";
    echo "session nama      : " . var_export($_SESSION['nama'] ?? null, true) . "\n";
    echo "session role      : " . var_export($_SESSION['role'] ?? null, true) . "\n";
    echo "task dibuat_oleh  : " . var_export($task['dibuat_oleh'], true) . "\n";
    echo "nama_pembuat hasil: " . var_export($nama_pembuat, true) . "\n";
    echo "nama_login (trim) : " . var_export(trim($nama_login), true) . "\n";
    echo "is_pembuat        : " . var_export($is_pembuat, true) . "\n";
    echo "is_admin_direktur : " . var_export($is_admin_direktur, true) . "\n";
    echo "</pre>";
}

if (!$is_pembuat && !$is_admin_direktur) {
    die("Akses ditolak. Anda tidak memiliki izin untuk mengedit urgent task ini.");
}

// Ambil daftar penerima saat ini
$penerima_terpilih = [];
$q_terpilih = mysqli_query($conn, "SELECT id_user FROM urgent_penerima WHERE urgent_id = '$id_task'");
while ($r = mysqli_fetch_assoc($q_terpilih)) {
    $penerima_terpilih[] = (int)$r['id_user'];
}

// Daftar semua user aktif (selain diri sendiri) untuk pilihan penerima
$q_user = mysqli_query($conn, "
    SELECT id_user, nama, role
    FROM users
    WHERE status = 'aktif'
    AND id_user != '".$id_user_login."'
    ORDER BY role, nama
");

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

    $judul        = mysqli_real_escape_string($conn, $_POST['judul']);
    $deskripsi    = mysqli_real_escape_string($conn, $_POST['keterangan']);
    $deadline     = !empty($_POST['deadline']) ? "'".mysqli_real_escape_string($conn, $_POST['deadline'])."'" : "NULL";
    $penerima_ids = isset($_POST['penerima']) ? $_POST['penerima'] : [];

    if (empty($penerima_ids)) {
        $error = "Pilih minimal satu penerima urgent task.";
    } else {

        $update = mysqli_query($conn, "
            UPDATE urgent_task
            SET judul = '$judul',
                deskripsi = '$deskripsi',
                deadline = $deadline
            WHERE id = '$id_task'
        ");

        if (!$update) die("Error: ".mysqli_error($conn));

        // Sinkronkan penerima tanpa menghapus progress yang sudah ada
        $penerima_ids_int = array_map('intval', $penerima_ids);
        $in_list = implode(',', $penerima_ids_int);

        mysqli_query($conn, "
            DELETE FROM urgent_penerima
            WHERE urgent_id = '$id_task'
            AND id_user NOT IN ($in_list)
        ");

        foreach ($penerima_ids_int as $pid) {
            $cek = mysqli_query($conn, "
                SELECT id FROM urgent_penerima
                WHERE urgent_id = '$id_task' AND id_user = '$pid'
                LIMIT 1
            ");
            if (mysqli_num_rows($cek) === 0) {
                mysqli_query($conn, "
                    INSERT INTO urgent_penerima (urgent_id, id_user, dibaca, status)
                    VALUES ('$id_task', '$pid', 0, 'Belum')
                ");
            }
        }

        echo "<script>alert('Urgent task berhasil diperbarui!'); window.location='urgent_list.php';</script>";
        exit;
    }
}
?>

<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-4" style="color:var(--text-primary);">✏️ Edit Urgent Task</h6>

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

        <form method="POST" id="urgent-edit-form">

            <div class="mb-3">
                <label class="form-label fw-semibold">Judul Pekerjaan</label>
                <input type="text" name="judul" class="form-control"
                       value="<?= htmlspecialchars($task['judul']) ?>" required>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold">Keterangan / Detail</label>
                <textarea name="keterangan" class="form-control" rows="3"
                          required><?= htmlspecialchars($task['deskripsi']) ?></textarea>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold">Deadline <small class="text-muted fw-normal">(opsional)</small></label>
                <input type="date" name="deadline" class="form-control"
                       value="<?= $task['deadline'] ? date('Y-m-d', strtotime($task['deadline'])) : '' ?>">
            </div>

            <div class="mb-4">
                <label class="form-label fw-semibold">Kirim Kepada</label>

                <div class="mb-2">
                    <input type="text" id="penerima-search" class="form-control form-control-sm"
                           placeholder="🔍 Cari nama atau role…">
                </div>

                <div class="border rounded p-2" id="penerima-list" style="max-height:220px; overflow-y:auto;">
                    <?php
                    $no_penerima = true;
                    while ($u = mysqli_fetch_assoc($q_user)):
                        $no_penerima = false;
                        $nama_role = strtolower($u['nama'].' '.$u['role']);
                        $checked = in_array((int)$u['id_user'], $penerima_terpilih) ? 'checked' : '';
                    ?>
                        <div class="form-check penerima-item" data-search="<?= htmlspecialchars($nama_role) ?>">
                            <input class="form-check-input penerima-checkbox" type="checkbox"
                                   name="penerima[]" value="<?= $u['id_user'] ?>"
                                   id="penerima_<?= $u['id_user'] ?>" <?= $checked ?>>
                            <label class="form-check-label" for="penerima_<?= $u['id_user'] ?>">
                                <?= htmlspecialchars($u['nama']) ?> — <?= htmlspecialchars($u['role']) ?>
                            </label>
                        </div>
                    <?php endwhile; ?>

                    <?php if ($no_penerima): ?>
                        <p class="text-muted mb-0">Tidak ada user lain yang aktif.</p>
                    <?php endif; ?>
                </div>

                <small class="text-muted">Centang satu atau lebih penerima. Catatan: status &amp; validasi (Selesai/Ditolak) diatur lewat halaman Detail, bukan di sini.</small>
            </div>

            <button type="submit" name="simpan" class="btn btn-success fw-bold px-4">
                💾 Simpan Perubahan
            </button>
            <a href="urgent_list.php" class="btn btn-outline-secondary px-4">Batal</a>

        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const searchEl = document.getElementById('penerima-search');
    const items = document.querySelectorAll('.penerima-item');

    if (searchEl) {
        searchEl.addEventListener('input', function () {
            const keyword = this.value.toLowerCase().trim();
            items.forEach(item => {
                item.style.display = item.dataset.search.includes(keyword) ? '' : 'none';
            });
        });
    }
});

document.getElementById('urgent-edit-form').addEventListener('submit', function(e) {
    const checked = document.querySelectorAll('.penerima-checkbox:checked');
    if (checked.length === 0) {
        e.preventDefault();
        alert('⚠️ Pilih minimal satu penerima urgent task!');
    }
});
</script>