<?php

if (!isset($_GET['id'])) {
    die("Data tidak ditemukan");
}

$id = (int)$_GET['id'];

$data = mysqli_query($conn,"
    SELECT *
    FROM urgent_task
    WHERE id='$id'
");

if(mysqli_num_rows($data) == 0){
    die("Data tidak ditemukan");
}

$row = mysqli_fetch_assoc($data);

// Path folder bukti foto
$base_bukti = '/checklist_harian_harita/modules/urgent/bukti/';

// 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($row['dibuat_oleh'], $map_user);

$foto = mysqli_query($conn,"
    SELECT *
    FROM urgent_foto
    WHERE urgent_id='$id'
    ORDER BY id ASC
");

$is_pembuat = (trim($nama_pembuat) === trim($_SESSION['nama']));
$is_admin_direktur = ($_SESSION['role'] == 'admin' || $_SESSION['role'] == 'direktur');

// Ambil daftar penerima beserta status pengerjaan masing-masing
$penerima_list = mysqli_query($conn,"
    SELECT up.*, u.nama, u.role
    FROM urgent_penerima up
    LEFT JOIN users u ON u.id_user = up.id_user
    WHERE up.urgent_id='$id'
    ORDER BY up.status ASC, u.nama ASC
");

// Cek apakah user yang login adalah salah satu penerima
$penerima_saya = null;
$daftar_penerima = [];
while ($p = mysqli_fetch_assoc($penerima_list)) {
    $daftar_penerima[] = $p;
    if ((int)$p['id_user'] === (int)$_SESSION['id_user']) {
        $penerima_saya = $p;
    }
}

// Hanya pembuat, admin/direktur, atau penerima terkait yang boleh melihat detail ini
$boleh_lihat = $is_pembuat || $is_admin_direktur || $penerima_saya !== null;
if (!$boleh_lihat) {
    die("Akses ditolak. Anda bukan pembuat atau penerima urgent task ini.");
}
?>

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

.detail-header{
    padding:18px 22px;
    background:#f0fdf4;
    border-bottom:1px solid #dcfce7;
}

.detail-header h4{
    margin:0;
    font-weight:700;
}

.detail-body{
    padding:25px;
}

.info-table{
    width:100%;
}

.info-table td{
    padding:8px;
    vertical-align:top;
}

.label{
    width:180px;
    font-weight:700;
}

.badge-open{
    background:#fef3c7;
    color:#92400e;
    padding:5px 12px;
    border-radius:30px;
}

.badge-selesai{
    background:#dcfce7;
    color:#166534;
    padding:5px 12px;
    border-radius:30px;
}

.badge-ditolak{
    background:#fee2e2;
    color:#991b1b;
    padding:5px 12px;
    border-radius:30px;
}

.badge-belum-kerja{
    background:#fee2e2;
    color:#991b1b;
    padding:4px 10px;
    border-radius:30px;
    font-size:.8rem;
}

.gallery{
    display:flex;
    flex-wrap:wrap;
    gap:15px;
    margin-top:15px;
}

.gallery img{
    width:220px;
    height:220px;
    object-fit:cover;
    border-radius:12px;
    border:1px solid #ddd;
    transition:.2s;
}

.gallery img:hover{
    transform:scale(1.03);
}

.btn-valid{
    padding:10px 18px;
    border-radius:10px;
    text-decoration:none;
    color:#fff;
    font-weight:600;
}

.btn-selesai{
    background:#16a34a;
}

.btn-tolak{
    background:#dc2626;
}

.btn-back{
    background:#6b7280;
    color:#fff;
    text-decoration:none;
    padding:10px 18px;
    border-radius:10px;
}

.btn-edit{
    background:#f59e0b;
    color:#fff;
    text-decoration:none;
    padding:10px 18px;
    border-radius:10px;
    font-weight:600;
}

.btn-hapus{
    background:#dc2626;
    color:#fff;
    text-decoration:none;
    padding:10px 18px;
    border-radius:10px;
    font-weight:600;
}

.btn-kerjakan{
    background:#2563eb;
    color:#fff;
    text-decoration:none;
    padding:10px 18px;
    border-radius:10px;
    font-weight:600;
}

.section-title{
    margin-top:25px;
    margin-bottom:15px;
    font-weight:700;
}

.penerima-row{
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding:12px;
    border-bottom:1px solid #f1f5f9;
}

.penerima-row:last-child{
    border-bottom:none;
}

.thumb-bukti{
    width:48px;
    height:48px;
    object-fit:cover;
    border-radius:8px;
    border:1px solid #e5e7eb;
}
</style>

<div class="detail-card">

    <div class="detail-header">
        <h4>🚨 Detail Urgent Task</h4>
    </div>

    <div class="detail-body">

        <table class="info-table">

            <tr>
                <td class="label">Judul</td>
                <td><?= htmlspecialchars($row['judul']) ?></td>
            </tr>

            <tr>
                <td class="label">Keterangan</td>
                <td><?= nl2br(htmlspecialchars($row['deskripsi'])) ?></td>
            </tr>

            <tr>
                <td class="label">Dibuat Oleh</td>
                <td><?= htmlspecialchars($nama_pembuat) ?></td>
            </tr>

            <tr>
                <td class="label">Tanggal</td>
                <td>
                    <?= !empty($row['tanggal_buat'])
                        ? date('d-m-Y H:i', strtotime($row['tanggal_buat']))
                        : '-' ?>
                </td>
            </tr>

        </table>

        <div class="section-title">📌 Progress Penerima</div>

        <div class="border rounded">
            <?php if (empty($daftar_penerima)): ?>
                <div class="p-3 text-muted">Belum ada penerima.</div>
            <?php endif; ?>

            <?php foreach ($daftar_penerima as $p): ?>
                <div class="penerima-row">
                    <div class="d-flex align-items-center gap-2">
                        <?php if ($p['status'] === 'Selesai' && $p['bukti_foto']): ?>
                            <a href="<?= $base_bukti . htmlspecialchars($p['bukti_foto']) ?>" target="_blank">
                                <img src="<?= $base_bukti . htmlspecialchars($p['bukti_foto']) ?>" class="thumb-bukti">
                            </a>
                        <?php endif; ?>
                        <div>
                            <div class="fw-semibold"><?= htmlspecialchars($p['nama'] ?? 'User') ?></div>
                            <div class="small text-muted"><?= htmlspecialchars($p['role'] ?? '') ?></div>
                        </div>
                    </div>

                    <div class="text-end">
                        <?php if ($p['status'] === 'Selesai'): ?>
                            <span class="badge-selesai">✅ Selesai</span>
                            <div class="small text-muted"><?= date('d-m-Y H:i', strtotime($p['tanggal_selesai'])) ?></div>
                        <?php else: ?>
                            <span class="badge-belum-kerja">⏳ Belum</span>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="section-title">📷 Galeri Bukti Foto</div>

        <div class="gallery">
            <?php
            $ada_foto = false;
            while ($f = mysqli_fetch_assoc($foto)):
                $ada_foto = true;
            ?>
                <a href="<?= $base_bukti . htmlspecialchars($f['nama_file']) ?>" target="_blank">
                    <img src="<?= $base_bukti . htmlspecialchars($f['nama_file']) ?>">
                </a>
            <?php endwhile; ?>

            <?php if (!$ada_foto): ?>
                <p class="text-muted">Belum ada foto bukti pengerjaan.</p>
            <?php endif; ?>
        </div>

        <hr>

        <div class="d-flex gap-2 flex-wrap">

            <a href="urgent_list.php"
               class="btn-back">
                ← Kembali
            </a>

            <?php if ($is_pembuat || $is_admin_direktur): ?>

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

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

            <?php endif; ?>

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

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

            <?php endif; ?>

            <?php if($is_admin_direktur){ ?>

                <?php if($row['status']=='Open'){ ?>

                <a
                    href="urgent_status.php?id=<?= $row['id'] ?>&status=Selesai"
                    class="btn-valid btn-selesai"
                    onclick="return confirm('Tandai sebagai selesai?')">

                    ✓ Selesai
                </a>

                <a
                    href="urgent_status.php?id=<?= $row['id'] ?>&status=Ditolak"
                    class="btn-valid btn-tolak"
                    onclick="return confirm('Tolak pekerjaan ini?')">

                    ✕ Ditolak
                </a>

                <?php } ?>

            <?php } ?>

        </div>

    </div>

</div>