<?php

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

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

if ($is_admin_direktur) {
    // Admin & direktur melihat semua urgent task
    $data = mysqli_query($conn,"
        SELECT *
        FROM urgent_task
        ORDER BY id DESC
    ");
} else {
    // User biasa hanya melihat task yang dia buat sendiri
    // ATAU task yang dia tercatat sebagai penerima
    $nama_login_esc = mysqli_real_escape_string($conn, $nama_login);
    $data = mysqli_query($conn,"
        SELECT DISTINCT ut.*
        FROM urgent_task ut
        LEFT JOIN urgent_penerima up ON up.urgent_id = ut.id
        WHERE ut.dibuat_oleh = '$nama_login_esc'
        OR up.id_user = '$id_user_login'
        ORDER BY ut.id DESC
    ");
}

// 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;
}

// Ambil status penerima untuk user yang sedang login, dikumpulkan per urgent_id
$status_penerima = [];
$q_status = mysqli_query($conn,"
    SELECT urgent_id, status, bukti_foto
    FROM urgent_penerima
    WHERE id_user = '".(int)$_SESSION['id_user']."'
");
while ($s = mysqli_fetch_assoc($q_status)) {
    $status_penerima[$s['urgent_id']] = $s;
}
?>

<style>
.page-card{
    background:#fff;
    border-radius:16px;
    overflow:hidden;
    box-shadow:0 2px 10px rgba(0,0,0,.05);
}

.page-card-header{
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding:15px 20px;
    background:#f0fdf4;
    border-bottom:1px solid #dcfce7;
}

.page-card-header h5{
    margin:0;
    font-weight:700;
}

.btn-add{
    padding:8px 14px;
    border-radius:8px;
    text-decoration:none;
    background:#16a34a;
    color:#fff;
    font-weight:600;
}

.btn-add:hover{
    color:#fff;
}

.data-table{
    width:100%;
    border-collapse:collapse;
}

.data-table th{
    background:#f9fafb;
    padding:12px;
}

.data-table td{
    padding:12px;
    border-top:1px solid #eee;
    vertical-align:middle;
}

.badge-open{
    background:#fef3c7;
    color:#92400e;
    padding:4px 10px;
    border-radius:20px;
}

.badge-selesai{
    background:#dcfce7;
    color:#166534;
    padding:4px 10px;
    border-radius:20px;
}

.badge-ditolak{
    background:#fee2e2;
    color:#991b1b;
    padding:4px 10px;
    border-radius:20px;
}

.badge-selesai-kecil{
    background:#dcfce7;
    color:#166534;
    padding:3px 8px;
    border-radius:20px;
    font-size:.75rem;
}

.badge-belum-kecil{
    background:#fee2e2;
    color:#991b1b;
    padding:3px 8px;
    border-radius:20px;
    font-size:.75rem;
}

.action-btns{
    display:flex;
    gap:6px;
    flex-wrap:wrap;
}
</style>

<div class="page-card">

    <div class="page-card-header">
        <h5>🚨 Data Urgent</h5>

        <a href="urgent_tambah.php" class="btn-add">
            + Tambah Urgent
        </a>
    </div>

    <div class="table-responsive">

        <table class="data-table">

            <thead>
                <tr>
                    <th>No</th>
                    <th>Judul</th>
                    <th>Pembuat</th>
                    <th>Tanggal</th>
                    <th>Status</th>
                    <th>Aksi</th>
                </tr>
            </thead>

            <tbody>

            <?php
            $no=1;

            while($row=mysqli_fetch_assoc($data)):

                $nama_pembuat = nama_pembuat_urgent($row['dibuat_oleh'], $map_user);
                $is_pembuat   = (trim($nama_pembuat) === trim($nama_login));
                $boleh_kelola = $is_pembuat || $is_admin_direktur;

                $info_penerima = $status_penerima[$row['id']] ?? null;
            ?>

            <tr>

                <td><?= $no++ ?></td>

                <td>
                    <?= htmlspecialchars($row['judul']) ?>
                </td>

                <td>
                    <?= htmlspecialchars($nama_pembuat) ?>
                </td>

                <td>
                    <?= date('d-m-Y H:i', strtotime($row['tanggal_buat'])) ?>
                </td>

                <td>

<?php if ($info_penerima): ?>

    <?php if ($info_penerima['status'] === 'Selesai'): ?>
        <span class="badge-selesai-kecil">
            ✅ Sudah Dikerjakan
        </span>
    <?php else: ?>
        <span class="badge-belum-kecil">
            ⏳ Belum Dikerjakan
        </span>
    <?php endif; ?>

<?php else: ?>

    <?php
    $total_penerima = mysqli_num_rows(mysqli_query(
        $conn,
        "SELECT id FROM urgent_penerima WHERE urgent_id='".$row['id']."'"
    ));

    $total_selesai = mysqli_num_rows(mysqli_query(
        $conn,
        "SELECT id FROM urgent_penerima
         WHERE urgent_id='".$row['id']."'
         AND status='Selesai'"
    ));
    ?>

    <span class="badge-open">
        <?= $total_selesai ?> / <?= $total_penerima ?> Selesai
    </span>

<?php endif; ?>

</td>

                <td>
                    <div class="action-btns">

                        <a href="urgent_detail.php?id=<?= $row['id'] ?>"
                           class="btn btn-sm btn-primary">
                            Detail
                        </a>

                        <?php if ($boleh_kelola): ?>

                            <a href="urgent_edit.php?id=<?= $row['id'] ?>"
                               class="btn btn-sm btn-warning">
                                Edit
                            </a>

                            <a href="urgent_hapus.php?id=<?= $row['id'] ?>"
                               class="btn btn-sm btn-danger"
                               onclick="return confirm('Yakin ingin menghapus urgent task ini?');">
                                Hapus
                            </a>

                        <?php endif; ?>

                        <?php if ($info_penerima && $info_penerima['status'] !== 'Selesai'): ?>

                            <a href="urgent_kerjakan.php?id=<?= $row['id'] ?>"
                               class="btn btn-sm btn-success">
                                🛠️ Kerjakan
                            </a>

                        <?php elseif ($info_penerima && $info_penerima['status'] === 'Selesai'): ?>

                            <a href="urgent_kerjakan.php?id=<?= $row['id'] ?>"
                               class="btn btn-sm btn-outline-success">
                                Lihat Bukti
                            </a>

                        <?php endif; ?>

                    </div>
                </td>

            </tr>

            <?php endwhile; ?>

            </tbody>

        </table>

    </div>

</div>