<?php
/**
 * Template Name: Profile Search Embed
 * Description: Lightweight iframe-friendly page for searching dosen by name/NIP filtered by id_unit.
 */

if (!function_exists('sanitize_text_field')) {
    function sanitize_text_field($value)
    {
        $value = (string) $value;
        $value = preg_replace('/[\x00-\x1F\x7F]/u', '', $value);
        $value = strip_tags($value);
        return trim($value);
    }
}

if (!function_exists('esc_attr')) {
    function esc_attr($value)
    {
        return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('esc_html')) {
    function esc_html($value)
    {
        return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
    }
}

$id_unit = isset($_GET['id_unit']) ? sanitize_text_field($_GET['id_unit']) : '';
$id_sunit = isset($_GET['id_sunit']) ? sanitize_text_field($_GET['id_sunit']) : '';
$keyword = isset($_GET['q']) ? trim(sanitize_text_field($_GET['q'])) : '';
$page = isset($_GET['page']) ? max(1, (int) sanitize_text_field($_GET['page'])) : 1;
$per_page = 10;
$results = [];
$unit_name = '';
$total_results = 0;
$total_pages = 1;
$api_error = false;

if ($id_unit !== '') {
    $api_url = 'https://simdos.unud.ac.id/master_dosen/listdosen?id_unit=' . urlencode($id_unit);
    if ($id_sunit !== '') {
        $api_url .= '&id_sunit=' . urlencode($id_sunit);
    }
    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'header' => "User-Agent: Mozilla/5.0\r\nAccept: application/json\r\n",
            'timeout' => 20,
        ],
    ]);

    $response = @file_get_contents($api_url, false, $context);
    if ($response !== false) {
        $decoded = json_decode($response, true);
        if (json_last_error() === JSON_ERROR_NONE && isset($decoded['data']) && is_array($decoded['data'])) {
            foreach ($decoded['data'] as $row) {
                $nama = isset($row['nama']) ? (string) $row['nama'] : '';
                $nip = isset($row['nip']) ? (string) $row['nip'] : '';
                $unit_homebase = isset($row['unit_homebase']) ? (string) $row['unit_homebase'] : '';
                $sunit_homebase = isset($row['sunit_homebase']) ? (string) $row['sunit_homebase'] : '';
                $id_sunit_homebase = isset($row['id_sunit_homebase']) ? (string) $row['id_sunit_homebase'] : '';
                $fungsional = isset($row['fungsional']) ? (string) $row['fungsional'] : '';
                $pendidikan = isset($row['pendidikan_terakhir']) ? (string) $row['pendidikan_terakhir'] : '';
                $jurusan = isset($row['jurusan']) ? (string) $row['jurusan'] : '';
                $bidang_ilmu = isset($row['bidang_ilmu']) ? (string) $row['bidang_ilmu'] : '';
                $google_scholar = isset($row['akun_google_scholar']) ? (string) $row['akun_google_scholar'] : (isset($row['google_scholar']) ? (string) $row['google_scholar'] : '');
                $scopus = isset($row['akun_scopus']) ? (string) $row['akun_scopus'] : (isset($row['scopus']) ? (string) $row['scopus'] : '');
                $sinta = isset($row['akun_sinta']) ? (string) $row['akun_sinta'] : (isset($row['sinta']) ? (string) $row['sinta'] : '');
                $foto = isset($row['file_foto']) ? (string) $row['file_foto'] : '';

                if ($unit_name === '' && $unit_homebase !== '') {
                    $unit_name = $unit_homebase;
                }

                if ($keyword !== '') {
                    $needle = strtolower($keyword);
                    $name_match = stripos(strtolower($nama), $needle) !== false;
                    $nip_match = stripos(strtolower($nip), $needle) !== false;
                    if (!$name_match && !$nip_match) {
                        continue;
                    }
                }

                $results[] = [
                    'nip' => $nip,
                    'nama' => $nama,
                    'nama_unit' => $unit_homebase,
                    'sunit_homebase' => $sunit_homebase,
                    'id_sunit_homebase' => $id_sunit_homebase,
                    'fungsional' => $fungsional,
                    'pendidikan' => $pendidikan,
                    'jurusan' => $jurusan,
                    'bidang_ilmu' => $bidang_ilmu,
                    'google_scholar' => $google_scholar,
                    'scopus' => $scopus,
                    'sinta' => $sinta,
                    'foto' => $foto,
                ];
            }

            usort($results, function ($a, $b) {
                return strcmp($a['nama'], $b['nama']);
            });

            $total_results = count($results);
            $total_pages = $total_results > 0 ? (int) ceil($total_results / $per_page) : 1;
            if ($page > $total_pages) {
                $page = $total_pages;
            }

            $offset = ($page - 1) * $per_page;
            $results = array_slice($results, $offset, $per_page);
        } else {
            $api_error = true;
        }
    } else {
        $api_error = true;
    }
}
?><!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Pencarian Dosen</title>
    <style>
        :root {
            color-scheme: light;
            font-family: Arial, Helvetica, sans-serif;
        }
        body {
            margin: 0;
            background: #ffffff;
            color: #0f172a;
        }
        .wrap {
            max-width: 900px;
            margin: 0 auto;
            padding: 24px;
        }
        .card {
            background: #ffffff;
            border: 1px solid #e2e8f0;
            border-radius: 14px;
            box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08);
            padding: 24px;
        }
        h1 {
            margin: 0 0 8px;
            font-size: 1.5rem;
            color: #1d4ed8;
        }
        .muted {
            color: #64748b;
            margin-bottom: 16px;
        }
        form {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            align-items: end;
            margin-bottom: 18px;
        }
        .field {
            flex: 1 1 72px;
        }
        label {
            display: block;
            font-size: 0.9rem;
            font-weight: 700;
            margin-bottom: 6px;
            color: #334155;
        }
        input {
            width: 100%;
            box-sizing: border-box;
            padding: 10px 12px;
            border: 1px solid #cbd5e1;
            border-radius: 8px;
            font-size: 0.95rem;
        }
        button { 
            padding: 10px 16px;
            border: 0;
            border-radius: 8px;
            background: #1d4ed8;
            color: #fff;
            font-weight: 700;
            cursor: pointer;
        }
        button:hover {
            background: #1e40af;
        }
        .info {
            padding: 12px 14px;
            background: #eff6ff;
            border-left: 4px solid #3b82f6;
            border-radius: 8px;
            margin-bottom: 16px;
            color: #1e3a8a;
        }
        .empty {
            padding: 16px;
            border: 1px dashed #cbd5e1;
            border-radius: 10px;
            color: #64748b;
            background: #ffffff;
        }
        .result-list {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 18px;
            align-items: start;
        }
        .result-item {
            display: flex;
            gap: 12px;
            align-items: flex-start;
            padding: 14px;
            min-height: 120px;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            background: #ffffff;
            box-shadow: 0 4px 12px rgba(15,23,42,0.04);
        }
        .result-photo {
            width: 120px;
            height: 120px;
            border-radius: 8px;
            object-fit: cover;
            background: #e2e8f0;
            flex-shrink: 0;
        }
        .result-content {
            flex: 1;
        }
        @media (max-width: 700px) {
            .wrap {
                padding: 12px;
            }
            .card {
                padding: 16px;
            }
            form {
                flex-direction: column;
                align-items: stretch;
            }
            button {
                width: 100%;
            }
            .result-list {
                grid-template-columns: 1fr;
                gap: 12px;
            }
            .result-item {
                flex-direction: column;
                align-items: center;
                text-align: center;
                padding: 12px;
                min-height: auto;
            }
            .result-photo {
                width: 88px;
                height: 88px;
            }
            .result-content {
                width: 100%;
            }
            .pagination {
                flex-direction: column;
                align-items: stretch;
            }
            .page-link,
            .page-info {
                text-align: center;     
            }
        }
        @media (max-width: 480px) {
            h1 {
                font-size: 1.25rem;
            }
            .wrap {
                padding: 8px;
            }
            .card {
                padding: 12px;
                border-radius: 10px;
            }
            input {
                padding: 9px 10px;
            }
            .result-photo {
                width: 72px;
                height: 72px;
            }
        }
        .result-name {
            font-weight: 700;
            color: #0f172a;
            margin-bottom: 6px;
            font-size: 1.05rem;
        }
        .result-nip {
            color: #475569;
            font-size: 0.95rem;
        }
        .profile-link {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            color: #475569;
            text-decoration: none;
            font-weight: 600;
        }
        .profile-link:hover {
            color: #334155;
            text-decoration: underline;
        }
        .pagination {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            margin-top: 16px;
            padding-top: 14px;
            border-top: 1px solid #e2e8f0;
        }
        .page-link {
            display: inline-block;
            padding: 8px 12px;
            border-radius: 8px;
            background: #eff6ff;
            color: #1d4ed8;
            text-decoration: none;
            font-weight: 700;
        }
        .page-link:hover {
            background: #dbeafe;
        }
        .page-info {
            color: #64748b;
            font-size: 0.95rem;
        }
    </style>
