<?php

namespace App\Http\Controllers;

use App\Models\Dokter;
use App\Models\User;
use App\Models\Pasien;
use App\Models\DokterPasien;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Hash;

class DokterController extends Controller
{
    private $jenisDokterList = [
        'DOKTER_UMUM'                      => 'Dokter Umum',
        'DOKTER_GIGI'                      => 'Dokter Gigi',
        'DOKTER_SPESIALIS_ANAK'            => 'Spesialis Anak',
        'DOKTER_SPESIALIS_KANDUNGAN'       => 'Spesialis Kandungan',
        'DOKTER_SPESIALIS_PENYAKIT_DALAM'  => 'Spesialis Penyakit Dalam',
        'DOKTER_SPESIALIS_BEDAH'           => 'Spesialis Bedah',
        'DOKTER_SPESIALIS_MATA'            => 'Spesialis Mata',
        'DOKTER_SPESIALIS_THT'             => 'Spesialis THT',
        'DOKTER_SPESIALIS_KULIT'           => 'Spesialis Kulit',
        'DOKTER_SPESIALIS_JANTUNG'         => 'Spesialis Jantung',
        'LAINNYA'                          => 'Lainnya',
    ];

    private $statusList = [
        'AKTIF'    => 'Aktif',
        'CUTI'     => 'Cuti',
        'NONAKTIF' => 'Nonaktif',
        'PENSIUN'  => 'Pensiun',
    ];

    private $hariList = [
        'SENIN'   => 'Senin',
        'SELASA'  => 'Selasa',
        'RABU'    => 'Rabu',
        'KAMIS'   => 'Kamis',
        'JUMAT'   => 'Jumat',
        'SABTU'   => 'Sabtu',
        'MINGGU'  => 'Minggu',
    ];

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

