<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Pasien;
use App\Models\RiwayatPenghapusanPasien;
use App\Models\EmbeddingWajah;
use App\Models\Dokter;
use App\Models\Province;
use App\Models\Regency;
use App\Models\District;
use App\Models\Village;
use App\Models\DokterPasien;
use App\Models\LogNotifikasi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Notification;
use App\Models\User;
use App\Notifications\PemeriksaanSelesai;

class PasienController extends Controller
{
    // Golongan darah list
    private $golonganDarahList = [
        'A' => 'A', 'B' => 'B', 'AB' => 'AB', 'O' => 'O',
        'A+' => 'A+', 'A-' => 'A-', 'B+' => 'B+', 'B-' => 'B-',
        'AB+' => 'AB+', 'AB-' => 'AB-', 'O+' => 'O+', 'O-' => 'O-',
        'TIDAK_TAHU' => 'Tidak Tahu'
    ];

    /**
     * Display a listing of pasien - MODIFIKASI untuk return view
     */
    public function index(Request $request)
    {
        // Jika request dari DataTables (ajax), return JSON
        if ($request->ajax()) {
            return $this->datatables($request);
        }

        // Untuk web, kembalikan view
        return view('petugas.pasien.index', [
            'golonganDarahList' => $this->golonganDarahList,
        ]);
    }