</head>
<body>
    <div class="wrap">
        <div class="card">
            <!-- <h1>DATA DOSEN</h1> -->
       
            <form method="get" action="">
                <input type="hidden" name="id_unit" value="<?php echo esc_attr($id_unit); ?>">
                <input type="hidden" name="id_sunit" value="<?php echo esc_attr($id_sunit); ?>">
                <input type="hidden" name="page" value="1">
                <div class="field">
                    <label for="q">Cari Nama atau NIP</label>
                    <input type="text" id="q" name="q" value="<?php echo esc_attr($keyword); ?>" placeholder="Contoh: I Ketut, 198701012015041001">
                </div>
                <button type="submit">Cari</button>
            </form>

            <?php if ($id_unit === '') : ?>
                <div class="empty">Parameter id_unit belum diberikan. Gunakan URL seperti /profile-embed/?id_unit=123.</div>
            <?php else : ?>
                <!-- <?php if ($unit_name !== '') : ?>
                    <div class="info">Menampilkan data untuk unit: <strong><?php echo esc_html($unit_name); ?></strong></div>
                <?php endif; ?> -->

                <?php if ($api_error) : ?>
                    <div class="empty">Gagal mengambil data dari API SIMDOS. Silakan coba lagi sebentar lagi.</div>
                <?php elseif (empty($results)) : ?>
                    <div class="empty"><?php echo $keyword === '' ? 'Belum ada data dosen untuk unit ini.' : 'Tidak ada hasil yang ditemukan.'; ?></div>
                <?php else : ?>
                    <div class="info">Menampilkan <?php echo esc_html(($page - 1) * $per_page + 1); ?>–<?php echo esc_html(min($page * $per_page, $total_results)); ?> dari <?php echo esc_html($total_results); ?> data</div>
                    <div class="result-list">
                        <?php foreach ($results as $row) : ?>
                            <div class="result-item">
                                <?php if (!empty($row['foto'])) : ?>
                                    <img class="result-photo" src="<?php echo esc_attr($row['foto']); ?>" alt="Foto <?php echo esc_attr($row['nama']); ?>">
                                <?php else : ?>
                                    <div class="result-photo" style="display:flex;align-items:center;justify-content:center;color:#64748b;font-size:0.8rem;">No Foto</div>
                                <?php endif; ?>
                                <div class="result-content">
                                    <div class="result-name"><?php echo esc_html($row['nama']); ?></div>
                                    <?php if (!empty($row['sunit_homebase']) || !empty($row['id_sunit_homebase'])) : ?>
                                        <div class="result-nip">Program Studi: <?php echo esc_html(trim($row['sunit_homebase'] . (!empty($row['sunit_homebase']) && !empty($row['id_sunit_homebase']) ? ' (' . $row['id_sunit_homebase'] . ')' : $row['id_sunit_homebase']))); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($row['fungsional'])) : ?>
                                        <div class="result-nip">Jabatan Fungsional: <?php echo esc_html($row['fungsional']); ?></div>
                                    <?php endif; ?>
                                    <?php $pendidikan_text = trim(($row['pendidikan'] !== '' ? $row['pendidikan'] : '') . (($row['pendidikan'] !== '' && $row['jurusan'] !== '') ? ' ' : '') . ($row['jurusan'] !== '' ? $row['jurusan'] : '')); ?>
                                    <?php if ($pendidikan_text !== '') : ?>
                                        <div class="result-nip">Pendidikan: <?php echo esc_html($pendidikan_text); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($row['bidang_ilmu'])) : ?>
                                        <div class="result-nip">Bidang Ilmu: <?php echo esc_html($row['bidang_ilmu']); ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($row['google_scholar'])) : ?>
                                        <div class="result-nip">
                                            <a class="profile-link" href="<?php echo esc_attr((preg_match('#^https?://#', $row['google_scholar']) || strpos($row['google_scholar'], 'www.') === 0) ? $row['google_scholar'] : 'https://' . $row['google_scholar']); ?>" target="_blank" rel="noopener noreferrer">
                                                <span aria-hidden="true">🎓</span> Google Scholar
                                            </a>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (!empty($row['scopus'])) : ?>
                                        <div class="result-nip">
                                            <a class="profile-link" href="<?php echo esc_attr((preg_match('#^https?://#', $row['scopus']) || strpos($row['scopus'], 'www.') === 0) ? $row['scopus'] : 'https://' . $row['scopus']); ?>" target="_blank" rel="noopener noreferrer">
                                                <span aria-hidden="true">📘</span> Scopus
                                            </a>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (!empty($row['sinta'])) : ?>
                                        <div class="result-nip">
                                            <a class="profile-link" href="<?php echo esc_attr((preg_match('#^https?://#', $row['sinta']) || strpos($row['sinta'], 'www.') === 0) ? $row['sinta'] : 'https://' . $row['sinta']); ?>" target="_blank" rel="noopener noreferrer">
                                                <span aria-hidden="true">📗</span> Sinta
                                            </a>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <?php if ($total_pages > 1) : ?>
                        <div class="pagination">
                            <?php if ($page > 1) : ?>
                                <a class="page-link" href="?<?php echo http_build_query(['id_unit' => $id_unit, 'id_sunit' => $id_sunit, 'q' => $keyword, 'page' => $page - 1]); ?>">← Sebelumnya</a>
                            <?php else : ?>
                                <span></span>
                            <?php endif; ?>

                            <span class="page-info">Halaman <?php echo esc_html($page); ?> dari <?php echo esc_html($total_pages); ?></span>

                            <?php if ($page < $total_pages) : ?>
                                <a class="page-link" href="?<?php echo http_build_query(['id_unit' => $id_unit, 'id_sunit' => $id_sunit, 'q' => $keyword, 'page' => $page + 1]); ?>">Berikutnya →</a>
                            <?php else : ?>
                                <span></span>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
