<?php

namespace App\Http\Controllers;

use App\Models\Pasien;
use App\Models\RiwayatPenghapusanPasien;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;

class PasienRiwayatController extends Controller
{
    /**
     * Display riwayat penghapusan pasien
     */
    public function index(Request $request)
    {
        // Handle stats API
        if ($request->has('stats')) {
            return response()->json([
                'total' => RiwayatPenghapusanPasien::count(),
                'dapat_dipulihkan' => RiwayatPenghapusanPasien::where('status_pemulihan', 'DAPAT_DIPULIHKAN')->count(),
                'sudah_restore' => RiwayatPenghapusanPasien::where('status_pemulihan', 'SUDAH_DI_RESTORE')->count(),
            ]);
        }

        return view('pasien.riwayat-penghapusan.index');
    }

    /**
     * DataTables AJAX endpoint - PUBLIC untuk bisa di-access dari route
     */
    public function datatable(Request $request)
    {
        $query = RiwayatPenghapusanPasien::with(['penghapus:id,name', 'peRestorer:id,name']);

        // Filter berdasarkan status pemulihan - gunakan filled() untuk cek value tidak kosong
        if ($request->filled('status_pemulihan')) {
            $query->where('status_pemulihan', $request->status_pemulihan);
        }

        // Filter berdasarkan tipe penghapusan - gunakan filled() untuk cek value tidak kosong
        if ($request->filled('tipe_penghapusan')) {
            $query->where('tipe_penghapusan', $request->tipe_penghapusan);
        }

        // Search
        if ($request->filled('search')) {
            $searchData = $request->input('search');
            $keyword = is_array($searchData) ? ($searchData['value'] ?? '') : $searchData;
            
            if (!empty($keyword)) {
                $query->where(function ($q) use ($keyword) {
                    $q->where('nama_pasien', 'like', "%{$keyword}%")
                        ->orWhere('no_rekam_medis', 'like', "%{$keyword}%")
                        ->orWhere('nik', 'like', "%{$keyword}%");
                });
            }
        }

        return DataTables::of($query)
            ->addColumn('penghapus_nama', function ($row) {
                return $row->penghapus?->name ?? 'System';
            })
            ->addColumn('waktu_penghapusan_formatted', function ($row) {
                return $row->waktu_penghapusan->format('d/m/Y H:i');
            })
            ->addColumn('waktu_restore_formatted', function ($row) {
                return $row->waktu_restore ? $row->waktu_restore->format('d/m/Y H:i') : '-';
            })
            ->addColumn('status_badge', function ($row) {
                $statusColors = [
                    'DAPAT_DIPULIHKAN' => 'badge-warning',
                    'SUDAH_DI_RESTORE' => 'badge-success',
                    'TIDAK_REVERSIBLE' => 'badge-danger',
                ];
                $color = $statusColors[$row->status_pemulihan] ?? 'badge-secondary';
                $label = str_replace('_', ' ', $row->status_pemulihan);

                return "<span class='badge {$color}'>{$label}</span>";
            })
            ->addColumn('tipe_badge', function ($row) {
                $color = $row->tipe_penghapusan === 'SOFT_DELETE' ? 'badge-info' : 'badge-danger';
                $label = $row->tipe_penghapusan === 'SOFT_DELETE' ? 'Soft Delete' : 'Hard Delete';

                return "<span class='badge {$color}'>{$label}</span>";
            })
            ->addColumn('aksi', function ($row) {
                $buttons = '<div class="flex flex-wrap gap-1.5 items-center">';

                // Tombol View Detail
                $buttons .= '<a href="' . route('pasien.riwayat-penghapusan.show', $row->id) . '" 
                    class="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-blue-700 dark:text-blue-300 bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800 rounded-md hover:bg-blue-100 dark:hover:bg-blue-900/50 transition-colors duration-200" 
                    title="Lihat Detail">
                    <i class="fas fa-eye text-sm"></i>
                    <span>Lihat</span>
                </a>';

                // Tombol Restore (hanya jika bisa dipulihkan)
                if ($row->canRestore()) {
                    $buttons .= '<button type="button" 
                        class="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-amber-700 dark:text-amber-300 bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-800 rounded-md hover:bg-amber-100 dark:hover:bg-amber-900/50 transition-colors duration-200 restore-btn" 
                        data-id="' . $row->id . '" 
                        title="Restore Pasien">
                        <i class="fas fa-undo text-sm"></i>
                        <span>Restore</span>
                    </button>';
                }

                // Tombol Hard Delete Permanen (hanya jika soft delete)
                if ($row->tipe_penghapusan === 'SOFT_DELETE' && $row->status_pemulihan === 'DAPAT_DIPULIHKAN') {
                    $buttons .= '<button type="button" 
                        class="inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-red-700 dark:text-red-300 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-md hover:bg-red-100 dark:hover:bg-red-900/50 transition-colors duration-200 hard-delete-btn" 
                        data-id="' . $row->id . '" 
                        title="Hard Delete Permanen">
                        <i class="fas fa-trash text-sm"></i>
                        <span>Hapus</span>
                    </button>';
                }

                $buttons .= '</div>';

                return $buttons;
            })
            ->rawColumns(['status_badge', 'tipe_badge', 'aksi'])
            ->make(true);
    }

