const Api = (() => { // Deteksi path API secara otomatis const BASE = (() => { const path = window.location.pathname; const dir = path.substring(0, path.lastIndexOf('/') + 1); return dir + 'api/index.php'; })(); async function req(method, path, body=null) { // path contoh: '/penduduk' → '?r=penduduk' | '/penduduk/123' → '?r=penduduk/123' const cleanPath = path.replace(/^\//, ''); const url = `${BASE}?r=${cleanPath}`; const opts = { method, headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', }; if (body) opts.body = JSON.stringify(body); const res = await fetch(url, opts); const text = await res.text(); let json; try { json = JSON.parse(text); } catch { // PHP mengembalikan HTML/teks error bukan JSON const preview = text.substring(0, 200); throw new Error(`Server error ${res.status} — bukan JSON: ${preview}`); } if (!json.success) throw new Error(json.message || 'Terjadi kesalahan'); return json.data; } return { get: path => req('GET', path), post: (path, b) => req('POST', path, b), put: (path, b) => req('PUT', path, b), delete: path => req('DELETE', path), }; })();