<?php

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

$id_user_login = (int)$_SESSION['id_user'];
$nama_login = $_SESSION['nama'];

$q_penerima = 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']);
    $prioritas    = 'Medium';
    $deadline     = !empty($_POST['deadline']) ? "'".mysqli_real_escape_string($conn, $_POST['deadline'])."'" : "NULL";
    $dibuat_oleh  = mysqli_real_escape_string($conn, $nama_login);
    $penerima_ids = isset($_POST['penerima']) ? $_POST['penerima'] : [];

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

    $simpan = mysqli_query($conn,"
        INSERT INTO urgent_task
        (judul, deskripsi, prioritas, dibuat_oleh, tanggal_buat, deadline, status)
        VALUES
        ('$judul','$deskripsi','$prioritas','$dibuat_oleh',NOW(),$deadline,'Open')
    ");

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

    $urgent_id = mysqli_insert_id($conn);

    foreach ($penerima_ids as $pid) {
        $pid = (int)$pid;
        mysqli_query($conn,"
            INSERT INTO urgent_penerima (urgent_id, id_user, dibaca, status)
            VALUES ('$urgent_id','$pid', 0, 'Belum')
        ");
    }

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

show_form:
?>

<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);">🚨 Tambah Urgent Task</h6>

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

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

            <div class="mb-3">
                <label class="form-label fw-semibold">Judul Pekerjaan</label>
                <input type="text" name="judul" class="form-control"
                       placeholder="Deskripsikan masalah secara singkat…" required>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold">Keterangan / Detail</label>
                <textarea name="keterangan" class="form-control" rows="3"
                          placeholder="Jelaskan detail masalah, lokasi, atau instruksi…" required></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" min="<?= date('Y-m-d') ?>">
            </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_penerima)):
                        $no_penerima = false;
                        $nama_role = strtolower($u['nama'].' '.$u['role']);
                    ?>
                        <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'] ?>">
                            <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>

                <div class="d-flex justify-content-between align-items-center mt-2">
                    <small class="text-muted">Centang satu atau lebih penerima.</small>
                    <small class="text-muted"><span id="penerima-count">0</span> dipilih</small>
                </div>
            </div>

            <button type="submit" name="simpan" class="btn btn-success fw-bold px-4">
                🚀 Kirim Urgent Task
            </button>

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

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

    function updateCount() {
        countEl.textContent = document.querySelectorAll('.penerima-checkbox:checked').length;
    }

    checkboxes.forEach(cb => cb.addEventListener('change', updateCount));

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

    updateCount();
});

document.getElementById('urgent-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>