    /**
     * Tampilkan detail riwayat penghapusan
     */
    public function show($id)
    {
        $riwayat = RiwayatPenghapusanPasien::findOrFail($id);

        return view('pasien.riwayat-penghapusan.show', [
            'riwayat' => $riwayat,
        ]);
    }

    /**
     * Restore pasien dari riwayat
     * 
     * Mengembalikan pasien dari soft delete (restored ke active state)
     * Juga restore semua related soft-deleted data (exam, pembayaran, dll)
     */
    public function restore(Request $request, $id)
    {
        try {
            $riwayat = RiwayatPenghapusanPasien::findOrFail($id);

            // Cek apakah bisa di-restore
            if (!$riwayat->canRestore()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Riwayat ini tidak dapat di-restore. Status: ' . $riwayat->status_pemulihan,
                ], 422);
            }

            DB::beginTransaction();
            try {
                // 1. Restore pasien
                $pasien = Pasien::withTrashed()->findOrFail($riwayat->pasien_id);
                $pasien->restore();

                // 2. Restore semua related soft-deleted data
                // Pemeriksaan kesehatan
                \App\Models\PemeriksaanKesehatan::where('pasien_id', $pasien->id)
                    ->onlyTrashed()
                    ->restore();

                // Embedding wajah
                \App\Models\EmbeddingWajah::where('pasien_id', $pasien->id)
                    ->onlyTrashed()
                    ->restore();

                // Analisis AI
                \App\Models\AnalisisAi::where('pasien_id', $pasien->id)
                    ->onlyTrashed()
                    ->restore();

                // Log notifikasi
                \App\Models\LogNotifikasi::where('pasien_id', $pasien->id)
                    ->onlyTrashed()
                    ->restore();

                // Dokter pasien
                \App\Models\DokterPasien::where('pasien_id', $pasien->id)
                    ->onlyTrashed()
                    ->restore();

                // 3. Update riwayat status
                $riwayat->update([
                    'status_pemulihan' => 'SUDAH_DI_RESTORE',
                    'waktu_restore' => now(),
                    'di_restore_oleh' => auth()->id(),
                ]);

                // 4. Log aktivitas
                DB::table('log_aktivitas_sistem')->insert([
                    'user_id' => auth()->id(),
                    'jenis_aktivitas' => 'RESTORE',
                    'modul' => 'PASIEN',
                    'aksi' => 'RESTORE',
                    'deskripsi' => 'Pasien di-restore dari riwayat penghapusan',
                    'model_type' => 'Pasien',
                    'model_id' => $pasien->id,
                    'data_lama' => json_encode(['status' => 'DELETED']),
                    'data_baru' => json_encode(['status' => 'RESTORED']),
                    '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(),
                ]);

                DB::commit();

                return response()->json([
                    'success' => true,
                    'message' => 'Pasien ' . $pasien->nama_lengkap . ' berhasil di-restore. Semua data terkait juga di-restore.',
                ]);

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

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

    /**
     * Hard delete riwayat (permanen hapus)
     * 
     * Untuk riwayat yang tipe-nya SOFT_DELETE, user bisa pilih untuk hard delete
     * (menghapus data pasien secara permanen dari database)
     */
    public function hardDelete(Request $request, $id)
    {
        try {
            $riwayat = RiwayatPenghapusanPasien::findOrFail($id);

            // Cek: hanya soft delete yang bisa di-hard-delete
            if ($riwayat->tipe_penghapusan !== 'SOFT_DELETE') {
                return response()->json([
                    'success' => false,
                    'message' => 'Hanya riwayat soft delete yang dapat di-hard-delete.',
                ], 422);
            }

            // Require password confirmation
            $password = $request->input('password', '');
            if (!$password || !password_verify($password, auth()->user()->password)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Password incorrect.',
                ], 403);
            }

            DB::beginTransaction();
            try {
                $pasienId = $riwayat->pasien_id;
                $pasienNama = $riwayat->nama_pasien;

                // 1. Ambil pasien (termasuk yang sudah soft deleted)
                $pasien = Pasien::withTrashed()->findOrFail($pasienId);

                // 2. Hard delete semua data terkait
                \App\Models\PemeriksaanKesehatan::where('pasien_id', $pasienId)->forceDelete();
                \App\Models\EmbeddingWajah::where('pasien_id', $pasienId)->forceDelete();
                \App\Models\AnalisisAi::where('pasien_id', $pasienId)->forceDelete();
                \App\Models\LogNotifikasi::where('pasien_id', $pasienId)->forceDelete();
                \App\Models\DokterPasien::where('pasien_id', $pasienId)->forceDelete();

                // 3. Hard delete pasien itu sendiri
                $pasien->forceDelete();

                // 4. Update riwayat status
                $riwayat->update([
                    'tipe_penghapusan' => 'HARD_DELETE',
                    'status_pemulihan' => 'TIDAK_REVERSIBLE',
                ]);

                // 5. Log aktivitas
                DB::table('log_aktivitas_sistem')->insert([
                    'user_id' => auth()->id(),
                    'jenis_aktivitas' => 'DELETE',
                    'modul' => 'PASIEN',
                    'aksi' => 'HARD_DELETE',
                    'deskripsi' => 'Pasien hard deleted permanently dari riwayat',
                    'model_type' => 'Pasien',
                    'model_id' => $pasienId,
                    'data_lama' => json_encode(['nama' => $pasienNama]),
                    '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(),
                ]);

                DB::commit();

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

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

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