<?php

namespace App\Http\Controllers;

use App\Models\PemeriksaanKesehatan;
use App\Models\Pasien;
use App\Models\EmbeddingWajah;
use App\Models\AnalisisAi;
use App\Models\LogNotifikasi;
use App\Models\Dokter; // Perbaikan: tambahkan import
use App\Models\DokterPasien; // Perbaikan: tambahkan import
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Http;

class PemeriksaanKesehatanController extends Controller
{
    /**
     * Display a listing of pemeriksaan
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            return $this->datatables($request);
        }

        // Return view without data binding since datatables handles it
        return view('petugas.pemeriksaan.index');
    }

    /**
     * Server-side DataTables endpoint
     */
    public function datatables(Request $request)
    {
        try {
            $query = PemeriksaanKesehatan::with(['pasien']);

            // Total records before filtering
            $recordsTotal = PemeriksaanKesehatan::count();

            // Filter by date range
            if ($request->filled('tanggal_mulai')) {
                $query->whereDate('waktu_pemeriksaan', '>=', $request->tanggal_mulai);
            }
            if ($request->filled('tanggal_selesai')) {
                $query->whereDate('waktu_pemeriksaan', '<=', $request->tanggal_selesai);
            }

            // Filter by kategori suhu
            if ($request->filled('kategori_suhu')) {
                $query->where('kategori_suhu', $request->kategori_suhu);
            }

            // Search
            if ($request->has('search') && !empty($request->search['value'])) {
                $search = $request->search['value'];
                $query->where(function ($q) use ($search) {
                    $q->where('kode_pemeriksaan', 'like', "%{$search}%")
                        ->orWhereHas('pasien', function ($q2) use ($search) {
                            $q2->where('nama_lengkap', 'like', "%{$search}%")
                                ->orWhere('no_rekam_medis', 'like', "%{$search}%");
                        });
                });
            }

            // Count filtered records
            $recordsFiltered = $query->count();

            // Order by
            if ($request->has('order')) {
                $orderColumnIndex = $request->order[0]['column'];
                $orderDir = $request->order[0]['dir'];
                
                $columns = [
                    0 => 'kode_pemeriksaan',
                    1 => 'pasien_id',
                    2 => 'suhu_tubuh',
                    3 => 'kategori_suhu',
                    4 => 'waktu_pemeriksaan', // display
                    5 => 'waktu_pemeriksaan', // hidden ts for sorting
                ];

                if (isset($columns[$orderColumnIndex])) {
                    if ($columns[$orderColumnIndex] == 'pasien_id') {
                        // For sorting by related patient model (need join/complex sort or just skip for now and sort by code)
                        // Simplified approach here: fall back to kode_pemeriksaan if relationship sort is tricky
                        $query->orderBy('kode_pemeriksaan', $orderDir);
                    } else {
                        $query->orderBy($columns[$orderColumnIndex], $orderDir);
                    }
                }
            } else {
                $query->orderBy('waktu_pemeriksaan', 'desc');
            }

            // Pagination
            if ($request->has('start') && $request->has('length') && $request->length != -1) {
                $query->skip($request->start)->take($request->length);
            }

            $pemeriksaan = $query->get();

            $data = $pemeriksaan->map(function ($item) {
                // Formatting functions equivalent to the blade implementation
                
                // Kode
                $kode_formatted = '<span class="font-mono text-xs bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-400 px-2 py-0.5 rounded">' . e($item->kode_pemeriksaan) . '</span>';
                
                // Pasien
                $nama_pasien = $item->pasien ? e($item->pasien->nama_lengkap) : 'Pasien Dihapus';
                $no_rm = $item->pasien ? e($item->pasien->no_rekam_medis) : '-';
                $pasien_formatted = '<p class="font-medium text-gray-800 dark:text-gray-200">' . $nama_pasien . '</p>' . 
                                   '<p class="text-xs text-gray-400 dark:text-gray-500 mt-0.5">' . $no_rm . '</p>';

                // Suhu
                $suhu_formatted = '<span class="font-bold text-gray-800 dark:text-gray-100">' . $item->suhu_tubuh . '°C</span>';

                // Kategori
                $badgeMap = [
                    'HIPOTERMIA'   => 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',
                    'NORMAL'       => 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300',
                    'SUBFEBRIS'    => 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/40 dark:text-yellow-300',
                    'DEMAM_RINGAN' => 'bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300',
                    'DEMAM_SEDANG' => 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
                    'DEMAM_TINGGI' => 'bg-red-600 text-white',
                ];
                $badge = $badgeMap[$item->kategori_suhu] ?? 'bg-gray-100 text-gray-600 dark:bg-slate-700 dark:text-gray-400';
                $kategori_formatted = '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ' . $badge . '">' . str_replace('_', ' ', $item->kategori_suhu) . '</span>';

                // Waktu
                $waktu_formatted = '<p class="text-sm text-gray-700 dark:text-gray-300">' . $item->waktu_pemeriksaan->format('d/m/Y') . '</p>' .
                                  '<p class="text-xs text-gray-400 dark:text-gray-500">' . $item->waktu_pemeriksaan->format('H:i') . '</p>';

                // Aksi
                $url = route('petugas.pemeriksaan.show', $item->id);
                $aksi = '<a href="' . $url . '" class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-teal-500 hover:bg-teal-600 text-white text-xs font-medium rounded-lg transition shadow-sm"><i class="fas fa-eye text-xs"></i> Detail</a>';

                return [
                    'kode'     => $kode_formatted,
                    'pasien'   => $pasien_formatted,
                    'suhu'     => $suhu_formatted,
                    'kategori' => $kategori_formatted,
                    'waktu'    => $waktu_formatted,
                    'waktu_ts' => $item->waktu_pemeriksaan->timestamp, 
                    'aksi'     => $aksi,
                ];
            });

            return response()->json([
                'draw' => intval($request->draw),
                'recordsTotal' => $recordsTotal,
                'recordsFiltered' => $recordsFiltered,
                'data' => $data,
            ]);

        } catch (\Exception $e) {
            \Log::error('DataTables Error (Pemeriksaan): ' . $e->getMessage());
            
            return response()->json([
                'draw' => intval($request->draw ?? 0),
                'recordsTotal' => 0,
                'recordsFiltered' => 0,
                'data' => [],
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Show form untuk pemeriksaan manual
     */
    public function createManual()
    {
        $pasienList = Pasien::where('status_pasien', 'AKTIF')
            ->orderBy('nama_lengkap')
            ->get();

        return view('petugas.pemeriksaan.manual-create', [
            'pasien_list' => $pasienList,
            'kategori_suhu' => [
                'HIPOTERMIA' => '< 35°C',
                'NORMAL' => '35-37.5°C',
                'SUBFEBRIS' => '37.5-38°C',
                'DEMAM_RINGAN' => '38-38.5°C',
                'DEMAM_SEDANG' => '38.5-39.5°C',
                'DEMAM_TINGGI' => '> 39.5°C',
            ],
        ]);
    }

    /**
     * Store pemeriksaan manual
     */
    public function storeManual(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'pasien_id'              => 'required|exists:pasien,id',
            'suhu_tubuh'             => 'required|numeric|min:30|max:45',
            'detak_jantung'          => 'nullable|integer|min:30|max:220',
            'tekanan_darah_sistol'   => 'nullable|integer|min:60|max:250',
            'tekanan_darah_diastol'  => 'nullable|integer|min:40|max:150',
            'saturasi_oksigen'       => 'nullable|integer|min:50|max:100',
            'berat_badan_saat_ini'   => 'nullable|numeric|min:1|max:300',
            'keluhan_utama'          => 'nullable|string|max:1000',
            'gejala_lain'            => 'nullable|array',
            'catatan_petugas'        => 'nullable|string',
            'lokasi_pemeriksaan'     => 'nullable|string|max:100',
            'jenis_pemeriksaan'      => 'required|in:RUTIN,KELUHAN,KONTROL,DARURAT',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput()
                ->with('error', 'Validasi gagal: ' . implode(', ', $validator->errors()->all()));
        }

        try {
            DB::beginTransaction();

            $pasien = Pasien::findOrFail($request->pasien_id);

            // Hitung kategori suhu — FIX: wajib di-set agar isDemam() tidak error
            $suhu          = (float) $request->suhu_tubuh;
            $kategoriSuhu  = PemeriksaanKesehatan::kategorikanSuhu($suhu);

            // Create pemeriksaan
            $pemeriksaan = PemeriksaanKesehatan::create([
                'pasien_id'              => $pasien->id,
                'id_eksternal_pasien'    => $pasien->id_eksternal,
                'suhu_tubuh'             => $suhu,
                'kategori_suhu'          => $kategoriSuhu,
                'detak_jantung'          => $request->detak_jantung,
                'tekanan_darah_sistol'   => $request->tekanan_darah_sistol,
                'tekanan_darah_diastol'  => $request->tekanan_darah_diastol,
                'saturasi_oksigen'       => $request->saturasi_oksigen,
                'berat_badan_saat_ini'   => $request->berat_badan_saat_ini,
                'keluhan_utama'          => $request->keluhan_utama,
                'gejala_lain'            => $request->gejala_lain ? json_encode($request->gejala_lain) : null,
                'catatan_petugas'        => $request->catatan_petugas,
                'lokasi_pemeriksaan'     => $request->lokasi_pemeriksaan ?? 'Ruang Pemeriksaan Utama',
                'jenis_pemeriksaan'      => $request->jenis_pemeriksaan,
                'status_pemeriksaan'     => 'SELESAI',
                'waktu_pemeriksaan'      => now(),
                'diperiksa_oleh'         => auth()->id(),
                'ip_address'             => $request->ip(),
            ]);

            DB::commit(); // FIX: commit DULU sebelum proses AI/notifikasi agar data tidak rollback

           $aiStatus = null;  // null = tidak diproses, 'success', 'error'
$waStatus = null;
 
// Proses AI
try {
    if ($pemeriksaan->isDemam() || $request->filled('keluhan_utama')) {
        $this->requestAnalisisAI($pemeriksaan);
        $aiStatus = 'success';
    }
} catch (\Exception $aiError) {
    $aiStatus = 'error';
    \Log::warning('AI Analysis gagal (data tetap tersimpan): ' . $aiError->getMessage());
}
 
// Proses notifikasi WA
try {
    if ($pemeriksaan->kategori_suhu === 'DEMAM_TINGGI') {
        $sent = $this->sendNotifikasi($pemeriksaan, 'DEMAM_TINGGI');
        $waStatus = $sent ? 'success' : 'error';
    }
} catch (\Exception $notifError) {
    $waStatus = 'error';
    \Log::warning('Notifikasi gagal (data tetap tersimpan): ' . $notifError->getMessage());
}
 
$redirect = redirect()->route('petugas.pemeriksaan.index')
    ->with('success', 'Pemeriksaan ' . $pasien->nama_lengkap . ' berhasil disimpan. Kategori: ' . $kategoriSuhu);
 
if ($aiStatus) $redirect->with('ai_status', $aiStatus);
if ($waStatus) $redirect->with('wa_status', $waStatus);
 
return $redirect;
 
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('StoreManual Error: ' . $e->getMessage() . ' | ' . $e->getTraceAsString());

            return redirect()->back()
                ->withInput()
                ->with('error', 'Gagal menyimpan pemeriksaan: ' . $e->getMessage());
        }
    }
    /**
     * Show single pemeriksaan
     */
    public function show($id)
    {
        $pemeriksaan = PemeriksaanKesehatan::with([
            'pasien',
            'embeddingWajah',
            'petugas',
            'dokter',
            'analisisAi',
            'logNotifikasi',
        ])->findOrFail($id);

        return view('petugas.pemeriksaan.show', compact('pemeriksaan'));
    }

    /**
     * Update pemeriksaan
     */
    public function update(Request $request, $id)
    {
        $pemeriksaan = PemeriksaanKesehatan::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'suhu_tubuh' => 'nullable|numeric|min:30|max:45',
            'detak_jantung' => 'nullable|integer|min:30|max:220',
            'tekanan_darah_sistol' => 'nullable|integer|min:60|max:250',
            'tekanan_darah_diastol' => 'nullable|integer|min:40|max:150',
            'saturasi_oksigen' => 'nullable|integer|min:50|max:100',
            'berat_badan_saat_ini' => 'nullable|numeric|min:1|max:300',
            'keluhan_utama' => 'nullable|string|max:1000',
            'gejala_lain' => 'nullable|array',
            'catatan_petugas' => 'nullable|string',
            'tindakan_yang_dilakukan' => 'nullable|string',
            'rekomendasi' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput()
                ->with('error', 'Validasi gagal. Silakan periksa data yang dimasukkan.');
        }

        try {
            $pemeriksaan->update($request->only([
                'suhu_tubuh',
                'detak_jantung',
                'tekanan_darah_sistol',
                'tekanan_darah_diastol',
                'saturasi_oksigen',
                'berat_badan_saat_ini',
                'keluhan_utama',
                'gejala_lain',
                'catatan_petugas',
                'tindakan_yang_dilakukan',
                'rekomendasi',
            ]));

            return redirect()->route('petugas.pemeriksaan.show', $id)
                ->with('success', 'Pemeriksaan berhasil diupdate');

        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Gagal update pemeriksaan: ' . $e->getMessage());
        }
    }

    /**
     * Review form untuk dokter
     */
    public function reviewForm($id)
    {
        // Pastikan user adalah dokter
        if (!auth()->user()->isDokter()) {
            abort(403, 'Hanya dokter yang dapat mengakses halaman ini.');
        }
        
        $pemeriksaan = PemeriksaanKesehatan::with(['pasien', 'analisisAi'])->findOrFail($id);
        
        // Pastikan dokter menangani pasien ini
        $dokter = auth()->user()->dokter;
        $isMyPatient = DokterPasien::where('dokter_id', $dokter->id)
            ->where('pasien_id', $pemeriksaan->pasien_id)
            ->where('status_penanganan', 'AKTIF')
            ->exists();
        
        if (!$isMyPatient) {
            abort(403, 'Anda tidak menangani pasien ini.');
        }
        
        return view('dokter.pemeriksaan.review', compact('pemeriksaan'));
    }

    /**
     * Review pemeriksaan oleh dokter
     */
    public function reviewDokter(Request $request, $id)
    {
        // Validasi untuk dokter
        if (!auth()->user()->isDokter()) {
            return response()->json([
                'success' => false,
                'message' => 'Hanya dokter yang dapat melakukan review',
            ], 403);
        }
        
        $validator = Validator::make($request->all(), [
            'diagnosis_dokter' => 'required|string|max:1000',
            'resep_dokter' => 'nullable|string|max:2000',
            'catatan_dokter' => 'nullable|string|max:1000',
            'tindakan_medis' => 'nullable|string|max:1000',
            'status_pemeriksaan' => 'required|in:SELESAI,DITINDAK_LANJUT,RUJUK',
        ]);
        
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }
        
        try {
            $pemeriksaan = PemeriksaanKesehatan::findOrFail($id);
            $dokter = auth()->user()->dokter;
            
            // Update pemeriksaan dengan data dokter
            $pemeriksaan->update([
                'diagnosis_dokter' => $request->diagnosis_dokter,
                'resep_dokter' => $request->resep_dokter,
                'catatan_dokter' => $request->catatan_dokter,
                'tindakan_medis' => $request->tindakan_medis,
                'status_pemeriksaan' => $request->status_pemeriksaan,
                'direview_oleh' => $dokter->id,
                'waktu_review' => now(),
            ]);
            
            // Update juga di tabel DokterPasien jika ada
            $dokterPasien = DokterPasien::where('dokter_id', $dokter->id)
                ->where('pasien_id', $pemeriksaan->pasien_id)
                ->first();
                
            if ($dokterPasien) {
                $dokterPasien->update([
                    'diagnosis_utama' => $request->diagnosis_dokter,
                    'resep_dokter' => $request->resep_dokter,
                    'catatan_dokter' => $request->catatan_dokter,
                    'tanggal_terakhir_periksa' => now(),
                ]);
            }
            
            return redirect()->route('dokter.pasien.detail', $pemeriksaan->pasien_id)
                ->with('success', 'Review pemeriksaan berhasil disimpan.');
                
        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Gagal menyimpan review: ' . $e->getMessage());
        }
    }

    /**
     * Delete pemeriksaan
     */
    public function destroy($id)
    {
        try {
            $pemeriksaan = PemeriksaanKesehatan::findOrFail($id);
            $pemeriksaan->delete();

            return response()->json([
                'success' => true,
                'message' => 'Pemeriksaan berhasil dihapus',
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal menghapus pemeriksaan: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Dashboard statistik
     */
    public function dashboard(Request $request)
    {
        $today = now()->toDateString();

        $stats = [
            'total_hari_ini' => PemeriksaanKesehatan::whereDate('waktu_pemeriksaan', $today)->count(),
            'demam_hari_ini' => PemeriksaanKesehatan::whereDate('waktu_pemeriksaan', $today)
                ->demam()->count(),
            'perlu_review' => PemeriksaanKesehatan::perluReview()->count()
                ->whereDate('waktu_pemeriksaan', $today)->count(),
        ];

        // Grafik per kategori suhu
        $grafikSuhu = PemeriksaanKesehatan::whereDate('waktu_pemeriksaan', $today)
            ->select('kategori_suhu', DB::raw('count(*) as total'))
            ->groupBy('kategori_suhu')
            ->get();

        // Pemeriksaan terbaru
        $pemeriksaanTerbaru = PemeriksaanKesehatan::with(['pasien', 'petugas'])
            ->orderBy('waktu_pemeriksaan', 'desc')
            ->limit(10)
            ->get();

        return view('petugas.pemeriksaan.dashboard', compact('stats', 'grafikSuhu', 'pemeriksaanTerbaru'));
    }
    /**
 * Generate AI analisis untuk pemeriksaan (trigger manual)
 */
public function generateAnalisis(Request $request, $pemeriksaan)
{
    $pemeriksaan = PemeriksaanKesehatan::findOrFail($pemeriksaan);

    try {
        $result = $this->requestAnalisisAI($pemeriksaan);

        if ($result) {
            return redirect()->route('petugas.pemeriksaan.show', $pemeriksaan->id)
                ->with('success', 'Analisis AI berhasil dibuat');
        } else {
            return redirect()->route('petugas.pemeriksaan.show', $pemeriksaan->id)
                ->with('error', 'Analisis AI gagal dibuat');
        }
    } catch (\Exception $e) {
        return redirect()->route('petugas.pemeriksaan.show', $pemeriksaan->id)
            ->with('error', 'Error: ' . $e->getMessage());
    }
}

       /**
     * Request analisis AI — Prioritas: Gemini BETA → GPT OSS 120B → Gemini Lite
     * Menggunakan endpoint /api/ai/gemini dengan parameter 'text' dan 'cookie'
     */
    private function requestAnalisisAI($pemeriksaan)
    {
        $dataInput = [];
        $prompt    = '';

        try {
            $pemeriksaan->loadMissing('pasien');

            $dataInput = [
                'nama_pasien'      => $pemeriksaan->pasien->nama_lengkap,
                'suhu_tubuh'       => $pemeriksaan->suhu_tubuh,
                'kategori_suhu'    => $pemeriksaan->kategori_suhu,
                'detak_jantung'    => $pemeriksaan->detak_jantung,
                'tekanan_darah'    => $pemeriksaan->tekanan_darah_formatted ?? null,
                'saturasi_oksigen' => $pemeriksaan->saturasi_oksigen,
                'keluhan_utama'    => $pemeriksaan->keluhan_utama,
                'gejala_lain'      => is_string($pemeriksaan->gejala_lain)
                                        ? json_decode($pemeriksaan->gejala_lain, true)
                                        : ($pemeriksaan->gejala_lain ?? []),
                'riwayat_penyakit' => $pemeriksaan->pasien->riwayat_penyakit ?? null,
                'alergi'           => $pemeriksaan->pasien->alergi ?? null,
                'usia'             => $pemeriksaan->pasien->usia,
                'jenis_kelamin'    => $pemeriksaan->pasien->jenis_kelamin,
            ];

            $prompt  = $this->buildStructuredPromptGemini($dataInput);
            $baseUrl = env('SIPUTZX_API_URL', 'https://api.siputzx.my.id');

            // ==================== GEMINI BETA (PRIORITAS UTAMA) ====================
            $cookieJson = '[{"domain":".gemini.google.com","expirationDate":1810693210.325487,"hostOnly":false,"httpOnly":false,"name":"_ga","path":"/","sameSite":"unspecified","secure":false,"session":false,"storeId":"0","value":"GA1.1.1423662132.1775449180"},{"domain":".gemini.google.com","expirationDate":1810693215.557618,"hostOnly":false,"httpOnly":false,"name":"_ga_BF8Q35BMLM","path":"/","sameSite":"unspecified","secure":false,"session":false,"storeId":"0","value":"GS2.1.s1776133210$o3$g0$t1776133215$j55$l0$h0"},{"domain":".gemini.google.com","expirationDate":1810693217.268495,"hostOnly":false,"httpOnly":false,"name":"_ga_WC57KJ50ZZ","path":"/","sameSite":"unspecified","secure":false,"session":false,"storeId":"0","value":"GS2.1.s1776133209$o3$g0$t1776133217$j52$l0$h0"},{"domain":".gemini.google.com","expirationDate":1783225180,"hostOnly":false,"httpOnly":false,"name":"_gcl_au","path":"/","sameSite":"unspecified","secure":false,"session":false,"storeId":"0","value":"1.1.919574046.1775449180"},{"domain":".google.com","expirationDate":1791007943.594958,"hostOnly":false,"httpOnly":true,"name":"AEC","path":"/","sameSite":"lax","secure":true,"session":false,"storeId":"0","value":"AaJma5vF6IgN3rqX5_pQioHaHtsfOT1tUvdD_Yv436YcH7j1lN6Aw2CMCw"},{"domain":".google.com","expirationDate":1810004176.596878,"hostOnly":false,"httpOnly":false,"name":"APISID","path":"/","sameSite":"unspecified","secure":false,"session":false,"storeId":"0","value":"KbNLMcZ3mEuHeFks/AirRcaZDEFMBBWMjX"},{"domain":".google.com","expirationDate":1810004176.596794,"hostOnly":false,"httpOnly":true,"name":"HSID","path":"/","sameSite":"unspecified","secure":false,"session":false,"storeId":"0","value":"AZNbMxUFNDVNvMWlO"},{"domain":".google.com","expirationDate":1791869596.404591,"hostOnly":false,"httpOnly":true,"name":"NID","path":"/","sameSite":"no_restriction","secure":true,"session":false,"storeId":"0","value":"530=ZUy8KdKl8W7o8UAq_WbLEpR8s9-8ln-ecopmhoJfDY-82UeLSOTK3PTxIuQxlV4F0X6r1Z6pZiVxnJdxwIyn_Nrp37yEtEhNOegyVUz-GGtET95_5C3JxFASCByWHLbsW0577FXF3fu_NsJV45iZRGmt8cm50LV6jefNKSQguAQL9iA1eI1rlWfzFIv3zpVXhS72FnHgvgs19d1TDYXeHBcWEsC8ifUm3oO_8W_kkLXSPoS2_kAjuzklMZI-8CN_kbSBHskX-s6wFtaGwuIOJ02Tn1l5e5clrhEJFlwmvUOYAVUbjBVCoc99jomOaFIjK1kqLY8ErI83TFqO6c0"},{"domain":".google.com","expirationDate":1810004176.596915,"hostOnly":false,"httpOnly":false,"name":"SAPISID","path":"/","sameSite":"unspecified","secure":true,"session":false,"storeId":"0","value":"RKAE4XyzMZZr--c3/ApMSGmeEyyluidacT"},{"domain":".google.com","expirationDate":1790996245.773276,"hostOnly":false,"httpOnly":false,"name":"SEARCH_SAMESITE","path":"/","sameSite":"strict","secure":false,"session":false,"storeId":"0","value":"CgQIxaAB"},{"domain":".google.com","expirationDate":1810004178.027429,"hostOnly":false,"httpOnly":false,"name":"SID","path":"/","sameSite":"unspecified","secure":false,"session":false,"storeId":"0","value":"g.a0008gjfoRUCh8czp2SA8zYvy8_k0q3MXwAQyIskpgpxVwMgBfxGFLaSezHfQMjuLmBYPRQv_gACgYKAdcSARISFQHGX2MiZxRjOGR_PNWyJ5_ftLg8CBoVAUF8yKr_euHIR2pVorPs41133g800076"},{"domain":".google.com","expirationDate":1807669271.634545,"hostOnly":false,"httpOnly":false,"name":"SIDCC","path":"/","sameSite":"unspecified","secure":false,"session":false,"storeId":"0","value":"AKEyXzWzfHu432GFJ8yBFnM28mcSWSr_Cfv74rmdC7mtrjyiaS9vk-NWq__zRJN_lohCpM-xLA"},{"domain":".google.com","expirationDate":1791869595.897985,"hostOnly":false,"httpOnly":true,"name":"SNID","path":"/verify","sameSite":"lax","secure":true,"session":false,"storeId":"0","value":"ABDP0S1Db_aO0g0KdnWDDyF8S3l3T77yvfrxBMB0ZPqOGAcmbiQF2M6FpH0wVyvYXzluTIf1_5D52qNcP-IE8utoqFwqAGc2Nr8"},{"domain":".google.com","expirationDate":1810004176.596831,"hostOnly":false,"httpOnly":true,"name":"SSID","path":"/","sameSite":"unspecified","secure":true,"session":false,"storeId":"0","value":"AgCzvZWd3x-fTC4wn"},{"domain":".google.com","expirationDate":1810004176.596952,"hostOnly":false,"httpOnly":false,"name":"__Secure-1PAPISID","path":"/","sameSite":"unspecified","secure":true,"session":false,"storeId":"0","value":"RKAE4XyzMZZr--c3/ApMSGmeEyyluidacT"},{"domain":".google.com","expirationDate":1810004178.027538,"hostOnly":false,"httpOnly":true,"name":"__Secure-1PSID","path":"/","sameSite":"unspecified","secure":true,"session":false,"storeId":"0","value":"g.a0008gjfoRUCh8czp2SA8zYvy8_k0q3MXwAQyIskpgpxVwMgBfxGC1Wap0e750TNJCL0lEQjuwACgYKAVQSARISFQHGX2MiTWEzfb0M-AkN9pjbGBHHuRoVAUF8yKo7YmPnvselQYx64l70yvet0076"},{"domain":".google.com","expirationDate":1807669271.634723,"hostOnly":false,"httpOnly":true,"name":"__Secure-1PSIDCC","path":"/","sameSite":"unspecified","secure":true,"session":false,"storeId":"0","value":"AKEyXzXdwISSj3FQQyI_D5Opa4AzywIbpPEuAcKBVUbFRgX5yhj88fszbmtu9tOBiiG4nntioQ"},{"domain":".google.com","expirationDate":1776133714.472166,"hostOnly":false,"httpOnly":true,"name":"__Secure-1PSIDRTS","path":"/","sameSite":"unspecified","secure":true,"session":false,"storeId":"0","value":"sidts-CjcBWhotCa1sc7TQWyVgohYAHtIY5sM3oqqeF2btjvg89sEikcu2ENp6_WkYukHv-rK9bXkJnjQzEAA"},{"domain":".google.com","expirationDate":1807669114.472054,"hostOnly":false,"httpOnly":true,"name":"__Secure-1PSIDTS","path":"/","sameSite":"unspecified","secure":true,"session":false,"storeId":"0","value":"sidts-CjcBWhotCa1sc7TQWyVgohYAHtIY5sM3oqqeF2btjvg89sEikcu2ENp6_WkYukHv-rK9bXkJnjQzEAA"},{"domain":".google.com","expirationDate":1810004176.596988,"hostOnly":false,"httpOnly":false,"name":"__Secure-3PAPISID","path":"/","sameSite":"no_restriction","secure":true,"session":false,"storeId":"0","value":"RKAE4XyzMZZr--c3/ApMSGmeEyyluidacT"},{"domain":".google.com","expirationDate":1810004178.027635,"hostOnly":false,"httpOnly":true,"name":"__Secure-3PSID","path":"/","sameSite":"no_restriction","secure":true,"session":false,"storeId":"0","value":"g.a0008gjfoRUCh8czp2SA8zYvy8_k0q3MXwAQyIskpgpxVwMgBfxGzy5wKlZ9dJGaBXdYXNrubAACgYKAb8SARISFQHGX2MizkEuWnOQ_DyR4Yq4yqOpXRoVAUF8yKq44nPOXty74SXT-yAL01tN0076"},{"domain":".google.com","expirationDate":1807669271.634812,"hostOnly":false,"httpOnly":true,"name":"__Secure-3PSIDCC","path":"/","sameSite":"no_restriction","secure":true,"session":false,"storeId":"0","value":"AKEyXzXIty5jW9dLv2EDrc6AsG0HkcLMdvSGaFZQ6x-57t_6VmCQ_WqVtov5Hx6w1jkMeSQtAA"},{"domain":".google.com","expirationDate":1776133714.472247,"hostOnly":false,"httpOnly":true,"name":"__Secure-3PSIDRTS","path":"/","sameSite":"no_restriction","secure":true,"session":false,"storeId":"0","value":"sidts-CjcBWhotCa1sc7TQWyVgohYAHtIY5sM3oqqeF2btjvg89sEikcu2ENp6_WkYukHv-rK9bXkJnjQzEAA"},{"domain":".google.com","expirationDate":1807669114.472208,"hostOnly":false,"httpOnly":true,"name":"__Secure-3PSIDTS","path":"/","sameSite":"no_restriction","secure":true,"session":false,"storeId":"0","value":"sidts-CjcBWhotCa1sc7TQWyVgohYAHtIY5sM3oqqeF2btjvg89sEikcu2ENp6_WkYukHv-rK9bXkJnjQzEAA"},{"domain":".google.com","expirationDate":1791601596.595005,"hostOnly":false,"httpOnly":true,"name":"__Secure-BUCKET","path":"/","sameSite":"unspecified","secure":true,"session":false,"storeId":"0","value":"CKgE"},{"domain":".google.com","expirationDate":1776133543.032946,"hostOnly":false,"httpOnly":false,"name":"__Secure-STRP","path":"/","sameSite":"strict","secure":true,"session":false,"storeId":"0","value":"AEEP7gKD8HZS0mvpmM_px4hTpGIe1njIpiB8UMoazWXVQ2r10WI9ABUiqFWea_1RYtKpFBgoYdLNLP7k2gXkxfUgI32Op51rt350"}]';   // ← GANTI DENGAN COOKIE JSON MILIKMU

            $response = Http::timeout(45)->get("{$baseUrl}/api/ai/gemini", [
                'text'         => $prompt,
                'cookie'       => $cookieJson,
                'promptSystem' => 'Anda adalah seorang dokter spesialis yang berpengalaman dalam praktik klinis di Indonesia. Jawab dengan bahasa Indonesia yang formal, profesional, dan sesuai standar kedokteran. Jangan gunakan emoji atau bahasa kasual.',
            ]);

            \Log::info('Gemini BETA Response', [
                'status' => $response->status(),
                'body'   => substr($response->body(), 0, 800),
            ]);

            // Jika Gemini BETA gagal, coba GPT OSS 120B
            if (!$response->successful() || !($response->json()['status'] ?? false)) {
                \Log::warning('Gemini BETA gagal, mencoba GPT OSS 120B');

                $response = Http::timeout(40)->get("{$baseUrl}/api/ai/gptoss120b", [
                    'prompt'      => $prompt,
                    'system'      => 'You are a helpful assistant.',
                    'temperature' => 0.7,
                ]);

                \Log::info('GPT OSS 120B Fallback Response', ['status' => $response->status()]);
            }

            // Jika masih gagal, fallback ke Gemini Lite
            if (!$response->successful() || !($response->json()['status'] ?? false)) {
                \Log::warning('GPT OSS 120B gagal, fallback ke Gemini Lite');

                $response = Http::timeout(30)->get("{$baseUrl}/api/ai/gemini-lite", [
                    'model'  => 'gemini-2.0-flash-lite',
                    'prompt' => $prompt,
                ]);

                \Log::info('Gemini Lite Fallback Response', ['status' => $response->status()]);
            }

            // ==================== PROSES RESPONSE YANG BERHASIL ====================
            if ($response->successful()) {
                $result = $response->json();

                if (!($result['status'] ?? false)) {
                    throw new \Exception('AI API returned status false');
                }

                // Parsing response (support Gemini BETA, GPT OSS, dan Gemini Lite)
                $raw = $result['data'] ?? [];
                $analisisText = '';

                if (is_array($raw)) {
                    $analisisText = $raw['response'] ?? 
                                    ($raw['parts'][0]['text'] ?? 
                                    ($raw['text'] ?? json_encode($raw)));
                } else {
                    $analisisText = (string) $raw;
                }

                if (empty(trim($analisisText))) {
                    throw new \Exception('AI response kosong');
                }

                // Bersihkan teks
                $analisisText = str_replace(['**', '*'], '', $analisisText);
                $analisisText = preg_replace('/[\x{1F600}-\x{1F64F}\x{1F300}-\x{1F5FF}\x{1F680}-\x{1F6FF}\x{1F1E0}-\x{1F1FF}\x{2600}-\x{26FF}\x{2700}-\x{27BF}\x{FE00}-\x{FE0F}\x{1F900}-\x{1F9FF}\x{1FA00}-\x{1FA6F}\x{1FA70}-\x{1FAFF}\x{200D}\x{20E3}\x{E0020}-\x{E007F}]/u', '', $analisisText);

                $parsedAnalysis = $this->parseGeminiResponse($analisisText);

                // Simpan ke database
                AnalisisAi::create([
                    'pemeriksaan_kesehatan_id' => $pemeriksaan->id,
                    'pasien_id'                => $pemeriksaan->pasien_id,
                    'data_input'               => $dataInput,
                    'prompt_yang_dikirim'      => $prompt,
                    'penjelasan_kondisi'       => $parsedAnalysis['penjelasan_kondisi'] ?? $analisisText,
                    'saran_umum'               => $parsedAnalysis['saran_umum'] ?? null,
                    'kapan_harus_ke_dokter'    => $parsedAnalysis['kapan_ke_dokter'] ?? null,
                    'konsultasi_setelah_dokter' => $parsedAnalysis['konsultasi_setelah_dokter'] ?? null,
                    'solusi_dari_ai'           => $parsedAnalysis['solusi_dari_ai'] ?? null,
                    'gejala_yang_dianalisis'   => $dataInput['gejala_lain'] ?? [],
                    'tingkat_keparahan_ai'     => $parsedAnalysis['tingkat_keparahan'] ?? 'RINGAN',
                    'rekomendasi_ai'           => $parsedAnalysis['rekomendasi'] ?? 'ISTIRAHAT_CUKUP',
                    'raw_response'             => json_encode($result),
                    'model_ai'                 => 'gemini-beta',
                    'status_analisis'          => 'BERHASIL',
                    'waktu_analisis'           => now(),
                    'diminta_oleh'             => auth()->id() ?? 1,
                    'ip_address'               => request()->ip(),
                ]);

                $pemeriksaan->update(['analisis_ai_selesai' => true]);
                return true;

            } else {
                throw new \Exception('Semua endpoint AI gagal. HTTP: ' . $response->status());
            }

        } catch (\Exception $e) {
            \Log::error('requestAnalisisAI Error: ' . $e->getMessage(), [
                'pemeriksaan_id' => $pemeriksaan->id ?? null,
            ]);

            // Simpan record GAGAL (aman, tidak error SQL)
            AnalisisAi::create([
                'pemeriksaan_kesehatan_id' => $pemeriksaan->id,
                'pasien_id'                => $pemeriksaan->pasien_id,
                'data_input'               => $dataInput,
                'prompt_yang_dikirim'      => $prompt,
                'penjelasan_kondisi'       => 'Gagal mendapatkan analisis AI. Silakan coba beberapa saat lagi atau hubungi admin.',
                'saran_umum'               => null,
                'kapan_harus_ke_dokter'    => null,
                'konsultasi_setelah_dokter'=> null,
                'solusi_dari_ai'           => null,
                'gejala_yang_dianalisis'   => $dataInput['gejala_lain'] ?? [],
                'tingkat_keparahan_ai'     => 'RINGAN',
                'rekomendasi_ai'           => 'KONSULTASI_DOKTER',
                'raw_response'             => null,
                'model_ai'                 => 'gemini-beta',
                'status_analisis'          => 'GAGAL',
                'error_message'            => $e->getMessage(),
                'waktu_analisis'           => now(),
                'diminta_oleh'             => auth()->id() ?? 1,
                'ip_address'               => request()->ip(),
            ]);

            return false;
        }
    }
    private function buildStructuredPromptGemini($data)
    {
        $nama   = $data['nama_pasien'] ?? 'Pasien';
        $jk     = $data['jenis_kelamin'] == 'L' ? 'laki-laki' : 'perempuan';
        $sapaan = $data['jenis_kelamin'] == 'L' ? 'Tn.' : 'Ny.';

        $prompt  = "Anda adalah seorang dokter spesialis yang berpengalaman dalam praktik klinis di Indonesia. ";
        $prompt .= "Tulis laporan analisis medis resmi dengan bahasa Indonesia yang profesional, formal, dan sesuai standar kedokteran. ";
        $prompt .= "ATURAN KETAT yang WAJIB dipatuhi:\n";
        $prompt .= "- DILARANG menggunakan emoji, emotikon, atau simbol dekoratif apapun\n";
        $prompt .= "- DILARANG menggunakan bahasa kasual, slang, atau bahasa gaul\n";
        $prompt .= "- Gunakan terminologi medis yang tepat, sertakan penjelasan awam dalam tanda kurung jika diperlukan\n";
        $prompt .= "- Tulis seolah-olah Anda sedang menulis laporan medis resmi untuk pasien\n";
        $prompt .= "- Nada penulisan harus tenang, objektif, dan meyakinkan sebagai seorang dokter\n\n";

        $prompt .= "DATA KLINIS PASIEN:\n";
        $prompt .= "- Nama         : {$sapaan} {$nama}\n";
        $prompt .= "- Usia         : {$data['usia']} tahun ({$jk})\n";
        $prompt .= "- Suhu Tubuh   : {$data['suhu_tubuh']}°C (Kategori: {$data['kategori_suhu']})\n";

        if (!empty($data['detak_jantung']))    $prompt .= "- Frekuensi Nadi  : {$data['detak_jantung']} kali/menit\n";
        if (!empty($data['tekanan_darah']))    $prompt .= "- Tekanan Darah   : {$data['tekanan_darah']} mmHg\n";
        if (!empty($data['saturasi_oksigen'])) $prompt .= "- Saturasi Oksigen: {$data['saturasi_oksigen']}%\n";
        if (!empty($data['keluhan_utama']))    $prompt .= "- Keluhan Utama   : {$data['keluhan_utama']}\n";

        if (!empty($data['gejala_lain']) && is_array($data['gejala_lain'])) {
            $prompt .= "- Gejala Penyerta : " . implode(', ', $data['gejala_lain']) . "\n";
        }
        if (!empty($data['riwayat_penyakit'])) $prompt .= "- Riwayat Penyakit Terdahulu: {$data['riwayat_penyakit']}\n";
        if (!empty($data['alergi']))           $prompt .= "- Riwayat Alergi  : {$data['alergi']}\n";

        $prompt .= "\nSusun laporan analisis medis dengan format PERSIS berikut (gunakan pembatas === persis seperti contoh):\n\n";

        $prompt .= "=== PENJELASAN KONDISI ===\n";
        $prompt .= "Awali dengan menyebut nama pasien ({$sapaan} {$nama}). Jelaskan kondisi klinis pasien saat ini berdasarkan data pemeriksaan fisik dan keluhan yang disampaikan. Gunakan bahasa medis formal dalam 2-3 kalimat. Sertakan interpretasi klinis terhadap hasil pemeriksaan tanda vital.\n\n";

        $prompt .= "=== SOLUSI DAN PENANGANAN ===\n";
        $prompt .= "Berikan rekomendasi tatalaksana medis yang spesifik dan berbasis bukti, meliputi:\n";
        $prompt .= "1. Tatalaksana farmakologis: nama obat generik, dosis berdasarkan usia/berat badan, frekuensi pemberian, dan durasi pengobatan\n";
        $prompt .= "2. Tatalaksana non-farmakologis: terapi suportif seperti kompres, rehidrasi, tirah baring dengan durasi yang disarankan\n";
        $prompt .= "3. Kontraindikasi dan pantangan: makanan, aktivitas, atau obat-obatan yang harus dihindari beserta alasan medisnya\n\n";

        $prompt .= "=== SARAN PERAWATAN MANDIRI ===\n";
        $prompt .= "Berikan 3-5 instruksi perawatan mandiri di rumah yang dapat dilakukan oleh pasien atau keluarga pasien. Gunakan kalimat instruksi yang jelas dan terukur.\n\n";

        $prompt .= "=== KAPAN HARUS KE DOKTER ===\n";
        $prompt .= "Jelaskan tanda-tanda bahaya (warning signs) yang mengharuskan {$sapaan} {$nama} segera memeriksakan diri ke fasilitas kesehatan atau Instalasi Gawat Darurat (IGD). Sebutkan secara spesifik gejala dan parameter klinis yang perlu diwaspadai.\n\n";

        $prompt .= "=== KONSULTASI SETELAH DARI DOKTER ===\n";
        $prompt .= "Jelaskan panduan tindak lanjut pasca-konsultasi medis, meliputi:\n";
        $prompt .= "1. Jadwal kontrol ulang yang disarankan\n";
        $prompt .= "2. Parameter klinis yang perlu dipantau dan dilaporkan pada kunjungan berikutnya\n";
        $prompt .= "3. Hal-hal yang perlu dipersiapkan atau dicatat sebelum kunjungan kontrol\n\n";

        $prompt .= "=== SOLUSI DARI AI ===\n";
        $prompt .= "Tulis ringkasan komprehensif berupa kesimpulan analisis dan rekomendasi utama dalam 2-3 kalimat. Ringkasan ini harus mencakup penilaian kondisi, prioritas tindakan, dan prognosis umum.\n\n";

        $prompt .= "=== TINGKAT KEPARAHAN ===\n";
        $prompt .= "Tulis SATU KATA saja: NORMAL atau RINGAN atau SEDANG atau BERAT atau SANGAT_BERAT\n\n";

        $prompt .= "=== REKOMENDASI TINDAKAN ===\n";
        $prompt .= "Tulis SATU KATA saja: ISTIRAHAT_CUKUP atau MINUM_OBAT_BEBAS atau KONSULTASI_DOKTER atau PERIKSA_SEGERA atau IGD_DARURAT\n";

        return $prompt;
    }
       /**
     * Parse response dari Gemini (lanjutan)
     */
    private function parseGeminiResponse($text)
    {
        $parsed = [
            'penjelasan_kondisi'        => '',
            'saran_umum'                => '',
            'kapan_ke_dokter'           => '',
            'konsultasi_setelah_dokter' => '',
            'solusi_dari_ai'            => '',
            'tingkat_keparahan'         => 'RINGAN',
            'rekomendasi'               => 'ISTIRAHAT_CUKUP',
        ];

        // Extract sections
        $penjelasan = '';
        if (preg_match('/=== PENJELASAN KONDISI ===\s*(.*?)\s*===/s', $text, $matches)) {
            $penjelasan = trim($matches[1]);
        }
        $solusi = '';
        if (preg_match('/=== SOLUSI DAN PENANGANAN ===\s*(.*?)\s*===/s', $text, $matches)) {
            $solusi = trim($matches[1]);
        }
        if ($penjelasan && $solusi) {
            $parsed['penjelasan_kondisi'] = $penjelasan . "\n\nSolusi dan Penanganan:\n" . $solusi;
        } elseif ($solusi) {
            $parsed['penjelasan_kondisi'] = $solusi;
        } else {
            $parsed['penjelasan_kondisi'] = $penjelasan;
        }

        if (preg_match('/=== SARAN PERAWATAN MANDIRI ===\s*(.*?)\s*===/s', $text, $matches)) {
            $parsed['saran_umum'] = trim($matches[1]);
        }

        if (preg_match('/=== KAPAN HARUS KE DOKTER ===\s*(.*?)\s*===/s', $text, $matches)) {
            $parsed['kapan_ke_dokter'] = trim($matches[1]);
        }

        if (preg_match('/=== KONSULTASI SETELAH DARI DOKTER ===\s*(.*?)\s*===/s', $text, $matches)) {
            $parsed['konsultasi_setelah_dokter'] = trim($matches[1]);
        }

        if (preg_match('/=== SOLUSI DARI AI ===\s*(.*?)\s*===/s', $text, $matches)) {
            $parsed['solusi_dari_ai'] = trim($matches[1]);
        }

        if (preg_match('/=== TINGKAT KEPARAHAN ===\s*(.*?)\s*===/s', $text, $matches)) {
            $severity = strtoupper(trim($matches[1]));
            $validSeverities = ['NORMAL', 'RINGAN', 'SEDANG', 'BERAT', 'SANGAT_BERAT'];
            if (in_array($severity, $validSeverities)) {
                $parsed['tingkat_keparahan'] = $severity;
            }
        }

        if (preg_match('/=== REKOMENDASI TINDAKAN ===\s*(.*?)\s*($|===)/s', $text, $matches)) {
            $recommendation = strtoupper(trim($matches[1]));
            $validRecommendations = ['ISTIRAHAT_CUKUP', 'MINUM_OBAT_BEBAS', 'KONSULTASI_DOKTER', 'PERIKSA_SEGERA', 'IGD_DARURAT'];
            if (in_array($recommendation, $validRecommendations)) {
                $parsed['rekomendasi'] = $recommendation;
            }
        }

        return $parsed;
    }

    /**
     * Send WhatsApp notification using Fonnte
     */
    private function sendNotifikasi($pemeriksaan, $template)
    {
        try {
            $pasien = $pemeriksaan->pasien;

            if (!$pasien->no_wa) {
                return false;
            }

            $pesan = $this->buildPesanNotifikasi($pemeriksaan, $template);

            // Kirim via Fonnte API
            $response = Http::withHeaders([
                'Authorization' => env('FONNTE_API_KEY'),
            ])->post('https://api.fonnte.com/send', [
                'target' => $pasien->no_wa,
                'message' => $pesan,
                'countryCode' => '62', // Indonesia
            ]);

            $result = $response->json();

            // Simpan log notifikasi
            LogNotifikasi::create([
                'pemeriksaan_kesehatan_id' => $pemeriksaan->id,
                'pasien_id' => $pasien->id,
                'jenis_notifikasi' => 'WHATSAPP',
                'nomor_tujuan' => $pasien->no_wa,
                'judul_pesan' => 'Hasil Pemeriksaan Kesehatan',
                'isi_pesan' => $pesan,
                'template_digunakan' => $template,
                'status_pengiriman' => $response->successful() ? 'TERKIRIM' : 'GAGAL',
                'waktu_dikirim' => now(),
                'message_id' => $result['id'] ?? null,
                'provider' => 'Fonnte',
                'response_provider' => $result,
                'prioritas' => $template === 'DEMAM_TINGGI' ? 'TINGGI' : 'NORMAL',
                'kategori' => 'PERINGATAN',
                'dikirim_oleh' => auth()->id(),
                'ip_address' => request()->ip(),
                'otomatis' => true,
            ]);

            return $response->successful();

        } catch (\Exception $e) {
            \Log::error('Gagal kirim notifikasi: ' . $e->getMessage());
            
            // Simpan log error
            LogNotifikasi::create([
                'pemeriksaan_kesehatan_id' => $pemeriksaan->id,
                'pasien_id' => $pasien->id,
                'jenis_notifikasi' => 'WHATSAPP',
                'nomor_tujuan' => $pasien->no_wa,
                'judul_pesan' => 'Hasil Pemeriksaan Kesehatan',
                'isi_pesan' => $pesan ?? '',
                'template_digunakan' => $template,
                'status_pengiriman' => 'GAGAL',
                'pesan_error' => $e->getMessage(),
                'prioritas' => $template === 'DEMAM_TINGGI' ? 'TINGGI' : 'NORMAL',
                'kategori' => 'PERINGATAN',
                'dikirim_oleh' => auth()->id(),
                'otomatis' => true,
            ]);

            return false;
        }
    }

    /**
     * Build message untuk notifikasi
     */
    private function buildPesanNotifikasi($pemeriksaan, $template)
    {
        $pasien = $pemeriksaan->pasien;

        $pesan = "🏥 *Hasil Pemeriksaan Kesehatan*\n\n";
        $pesan .= "Yth. {$pasien->nama_lengkap}\n\n";
        $pesan .= "Hasil pemeriksaan Anda:\n";
        $pesan .= "📅 Waktu: " . $pemeriksaan->waktu_pemeriksaan->format('d/m/Y H:i') . "\n";
        $pesan .= "🌡️ Suhu: {$pemeriksaan->suhu_tubuh}°C ({$pemeriksaan->kategori_suhu})\n";

        if ($template === 'DEMAM_TINGGI') {
            $pesan .= "\n⚠️ *PERHATIAN*\n";
            $pesan .= "Suhu tubuh Anda terdeteksi tinggi.\n";
            $pesan .= "Segera hubungi dokter atau datang ke fasilitas kesehatan terdekat.\n";
        }

        $pesan .= "\nKode Pemeriksaan: {$pemeriksaan->kode_pemeriksaan}\n";

        return $pesan;
    }
}