        return view('admin.dokter.index', [
            'jenisDokterList' => $this->jenisDokterList,
            'statusList'      => $this->statusList,
            'dokters'         => Dokter::with(['pasienAktif'])
                                    ->when($request->get('search'), fn($q, $s) =>
                                        $q->where('nama_lengkap', 'like', "%{$s}%")
                                          ->orWhere('kode_dokter', 'like', "%{$s}%")
                                          ->orWhere('nip', 'like', "%{$s}%")
                                    )
                                    ->when($request->get('status_dokter'), fn($q, $s) =>
                                        $q->where('status_dokter', $s)
                                    )
                                    ->when($request->get('jenis_dokter'), fn($q, $j) =>
                                        $q->where('jenis_dokter', $j)
                                    )
                                    ->when($request->get('praktik_hari_ini'), fn($q) =>
                                        $q->whereJsonContains('hari_praktik', now()->locale('id')->isoFormat('dddd')->toUpperCase())
                                    )
                                    ->orderBy('nama_lengkap')
                                    ->paginate(15)
                                    ->withQueryString(),
        ]);
    }

    /**
     * DataTables endpoint - format sama persis dengan PasienController
     */
    public function datatables(Request $request)
    {
        try {
            $query = Dokter::with(['pasienAktif']);

            // Total records tanpa filter
            $recordsTotal = Dokter::count();

            // Filter by status
            if ($request->filled('status_dokter')) {
                $query->where('status_dokter', $request->status_dokter);
            }

            // Filter by jenis dokter
            if ($request->filled('jenis_dokter')) {
                $query->where('jenis_dokter', $request->jenis_dokter);
            }

            // Filter praktik hari ini
            if ($request->filled('praktik_hari_ini') && $request->praktik_hari_ini == '1') {
                $query->whereJsonContains('hari_praktik', strtoupper(now()->isoFormat('dddd')));
            }

            // 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('kode_dokter', 'like', "%{$search}%")
                        ->orWhere('nip', 'like', "%{$search}%")
                        ->orWhere('no_str', 'like', "%{$search}%")
                        ->orWhere('no_telepon', 'like', "%{$search}%");
                });
            }

            // Hitung recordsFiltered SEBELUM skip/take
            $recordsFiltered = $query->count();

            // Order by
            if ($request->has('order')) {
                $orderColumn = $request->order[0]['column'];
                $orderDir    = $request->order[0]['dir'];

                $columns = [
                    0 => 'nama_lengkap',
                    1 => 'jenis_dokter',
                    2 => 'no_telepon',
                    3 => 'status_dokter',
                ];

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

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

            $dokters = $query->get();

            // Format data
            $data = $dokters->map(function ($dokter) {
                // Avatar
                if ($dokter->foto_profil) {
                    $avatar = '<img src="' . asset('storage/' . $dokter->foto_profil) . '" class="w-9 h-9 rounded-full object-cover shrink-0" alt="">';
                } else {
                    $initial = strtoupper(substr($dokter->nama_lengkap, 0, 1));
                    $avatar  = '<div class="w-9 h-9 rounded-full bg-gradient-to-br from-teal-400 to-teal-600 flex items-center justify-center text-white font-bold text-sm shrink-0">' . $initial . '</div>';
                }

                // Nama + kode
                $nama_formatted = '
                    <div class="flex items-center gap-3">
                        ' . $avatar . '
                        <div>
                            <p class="text-sm font-semibold text-slate-800 dark:text-slate-100">' . e($dokter->nama_lengkap) . '</p>
                            <p class="text-xs text-slate-400 dark:text-slate-500 font-mono">' . e($dokter->kode_dokter) . '</p>
                        </div>
                    </div>';

                // Spesialisasi
                $jenisDokterList = [
                    'DOKTER_UMUM'                      => 'Dokter Umum',
                    'DOKTER_GIGI'                      => 'Dokter Gigi',
                    'DOKTER_SPESIALIS_ANAK'            => 'Spesialis Anak',
                    'DOKTER_SPESIALIS_KANDUNGAN'       => 'Spesialis Kandungan',
                    'DOKTER_SPESIALIS_PENYAKIT_DALAM'  => 'Spesialis Penyakit Dalam',
                    'DOKTER_SPESIALIS_BEDAH'           => 'Spesialis Bedah',
                    'DOKTER_SPESIALIS_MATA'            => 'Spesialis Mata',
                    'DOKTER_SPESIALIS_THT'             => 'Spesialis THT',
                    'DOKTER_SPESIALIS_KULIT'           => 'Spesialis Kulit',
                    'DOKTER_SPESIALIS_JANTUNG'         => 'Spesialis Jantung',
                    'LAINNYA'                          => 'Lainnya',
                ];
                $jenisLabel = $jenisDokterList[$dokter->jenis_dokter] ?? $dokter->jenis_dokter;
                $spesialis_formatted = '<p class="text-sm text-slate-700 dark:text-slate-200">' . e($jenisLabel) . '</p>';
                if ($dokter->spesialisasi) {
                    $spesialis_formatted .= '<p class="text-xs text-slate-400 dark:text-slate-500">' . e($dokter->spesialisasi) . '</p>';
                }

                // Jadwal
                $jadwal_formatted = '<span class="text-xs text-slate-400 dark:text-slate-500">—</span>';
                if ($dokter->hari_praktik) {
                    $hari = is_array($dokter->hari_praktik) ? $dokter->hari_praktik : json_decode($dokter->hari_praktik, true);
                    $hariShort = ['SENIN'=>'Sen','SELASA'=>'Sel','RABU'=>'Rab','KAMIS'=>'Kam','JUMAT'=>'Jum','SABTU'=>'Sab','MINGGU'=>'Min'];
                    $hariSlice = array_slice($hari ?? [], 0, 3);
                    $badges = '';
                    foreach ($hariSlice as $h) {
                        $label   = $hariShort[strtoupper($h)] ?? substr($h, 0, 3);
                        $badges .= '<span class="inline-flex px-1.5 py-0.5 text-xs bg-teal-100 dark:bg-teal-900/40 text-teal-700 dark:text-teal-300 rounded">' . $label . '</span>';
                    }
                    if (count($hari ?? []) > 3) {
                        $badges .= '<span class="text-xs text-slate-400">+' . (count($hari) - 3) . '</span>';
                    }
                    $jam = '';
                    if ($dokter->jam_mulai_praktik && $dokter->jam_selesai_praktik) {
                        $jam = '<p class="text-xs text-slate-400 dark:text-slate-500 mt-0.5">'
                            . substr($dokter->jam_mulai_praktik, 0, 5) . ' – ' . substr($dokter->jam_selesai_praktik, 0, 5)
                            . '</p>';
                    }
                    $jadwal_formatted = '<div class="flex flex-wrap gap-1">' . $badges . '</div>' . $jam;
                }

                // Kontak
                $kontak_formatted = '<p class="text-sm text-slate-600 dark:text-slate-300">' . e($dokter->no_telepon ?? '—') . '</p>';
                if ($dokter->email) {
                    $kontak_formatted .= '<p class="text-xs text-slate-400 dark:text-slate-500 truncate max-w-[140px]">' . e($dokter->email) . '</p>';
                }

                // Status badge
                $statusList = [
                    'AKTIF'    => 'Aktif',
                    'CUTI'     => 'Cuti',
                    'NONAKTIF' => 'Nonaktif',
                    'PENSIUN'  => 'Pensiun',
                ];
                $sc = match ($dokter->status_dokter) {
                    'AKTIF'    => 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-400',
                    'CUTI'     => 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/40 dark:text-yellow-400',
                    'NONAKTIF' => 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-400',
                    'PENSIUN'  => 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-400',
                    default    => 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-400',
                };
                $pasienAktifCount    = $dokter->pasienAktif->count();
                $status_formatted    = '
                    <span class="inline-flex px-2.5 py-0.5 rounded-full text-xs font-semibold ' . $sc . '">'
                        . ($statusList[$dokter->status_dokter] ?? $dokter->status_dokter) .
                    '</span>
                    <p class="text-xs text-slate-400 dark:text-slate-500 mt-1">' . $pasienAktifCount . ' pasien aktif</p>';

                // Aksi
                $showUrl   = route('admin.dokter.show', $dokter->id);
                $editUrl   = route('admin.dokter.edit', $dokter->id);
                $jadwalUrl = route('admin.dokter.jadwal', $dokter->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"
                           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"
                           title="Edit Dokter">
                            <i class="fas fa-edit"></i>
                        </a>
                        <a href="' . $jadwalUrl . '"
                           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"
                           title="Jadwal">
                            <i class="fas fa-calendar-alt"></i>
                        </a>
                        <button onclick="confirmDelete(' . $dokter->id . ', \'' . addslashes($dokter->nama_lengkap) . '\')"
                                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"
                                title="Hapus">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>';

                return [
                    'id'                  => $dokter->id,
                    'nama_lengkap'        => $dokter->nama_lengkap,
                    'nama_formatted'      => $nama_formatted,
                    'spesialis_formatted' => $spesialis_formatted,
                    'jadwal_formatted'    => $jadwal_formatted,
                    'kontak_formatted'    => $kontak_formatted,
                    'status_dokter'       => $dokter->status_dokter,
                    'status_formatted'    => $status_formatted,
                    'aksi'                => $aksi,
                ];
            });

            // Stats untuk cards
            $stats = [
                'total'    => Dokter::count(),
                'aktif'    => Dokter::where('status_dokter', 'AKTIF')->count(),
                'cuti'     => Dokter::where('status_dokter', 'CUTI')->count(),
                'nonaktif' => Dokter::whereIn('status_dokter', ['NONAKTIF', 'PENSIUN'])->count(),
            ];

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

        } catch (\Exception $e) {
            \Log::error('Dokter DataTables Error: ' . $e->getMessage());

            return response()->json([
                'draw'            => intval($request->draw ?? 0),
                'recordsTotal'    => 0,
                'recordsFiltered' => 0,
                'data'            => [],
                'error'           => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Show the form for creating a new dokter
     */
    public function create()
    {
        return view('admin.dokter.create', [
            'jenisDokterList' => $this->jenisDokterList,
            'hariList'        => $this->hariList,
        ]);
    }

    /**
     * Store a newly created dokter
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'buat_akun_login'        => 'required|boolean',
            'username'               => 'required_if:buat_akun_login,true|string|max:50|unique:users,username',
            'email_login'            => 'required_if:buat_akun_login,true|email|unique:users,email',
            'password'               => 'required_if:buat_akun_login,true|string|min:8',
            'nip'                    => 'nullable|string|max:30|unique:dokter,nip',
            'nik'                    => 'nullable|string|size:16|unique:dokter,nik',
            'nama_lengkap'           => 'required|string|max:100',
            'jenis_kelamin'          => 'required|in:L,P',
            'tanggal_lahir'          => 'required|date|before:today',
            'tempat_lahir'           => 'nullable|string|max:50',
            'alamat_lengkap'         => 'nullable|string',
            'province_id'            => 'nullable|string|max:2',
            'regency_id'             => 'nullable|string|max:4',
            'district_id'            => 'nullable|string|max:7',
            'village_id'             => 'nullable|string|max:10',
            'no_telepon'             => 'nullable|string|max:15',
            'no_wa'                  => 'nullable|string|max:15',
            'email'                  => 'nullable|email|max:100',
            'no_str'                 => 'required|string|max:50',
            'tanggal_str'            => 'required|date',
            'tanggal_expired_str'    => 'required|date|after:tanggal_str',
            'no_sip'                 => 'nullable|string|max:50',
            'tanggal_sip'            => 'nullable|date',
            'tanggal_expired_sip'    => 'nullable|date|after:tanggal_sip',
            'jenis_dokter'           => 'required|in:DOKTER_UMUM,DOKTER_GIGI,DOKTER_SPESIALIS_ANAK,DOKTER_SPESIALIS_KANDUNGAN,DOKTER_SPESIALIS_PENYAKIT_DALAM,DOKTER_SPESIALIS_BEDAH,DOKTER_SPESIALIS_MATA,DOKTER_SPESIALIS_THT,DOKTER_SPESIALIS_KULIT,DOKTER_SPESIALIS_JANTUNG,LAINNYA',
            'spesialisasi'           => 'nullable|string|max:100',
            'hari_praktik'           => 'nullable|array',
            'jam_mulai_praktik'      => 'nullable|date_format:H:i',
            'jam_selesai_praktik'    => 'nullable|date_format:H:i|after:jam_mulai_praktik',
            'ruangan'                => 'nullable|string|max:50',
            'gedung'                 => 'nullable|string|max:50',
            'lantai'                 => 'nullable|string|max:20',
            'kuota_pasien_per_hari'  => 'nullable|integer|min:1',
            'biografi'               => 'nullable|string',
            'bahasa_yang_dikuasai'   => 'nullable|array',
            'tarif_konsultasi'       => 'nullable|numeric|min:0',
            'foto_profil'            => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
        ]);

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

        try {
            DB::beginTransaction();

            $userId = null;

            if ($request->buat_akun_login) {
                $user = User::create([
                    'role'               => 'dokter',
                    'name'               => $request->nama_lengkap,
                    'username'           => $request->username,
                    'email'              => $request->email_login,
                    'password'           => Hash::make($request->password),
                    'email_verified_at'  => now(),
                ]);
                $userId = $user->id;
            }

            $lastDokter  = Dokter::orderBy('id', 'desc')->first();
            $nextNumber  = $lastDokter ? (int) substr($lastDokter->kode_dokter, 4) + 1 : 1;
            $kodeDokter  = 'DOK-' . str_pad($nextNumber, 4, '0', STR_PAD_LEFT);

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

            $usia = null;
            if ($request->tanggal_lahir) {
                $usia = now()->diff(\Carbon\Carbon::parse($request->tanggal_lahir))->y;
            }

            Dokter::create([
                'user_id'                => $userId,
                'kode_dokter'            => $kodeDokter,
                'nip'                    => $request->nip,
                'nik'                    => $request->nik,
                'nama_lengkap'           => $request->nama_lengkap,
                'jenis_kelamin'          => $request->jenis_kelamin,
                'tanggal_lahir'          => $request->tanggal_lahir,
                'tempat_lahir'           => $request->tempat_lahir,
                'usia'                   => $usia,
                'alamat_lengkap'         => $request->alamat_lengkap,
                'province_id'            => $request->province_id,
                'regency_id'             => $request->regency_id,
                'district_id'            => $request->district_id,
                'village_id'             => $request->village_id,
                'no_telepon'             => $request->no_telepon,
                'no_wa'                  => $request->no_wa,
                'email'                  => $request->email,
                'no_str'                 => $request->no_str,
                'tanggal_str'            => $request->tanggal_str,
                'tanggal_expired_str'    => $request->tanggal_expired_str,
                'no_sip'                 => $request->no_sip,
                'tanggal_sip'            => $request->tanggal_sip,
                'tanggal_expired_sip'    => $request->tanggal_expired_sip,
                'jenis_dokter'           => $request->jenis_dokter,
                'spesialisasi'           => $request->spesialisasi,
                'hari_praktik'           => $request->hari_praktik ? json_encode($request->hari_praktik) : null,
                'jam_mulai_praktik'      => $request->jam_mulai_praktik,
                'jam_selesai_praktik'    => $request->jam_selesai_praktik,
                'ruangan'                => $request->ruangan,
                'gedung'                 => $request->gedung,
                'lantai'                 => $request->lantai,
                'kuota_pasien_per_hari'  => $request->kuota_pasien_per_hari,
                'biografi'               => $request->biografi,
                'bahasa_yang_dikuasai'   => $request->bahasa_yang_dikuasai ? json_encode($request->bahasa_yang_dikuasai) : null,
                'tarif_konsultasi'       => $request->tarif_konsultasi,
                'foto_profil'            => $fotoPath,
                'status_dokter'          => 'AKTIF',
            ]);

            DB::commit();

            return redirect()->route('admin.dokter.index')
                ->with('success', 'Dokter berhasil ditambahkan.');

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

    /**
     * Display the specified dokter
     */
    public function show($id)
    {
        $dokter = Dokter::with(['user', 'pasienAktif'])->findOrFail($id);
        return view('admin.dokter.show', [
            'dokter'          => $dokter,
            'jenisDokterList' => $this->jenisDokterList,
            'statusList'      => $this->statusList,
        ]);
    }

    /**
     * Show the form for editing the specified dokter
     */
    public function edit($id)
    {
        $dokter = Dokter::findOrFail($id);
        return view('admin.dokter.edit', [
            'dokter'          => $dokter,
            'jenisDokterList' => $this->jenisDokterList,
            'statusList'      => $this->statusList,
            'hariList'        => $this->hariList,
        ]);
    }

    /**
     * Update the specified dokter
     */
    public function update(Request $request, $id)
    {
        $dokter = Dokter::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'nama_lengkap'           => 'required|string|max:100',
            'jenis_kelamin'          => 'required|in:L,P',
            'tanggal_lahir'          => 'required|date|before:today',
            'tempat_lahir'           => 'nullable|string|max:50',
            'alamat_lengkap'         => 'nullable|string',
            'no_telepon'             => 'nullable|string|max:15',
            'no_wa'                  => 'nullable|string|max:15',
            'email'                  => 'nullable|email|max:100',
            'no_str'                 => 'required|string|max:50',
            'tanggal_str'            => 'required|date',
            'tanggal_expired_str'    => 'required|date|after:tanggal_str',
            'no_sip'                 => 'nullable|string|max:50',
            'tanggal_sip'            => 'nullable|date',
            'tanggal_expired_sip'    => 'nullable|date|after:tanggal_sip',
            'jenis_dokter'           => 'required',
            'spesialisasi'           => 'nullable|string|max:100',
            'hari_praktik'           => 'nullable|array',
            'jam_mulai_praktik'      => 'nullable|date_format:H:i',
            'jam_selesai_praktik'    => 'nullable|date_format:H:i|after:jam_mulai_praktik',
            'ruangan'                => 'nullable|string|max:50',
            'kuota_pasien_per_hari'  => 'nullable|integer|min:1',
            'status_dokter'          => 'required|in:AKTIF,CUTI,NONAKTIF,PENSIUN',
            'biografi'               => 'nullable|string',
            'tarif_konsultasi'       => 'nullable|numeric|min:0',
            'foto_profil'            => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
        ]);

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

        try {
            $usia = null;
            if ($request->tanggal_lahir) {
                $usia = now()->diff(\Carbon\Carbon::parse($request->tanggal_lahir))->y;
            }

            if ($request->hasFile('foto_profil')) {
                if ($dokter->foto_profil) {
                    Storage::disk('public')->delete($dokter->foto_profil);
                }
                $fotoPath       = $request->file('foto_profil')->store('dokter/foto', 'public');
                $dokter->foto_profil = $fotoPath;
            }

            $dokter->update([
                'nama_lengkap'           => $request->nama_lengkap,
                'jenis_kelamin'          => $request->jenis_kelamin,
                'tanggal_lahir'          => $request->tanggal_lahir,
                'tempat_lahir'           => $request->tempat_lahir,
                'usia'                   => $usia,
                'alamat_lengkap'         => $request->alamat_lengkap,
                'province_id'            => $request->province_id,
                'regency_id'             => $request->regency_id,
                'district_id'            => $request->district_id,
                'village_id'             => $request->village_id,
                'no_telepon'             => $request->no_telepon,
                'no_wa'                  => $request->no_wa,
                'email'                  => $request->email,
                'no_str'                 => $request->no_str,
                'tanggal_str'            => $request->tanggal_str,
                'tanggal_expired_str'    => $request->tanggal_expired_str,
                'no_sip'                 => $request->no_sip,
                'tanggal_sip'            => $request->tanggal_sip,
                'tanggal_expired_sip'    => $request->tanggal_expired_sip,
                'jenis_dokter'           => $request->jenis_dokter,
                'spesialisasi'           => $request->spesialisasi,
                'hari_praktik'           => $request->hari_praktik ? json_encode($request->hari_praktik) : null,
                'jam_mulai_praktik'      => $request->jam_mulai_praktik,
                'jam_selesai_praktik'    => $request->jam_selesai_praktik,
                'ruangan'                => $request->ruangan,
                'kuota_pasien_per_hari'  => $request->kuota_pasien_per_hari,
                'status_dokter'          => $request->status_dokter,
                'biografi'               => $request->biografi,
                'tarif_konsultasi'       => $request->tarif_konsultasi,
            ]);

            if ($dokter->user) {
                $dokter->user->update(['name' => $request->nama_lengkap]);
            }

            return redirect()->route('admin.dokter.show', $dokter->id)
                ->with('success', 'Data dokter berhasil diperbarui.');

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

    /**
     * Show jadwal dokter
     */
    public function jadwal($id)
    {
        $dokter = Dokter::with('pasienAktif')->findOrFail($id);
        return view('admin.dokter.jadwal', compact('dokter'));
    }

    /**
     * Statistik overview
     */
    public function statistik(Request $request)
    {
        return view('admin.dokter.statistik');
    }

    /**
     * Assign pasien to dokter
     */
    public function assignPasien(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'pasien_id'                      => 'required|exists:pasien,id',
            'diagnosis_utama'                => 'nullable|string',
            'rencana_perawatan'              => 'nullable|string',
            'tanggal_kontrol_berikutnya'     => 'nullable|date|after:today',
        ]);

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

        try {
            $dokter   = Dokter::findOrFail($id);
            $existing = DokterPasien::where('dokter_id', $dokter->id)
                ->where('pasien_id', $request->pasien_id)
                ->where('status_penanganan', 'AKTIF')
                ->first();

            if ($existing) {
                return redirect()->back()->with('error', 'Pasien sudah dalam penanganan dokter ini');
            }

            DokterPasien::create([
                'dokter_id'                      => $dokter->id,
                'pasien_id'                      => $request->pasien_id,
                'tanggal_mulai_menangani'        => now(),
                'status_penanganan'              => 'AKTIF',
                'diagnosis_utama'                => $request->diagnosis_utama,
                'rencana_perawatan'              => $request->rencana_perawatan,
                'tanggal_kontrol_berikutnya'     => $request->tanggal_kontrol_berikutnya,
                'didaftarkan_oleh'               => auth()->id(),
            ]);

            $dokter->increment('jumlah_pasien_ditangani');

            return redirect()->back()->with('success', 'Pasien berhasil ditambahkan ke daftar penanganan dokter.');

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

    /**
     * Remove the specified dokter
     */
    public function destroy($id)
    {
        try {
            $dokter = Dokter::findOrFail($id);

            if ($dokter->pasienAktif()->count() > 0) {
                return response()->json([
                    'success' => false,
                    'message' => 'Tidak dapat menghapus dokter yang masih menangani pasien aktif.',
                ], 422);
            }

            if ($dokter->foto_profil) {
                Storage::disk('public')->delete($dokter->foto_profil);
            }

            $dokter->delete();

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

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