    /**
     * DataTables endpoint dengan formatted data - DIPERBAIKI
     */
    public function datatables(Request $request)
    {
        try {
            $query = Pasien::query();

            // Hitung total records (tanpa filter)
            $recordsTotal = Pasien::count();

            // PERBAIKAN: Filter by status - gunakan filled() untuk cek apakah value tidak kosong
            if ($request->filled('status_pasien')) {
                $query->where('status_pasien', $request->status_pasien);
            }

            // PERBAIKAN: Filter wajah terdaftar - gunakan filled() untuk cek apakah value tidak kosong
            if ($request->filled('wajah_terdaftar')) {
                // Convert string ke boolean untuk filter yang benar
                $wajahValue = filter_var($request->wajah_terdaftar, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
                if ($wajahValue !== null) {
                    $query->where('wajah_terdaftar', $wajahValue);
                }
            }

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

            // PERBAIKAN: Hitung total records setelah filter SEBELUM skip/take
            // Ini sangat penting untuk pagination yang benar
            $recordsFiltered = $query->count();

            // Order by
            if ($request->has('order')) {
                $orderColumn = $request->order[0]['column'];
                $orderDir = $request->order[0]['dir'];
                
                // Mapping kolom index ke nama kolom
                $columns = [
                    'no_rekam_medis',
                    'nama_lengkap', 
                    'jenis_kelamin',
                    'tanggal_lahir', // Untuk sorting usia
                    'no_telepon',
                    'wajah_terdaftar'
                ];

                if (isset($columns[$orderColumn])) {
                    $orderBy = $columns[$orderColumn];
                    $query->orderBy($orderBy, $orderDir);
                }
            } else {
                $query->orderBy('created_at', 'desc');
            }

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

            // Ambil data
            $pasienList = $query->get();

            // Format data untuk DataTables
            $data = $pasienList->map(function ($item) {
                $usia = null;
                if ($item->tanggal_lahir) {
                    $tglLahir = Carbon::parse($item->tanggal_lahir);
                    $usia = $tglLahir->isPast() ? $tglLahir->age : 0;
                }

                // Format No. Rekam Medis
                $no_rekam_medis_formatted = '<span class="px-2 py-1 bg-gray-100 dark:bg-slate-700 rounded font-mono text-sm">' 
                    . e($item->no_rekam_medis) 
                    . '</span>';

                // Format Jenis Kelamin
                $jk_icon = $item->jenis_kelamin === 'L' 
                    ? '<i class="fas fa-mars text-blue-500 mr-1"></i>' 
                    : '<i class="fas fa-venus text-pink-500 mr-1"></i>';
                $jk_text = $item->jenis_kelamin === 'L' ? 'Laki-laki' : 'Perempuan';
                $jenis_kelamin_formatted = $jk_icon . $jk_text;

                // Format Usia
                $usia_formatted = $usia ? $usia . ' tahun' : '-';

                // Format Wajah Terdaftar
                if ($item->wajah_terdaftar) {
                    $wajah_terdaftar_formatted = '<span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">'
                        . '<i class="fas fa-check-circle mr-1"></i> Terdaftar'
                        . '</span>';
                } else {
                    $wajah_terdaftar_formatted = '<span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200">'
                        . '<i class="fas fa-exclamation-circle mr-1"></i> Belum'
                        . '</span>';
                }

                // Format Aksi Buttons
                $showUrl = route('petugas.pasien.show', $item->id);
                $editUrl = route('petugas.pasien.edit', $item->id);
                $assignUrl = route('petugas.pasien.assign', $item->id);
                $registerFaceUrl = route('petugas.pasien.register-face', $item->id);

                $aksi = '
                    <div class="flex items-center justify-center space-x-2">
                        <a href="' . $showUrl . '" 
                           class="action-btn inline-flex items-center px-3 py-1.5 bg-teal-500 hover:bg-teal-600 text-white rounded-lg transition transform hover:-translate-y-1"
                           data-bs-toggle="tooltip" 
                           title="Lihat Detail">
                            <i class="fas fa-eye"></i>
                        </a>
                        <a href="' . $editUrl . '" 
                           class="action-btn inline-flex items-center px-3 py-1.5 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition transform hover:-translate-y-1"
                           data-bs-toggle="tooltip" 
                           title="Edit Data">
                            <i class="fas fa-edit"></i>
                        </a>';
                
                if (!$item->wajah_terdaftar) {
                    $aksi .= '
                        <a href="' . $registerFaceUrl . '" 
                           class="action-btn inline-flex items-center px-3 py-1.5 bg-purple-500 hover:bg-purple-600 text-white rounded-lg transition transform hover:-translate-y-1"
                           data-bs-toggle="tooltip" 
                           title="Daftar Wajah">
                            <i class="fas fa-camera"></i>
                        </a>';
                }
                
                $aksi .= '
                        <a href="' . $assignUrl . '" 
                           class="action-btn inline-flex items-center px-3 py-1.5 bg-green-500 hover:bg-green-600 text-white rounded-lg transition transform hover:-translate-y-1"
                           data-bs-toggle="tooltip" 
                           title="Assign Dokter">
                            <i class="fas fa-user-md"></i>
                        </a>
                        <button onclick="confirmDelete(' . $item->id . ', \'' . addslashes($item->nama_lengkap) . '\', \'' . addslashes($item->no_rekam_medis) . '\')" 
                                class="action-btn inline-flex items-center px-3 py-1.5 bg-red-500 hover:bg-red-600 text-white rounded-lg transition transform hover:-translate-y-1"
                                data-bs-toggle="tooltip" 
                                title="Hapus">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                ';

                return [
                    'no_rekam_medis' => $item->no_rekam_medis,
                    'no_rekam_medis_formatted' => $no_rekam_medis_formatted,
                    'nama_lengkap' => $item->nama_lengkap,
                    'jenis_kelamin' => $item->jenis_kelamin,
                    'jenis_kelamin_formatted' => $jenis_kelamin_formatted,
                    'tanggal_lahir' => $item->tanggal_lahir,
                    'usia' => $usia,
                    'usia_formatted' => $usia_formatted,
                    'no_telepon' => $item->no_telepon ?? '-',
                    'wajah_terdaftar' => $item->wajah_terdaftar,
                    'wajah_terdaftar_formatted' => $wajah_terdaftar_formatted,
                    'aksi' => $aksi,
                ];
            });

            // Statistik untuk quick cards
            $stats = [
                'wajah_terdaftar' => Pasien::where('wajah_terdaftar', true)->count(),
                'pasien_aktif' => Pasien::where('status_pasien', 'AKTIF')->count(),
                'wajah_belum' => Pasien::where('wajah_terdaftar', false)->count(),
            ];

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

        } catch (\Exception $e) {
            \Log::error('DataTables Error: ' . $e->getMessage());
            \Log::error($e->getTraceAsString());
            
            return response()->json([
                'draw' => intval($request->draw ?? 0),
                'recordsTotal' => 0,
                'recordsFiltered' => 0,
                'data' => [],
                'error' => $e->getMessage()
            ], 500);
        }
    }
/**
 * Get provinces for dropdown
 */
public function getProvinces()
{
    $provinces = Province::orderBy('name')->get();
    return response()->json($provinces);
}

/**
 * Get regencies by province
 */
public function getRegencies($province_id)
{
    $regencies = Regency::where('province_id', $province_id)->orderBy('name')->get();
    return response()->json($regencies);
}

/**
 * Get districts by regency
 */
public function getDistricts($regency_id)
{
    $districts = District::where('regency_id', $regency_id)->orderBy('name')->get();
    return response()->json($districts);
}

/**
 * Get villages by district
 */
public function getVillages($district_id)
{
    $villages = Village::where('district_id', $district_id)->orderBy('name')->get();
    return response()->json($villages);
}
   /**
 * Show create form
 */
/**
 * Show create form - DIPERBAIKI
 */
public function create()
{
    $provinces = Province::orderBy('name')->get();
    
    return view('petugas.pasien.create', [
        'provinces' => $provinces,
        'golonganDarahList' => $this->golonganDarahList,
    ]);
}

    /**
     * Store new pasien
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nik'              => 'nullable|string|size:16|unique:pasien,nik',
            'nama_lengkap'     => 'required|string|max:100',
            'jenis_kelamin'    => 'required|in:L,P',
            // before_or_equal agar tanggal hari ini juga boleh
            'tanggal_lahir'    => 'required|date|before_or_equal:today',
            'tempat_lahir'     => 'nullable|string|max:50',
            'alamat_lengkap'   => 'nullable|string',
            // Hapus exists: agar tidak gagal karena perbedaan tipe char vs string
            'province_id'      => 'nullable|string|max:4',
            'regency_id'       => 'nullable|string|max:5',
            'district_id'      => 'nullable|string|max:8',
            'village_id'       => 'nullable|string|max:11',
            'kode_pos'         => 'nullable|string|max:10',
            'no_telepon'       => 'nullable|string|max:20',
            'no_wa'            => 'nullable|string|max:20',
            'email'            => 'nullable|email|max:100|unique:pasien,email',
            'golongan_darah'   => 'nullable|in:A,B,AB,O,A+,A-,B+,B-,AB+,AB-,O+,O-,TIDAK_TAHU',
            'tinggi_badan'     => 'nullable|numeric|min:1|max:300',
            'berat_badan'      => 'nullable|numeric|min:1|max:500',
            'riwayat_penyakit' => 'nullable|string',
            'alergi'           => 'nullable|string',
            'catatan_khusus'   => 'nullable|string',
            'foto_profil'      => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
        ]);

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

        try {
            DB::beginTransaction();

            $id_eksternal   = 'PSN-' . strtoupper(Str::random(10));
            $no_rekam_medis = 'RM' . now()->format('Ymd') . str_pad(Pasien::count() + 1, 4, '0', STR_PAD_LEFT);

            $fotoPath = null;
            if ($request->hasFile('foto_profil')) {
                $fotoPath = $request->file('foto_profil')->store('pasien/foto', 'public');
            }

            $usia = null;
            if ($request->tanggal_lahir) {
                $tglLahir = Carbon::createFromFormat('Y-m-d', $request->tanggal_lahir);
                $usia = ($tglLahir && $tglLahir->isPast()) ? $tglLahir->age : 0;
            }

            // Hanya ambil kolom yang ada di tabel pasien
            $data = $request->only([
                'nik', 'nama_lengkap', 'jenis_kelamin', 'tanggal_lahir',
                'tempat_lahir', 'golongan_darah', 'alamat_lengkap',
                'province_id', 'regency_id', 'district_id', 'village_id',
                'kode_pos', 'no_telepon', 'no_wa', 'email',
                'tinggi_badan', 'berat_badan', 'riwayat_penyakit',
                'alergi', 'catatan_khusus',
            ]);

            // Cast wilayah ke string (char)
            foreach (['province_id', 'regency_id', 'district_id', 'village_id'] as $col) {
                if (isset($data[$col]) && $data[$col] !== '') {
                    $data[$col] = (string) $data[$col];
                } else {
                    $data[$col] = null;
                }
            }

            $data['id_eksternal']     = $id_eksternal;
            $data['no_rekam_medis']   = $no_rekam_medis;
            $data['usia']             = $usia;
            $data['foto_profil']      = $fotoPath;
            $data['didaftarkan_oleh'] = auth()->id();
            $data['status_pasien']    = 'AKTIF';
            $data['wajah_terdaftar']  = false;

            $pasien = Pasien::create($data);

            DB::commit();

            return redirect()->route('petugas.pasien.show', $pasien->id)
                ->with('success', 'Pasien ' . $pasien->nama_lengkap . ' berhasil didaftarkan. No. RM: ' . $no_rekam_medis);

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Store Pasien Error: ' . $e->getMessage() . ' | ' . $e->getTraceAsString());

            return redirect()->back()
                ->withInput()
                ->with('error', 'Gagal mendaftarkan pasien: ' . $e->getMessage());
        }
    }
    /**
 * Show edit form
 */

/**
 * Show edit form - DIPERBAIKI
 */
public function edit($id)
{
    $pasien = Pasien::with(['province', 'regency', 'district', 'village'])->findOrFail($id);
    $provinces = Province::orderBy('name')->get();
    
    return view('petugas.pasien.edit', [
        'pasien' => $pasien,
        'provinces' => $provinces,
        'golonganDarahList' => $this->golonganDarahList,
    ]);
}

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

        $validator = Validator::make($request->all(), [
            // NIK: nullable, 16 digit, unik kecuali milik pasien ini sendiri
            'nik'              => 'nullable|string|size:16|unique:pasien,nik,' . $id,
            'nama_lengkap'     => 'required|string|max:100',
            'jenis_kelamin'    => 'required|in:L,P',
            // before_or_equal agar tanggal lama (bahkan hari ini) tidak ditolak
            'tanggal_lahir'    => 'required|date|before_or_equal:today',
            'tempat_lahir'     => 'nullable|string|max:50',
            'alamat_lengkap'   => 'nullable|string',
            // wilayah: hapus validasi exists agar tidak gagal karena tipe char vs string
            'province_id'      => 'nullable|string|max:4',
            'regency_id'       => 'nullable|string|max:5',
            'district_id'      => 'nullable|string|max:8',
            'village_id'       => 'nullable|string|max:11',
            'kode_pos'         => 'nullable|string|max:10',
            'no_telepon'       => 'nullable|string|max:20',
            'no_wa'            => 'nullable|string|max:20',
            'email'            => 'nullable|email|max:100|unique:pasien,email,' . $id,
            'golongan_darah'   => 'nullable|in:A,B,AB,O,A+,A-,B+,B-,AB+,AB-,O+,O-,TIDAK_TAHU',
            'tinggi_badan'     => 'nullable|numeric|min:1|max:300',
            'berat_badan'      => 'nullable|numeric|min:1|max:500',
            'riwayat_penyakit' => 'nullable|string',
            'alergi'           => 'nullable|string',
            'catatan_khusus'   => 'nullable|string',
            'status_pasien'    => 'nullable|in:AKTIF,NONAKTIF,MENINGGAL',
            'foto_profil'      => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
        ]);

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

        try {
            // Handle upload foto profil baru
            if ($request->hasFile('foto_profil')) {
                if ($pasien->foto_profil) {
                    Storage::disk('public')->delete($pasien->foto_profil);
                }
                $fotoPath = $request->file('foto_profil')->store('pasien/foto', 'public');
                $pasien->foto_profil = $fotoPath;
                $pasien->save(); // simpan foto dulu
            }

            // Hitung usia otomatis dari tanggal lahir
            $usia = $pasien->usia;
            if ($request->tanggal_lahir) {
                $tglLahir = Carbon::createFromFormat('Y-m-d', $request->tanggal_lahir);
                $usia = ($tglLahir && $tglLahir->isPast()) ? $tglLahir->age : 0;
            }

            // Ambil hanya kolom yang ada di tabel pasien (sesuai migration)
            $data = $request->only([
                'nik', 'nama_lengkap', 'jenis_kelamin', 'tanggal_lahir',
                'tempat_lahir', 'golongan_darah', 'alamat_lengkap',
                'province_id', 'regency_id', 'district_id', 'village_id',
                'kode_pos', 'no_telepon', 'no_wa', 'email',
                'tinggi_badan', 'berat_badan', 'riwayat_penyakit',
                'alergi', 'catatan_khusus', 'status_pasien',
            ]);

            $data['usia'] = $usia;

            // Pastikan province_id/regency_id/district_id/village_id
            // tersimpan sebagai string (char) agar cocok dengan kolom DB
            foreach (['province_id', 'regency_id', 'district_id', 'village_id'] as $col) {
                if (isset($data[$col]) && $data[$col] !== '') {
                    $data[$col] = (string) $data[$col];
                } else {
                    $data[$col] = null;
                }
            }

            $pasien->update($data);

            return redirect()->route('petugas.pasien.show', $pasien->id)
                ->with('success', 'Data pasien ' . $pasien->nama_lengkap . ' berhasil diperbarui.');

        } catch (\Exception $e) {
            \Log::error('Update Pasien Error: ' . $e->getMessage() . ' | ' . $e->getTraceAsString());
            return redirect()->back()
                ->withInput()
                ->with('error', 'Gagal memperbarui pasien: ' . $e->getMessage());
        }
    }

    /**
     * Delete pasien dengan 2 pilihan: Soft Delete (ke Riwayat) atau Hard Delete (Permanen)
     * 
     * Request body:
     * {
     *   "deletion_type": "soft" | "hard",
     *   "alasan": "Alasan penghapusan (optional)",
     *   "password": "password (required untuk hard delete)"
     * }
     */
    public function destroy($id, Request $request)
    {
        try {
            $pasien = Pasien::findOrFail($id);
            $currentUser = auth()->user();
            $deletionType = $request->input('deletion_type', 'soft');
            $alasan = $request->input('alasan', '');

            // ===== VALIDATION PHASE =====
            
            // Cek apakah pasien bisa dihapus
            [$canDelete, $errorMessage] = $pasien->canBeDeleted();
            if (!$canDelete) {
                return response()->json([
                    'success' => false,
                    'message' => $errorMessage,
                    'type' => 'validation_error',
                ], 422);
            }

            // Jika hard delete, require password confirmation
            if ($deletionType === 'hard') {
                $password = $request->input('password', '');
                if (!$password || !password_verify($password, $currentUser->password)) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Password incorrect. Hard delete memerlukan konfirmasi password.',
                        'type' => 'password_error',
                    ], 403);
                }
            }

            // ===== DELETION PHASE =====

            if ($deletionType === 'soft') {
                // SOFT DELETE - simpan ke riwayat, kemudian soft delete
                DB::beginTransaction();
                try {
                    // 1. Simpan ke riwayat_penghapusan_pasien
                    $riwayat = $pasien->saveToRiwayat(
                        userId: $currentUser->id,
                        alasan: $alasan,
                        tipePenghapusan: 'SOFT_DELETE'
                    );

                    // 2. Soft delete pasien
                    $pasien->delete();

                    // 3. Log aktivitas
                    $this->logAktivitas($currentUser, 'DELETE', 'PASIEN', $pasien->id, [
                        'id' => $pasien->id,
                        'nama' => $pasien->nama_lengkap,
                        'no_rekam_medis' => $pasien->no_rekam_medis,
                    ], null, 'SOFT_DELETE', 'Pasien soft deleted ke riwayat');

                    DB::commit();

                    return response()->json([
                        'success' => true,
                        'message' => 'Pasien berhasil dihapus dan disimpan ke Riwayat Penghapusan.',
                        'riwayat_id' => $riwayat->id,
                        'type' => 'soft_delete_success',
                    ]);

                } catch (\Exception $e) {
                    DB::rollBack();
                    throw $e;
                }

            } elseif ($deletionType === 'hard') {
                // HARD DELETE - penghapusan permanen
                DB::beginTransaction();
                try {
                    // 1. Cek apakah sudah ada di riwayat (soft delete dulu)
                    $riwayatExisting = RiwayatPenghapusanPasien::where('pasien_id', $pasien->id)
                        ->where('status_pemulihan', '!=', 'SUDAH_DI_RESTORE')
                        ->first();

                    if (!$riwayatExisting) {
                        // Belum ada di riwayat, buat dulu
                        $riwayat = $pasien->saveToRiwayat(
                            userId: $currentUser->id,
                            alasan: $alasan,
                            tipePenghapusan: 'HARD_DELETE'
                        );
                    } else {
                        $riwayat = $riwayatExisting;
                        // Update status menjadi TIDAK_REVERSIBLE
                        $riwayat->update([
                            'tipe_penghapusan' => 'HARD_DELETE',
                            'status_pemulihan' => 'TIDAK_REVERSIBLE',
                        ]);
                    }

                    // 2. Cascade delete semua data terkait (saat pasien hard delete)
                    // Note: yang sudah soft delete akan ikut terhapus
                    $pasien->pemeriksaanKesehatan()->forceDelete();
                    $pasien->embeddingWajah()->forceDelete();
                    $pasien->analisisAi()->forceDelete();
                    $pasien->logNotifikasi()->forceDelete();
                    $pasien->dokterPasien()->forceDelete();

                    // 3. Hard delete pasien itu sendiri
                    $dataPasienSnapshot = [
                        'id' => $pasien->id,
                        'nama' => $pasien->nama_lengkap,
                        'no_rekam_medis' => $pasien->no_rekam_medis,
                    ];
                    $pasien->forceDelete();

                    // 4. Log aktivitas
                    $this->logAktivitas($currentUser, 'DELETE', 'PASIEN', $pasien->id, $dataPasienSnapshot, null, 'HARD_DELETE', 'Pasien hard deleted permanently');

                    DB::commit();

                    return response()->json([
                        'success' => true,
                        'message' => 'Pasien dan semua data terkait berhasil dihapus secara permanen.',
                        'type' => 'hard_delete_success',
                    ]);

                } catch (\Exception $e) {
                    DB::rollBack();
                    throw $e;
                }

            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Tipe penghapusan tidak valid. Gunakan "soft" atau "hard".',
                ], 422);
            }

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal menghapus pasien: ' . $e->getMessage(),
                'error_detail' => env('APP_DEBUG') ? $e->getTraceAsString() : null,
            ], 500);
        }
    }

    /**
     * Helper method: Log aktivitas ke log_aktivitas_sistem
     */
    private function logAktivitas($user, $jenis_aktivitas, $modul, $model_id, $data_lama, $data_baru, $aksi, $deskripsi)
    {
        try {
            LogNotifikasi::where('id', '!=', 0) // Hack untuk akses class LogAktivitasSistem dari LogNotifikasi
                ->firstOrFail(); // This won't execute, but we need the class reference

            // Gunakan DB query langsung untuk log_aktivitas_sistem
            DB::table('log_aktivitas_sistem')->insert([
                'user_id' => $user->id,
                'jenis_aktivitas' => $jenis_aktivitas,
                'modul' => $modul,
                'aksi' => $aksi ?? 'DELETE',
                'deskripsi' => $deskripsi,
                'model_type' => 'Pasien',
                'model_id' => $model_id,
                'data_lama' => json_encode($data_lama),
                'data_baru' => json_encode($data_baru),
                'ip_address' => request()->ip(),
                'user_agent' => request()->userAgent(),
                'method' => request()->method(),
                'url' => request()->url(),
                'status' => 'BERHASIL',
                'waktu_aktivitas' => now(),
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        } catch (\Exception $e) {
            // Jika logging gagal, jangan throw exception
            // Hanya log ke error_log
            \Log::error('Failed to log aktivitas: ' . $e->getMessage());
        }
    }

    /**
     * Show assign form
     */
    public function assignForm($id)
    {
        $pasien = Pasien::findOrFail($id);
        $dokters = Dokter::where('status_dokter', 'AKTIF')->get();
        
        $existing = DokterPasien::with('dokter')
            ->where('pasien_id', $id)
            ->whereNotIn('status_konsultasi', ['SELESAI_KONSUL', 'LUNAS', 'BATAL'])
            ->first();

        return view('petugas.pasien.assign', compact('pasien', 'dokters', 'existing'));
    }

    /**
     * Assign pasien to dokter
     */
    public function assignToDokter(Request $request, $id)
    {
        $request->validate([
            'dokter_id'       => 'required|exists:dokter,id',
            'diagnosis_utama' => 'nullable|string',
        ]);

        $existing = DokterPasien::where('pasien_id', $id)
            ->whereNotIn('status_konsultasi', ['SELESAI_KONSUL', 'LUNAS', 'BATAL'])
            ->first();

        try {
            if ($existing) {
                // Update / Pindah dokter
                $existing->update([
                    'dokter_id' => $request->dokter_id,
                    'diagnosis_utama' => $request->diagnosis_utama ?? $existing->diagnosis_utama,
                ]);

                try {
                    $dokterUser = User::find($existing->dokter->user_id);
                    if ($dokterUser) {
                        $dokterUser->notify(new PemeriksaanSelesai($existing->pasien, $existing->pemeriksaan_id ?? $existing->id));
                    }
                } catch (\Exception $e) {
                    \Log::error('Notifikasi Gagal Dikirim ke Dokter: ' . $e->getMessage());
                }

                return redirect()->route('petugas.pasien.show', $id)
                    ->with('success', 'Pasien berhasil dipindahkan ke dokter lain');
            } else {
                $konsultasiBaru = DokterPasien::create([
                    'dokter_id'               => $request->dokter_id,
                    'pasien_id'               => $id,
                    'status_konsultasi'       => 'MENUNGGU',
                    'diagnosis_utama'         => $request->diagnosis_utama,
                    'tanggal_mulai_menangani' => now(),
                    'didaftarkan_oleh'        => auth()->id(),
                ]);

                try {
                    $dokterUser = User::find($konsultasiBaru->dokter->user_id);
                    if ($dokterUser) {
                        $dokterUser->notify(new PemeriksaanSelesai($konsultasiBaru->pasien, $konsultasiBaru->pemeriksaan_id ?? $id));
                    }
                } catch (\Exception $e) {
                    \Log::error('Notifikasi Gagal Dikirim ke Dokter: ' . $e->getMessage());
                }

                return redirect()->route('petugas.pasien.show', $id)
                    ->with('success', 'Pasien berhasil diassign ke dokter');
            }

        } catch (\Exception $e) {
        return redirect()->back()
            ->with('error', 'ERROR: ' . $e->getMessage());
    }
}
    /**
     * Show single pasien
     */
    public function show($id)
    {
        $pasien = Pasien::with([
            'dokterAktif',
            'embeddingWajahAktif',
            'pemeriksaanTerbaru',
            'dokterPasien' => function ($query) {
                $query->latest()->limit(5);
            },
        ])->findOrFail($id);

        // Statistik
        $stats = [
            'total_pemeriksaan' => $pasien->pemeriksaanKesehatan()->count(),
            'total_demam' => $pasien->pemeriksaanKesehatan()->whereIn('kategori_suhu', ['DEMAM_RINGAN', 'DEMAM_SEDANG', 'DEMAM_TINGGI'])->count(),
            'pemeriksaan_bulan_ini' => $pasien->pemeriksaanKesehatan()
                ->whereMonth('waktu_pemeriksaan', now()->month)
                ->count(),
        ];

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

    /**
     * Get riwayat pemeriksaan
     */
    public function riwayatPemeriksaan($id, Request $request)
    {
        $pasien = Pasien::findOrFail($id);

        $query = $pasien->pemeriksaanKesehatan()->with(['petugas', 'dokter', 'analisisAi']);

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

        $query->orderBy('waktu_pemeriksaan', 'desc');

        $riwayat = $query->paginate($request->per_page ?? 10);

        return view('petugas.pasien.riwayat', compact('pasien', 'riwayat'));
    }

    /**
     * Register face embedding
     */
    public function registerFace(Request $request, $id)
    {
        // Redirect ke FaceRecognitionController
        return app(FaceRecognitionController::class)->registerFace($request);
    }
}