<?php

namespace App\Http\Controllers;

use App\Models\Laporan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LaporanController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::user();
        
        // Base Query
        if ($user->isMahasiswaDosenRole()) {
            $query = Laporan::where('user_id', $user->id);
        } elseif ($user->isAdmin()) {
            $query = Laporan::query();
        } else {
            // Satgas, Penilai, Psikolog, Rektor: filter by their PTS
            $query = Laporan::where('pts_nama', $user->pts_nama);
        }

        // Filters
        if ($request->filled('tipe_laporan')) {
            $query->where('tipe_laporan', $request->tipe_laporan);
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('search')) {
            $query->where('judul', 'like', '%' . $request->search . '%');
        }

        $laporans = $query->latest()->paginate(10)->withQueryString();

        return view('laporan.index', compact('laporans'));
    }

    public function create()
    {
        // Only Mahasiswa / Dosen can create reports
        if (!Auth::user()->isMahasiswaDosenRole()) {
            return redirect()->route('dashboard')->with('error', 'Hanya Mahasiswa atau Dosen yang dapat mengajukan laporan.');
        }

        return view('laporan.create');
    }

    public function store(Request $request)
    {
        $user = Auth::user();
        if (!$user->isMahasiswaDosenRole()) {
            return redirect()->route('dashboard')->with('error', 'Akses ditolak.');
        }

        $request->validate([
            'pelapor_nama' => 'required|string|max:255',
            'pelapor_tipe' => 'required|in:Mahasiswa,Dosen,Tenaga Kependidikan,Masyarakat Umum',

            'pelapor_nim_nidn' => 'required|string|max:100',
            'no_telepon' => 'required|string|max:20',
            'file_identitas' => 'nullable|file|mimes:png,jpg,jpeg,zip|max:5120',
            'file_bukti' => 'nullable|file|mimes:png,jpg,jpeg,zip|max:5120',
            'tipe_laporan' => 'required|in:preventif_konseling,kekerasan_bullying,integritas_akademik',
            'jenis_kelamin' => 'required|in:Laki-Laki,Perempuan',
            'pelapor_email' => 'required|email|max:255',
            'tanggal_kejadian' => 'required|date',
            'lokasi_kejadian' => 'required|string|max:255',
            'jenis_kekerasan' => 'required_if:tipe_laporan,kekerasan_bullying|nullable|string|max:255',
            'jalur' => 'required_if:tipe_laporan,preventif_konseling|nullable|in:mandiri,rujukan',
            'judul' => 'required|string|max:255',
            'deskripsi' => 'required|string',
        ], [
            'file_identitas.max' => 'Maaf ukuran file identitas tidak sesuai maksimal 5 MB.',
            'file_bukti.max' => 'Maaf ukuran file bukti tidak sesuai maksimal 5 MB.',
        ]);

        // Handle file uploads
        $fileIdentitasPath = null;
        if ($request->hasFile('file_identitas')) {
            $file = $request->file('file_identitas');
            $filename = 'identitas_' . time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads'), $filename);
            $fileIdentitasPath = $filename;
        }

        $fileBuktiPath = null;
        if ($request->hasFile('file_bukti')) {
            $file = $request->file('file_bukti');
            $filename = 'bukti_' . time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads'), $filename);
            $fileBuktiPath = $filename;
        }

        // Determine initial status based on type
        $status = 'diajukan';
        if ($request->tipe_laporan === 'preventif_konseling') {
            $status = 'menunggu_psikolog';
        } elseif ($request->tipe_laporan === 'kekerasan_bullying') {
            $status = 'menunggu_satgas';
        } elseif ($request->tipe_laporan === 'integritas_akademik') {
            $status = 'menunggu_penilai';
        }

        Laporan::create([
            'user_id' => $user->id,
            'pelapor_nama' => $request->pelapor_nama,
            'pelapor_tipe' => $request->pelapor_tipe,

            'pelapor_nim_nidn' => $request->pelapor_nim_nidn,
            'no_telepon' => $request->no_telepon,
            'file_identitas' => $fileIdentitasPath,
            'file_bukti' => $fileBuktiPath,
            'tipe_laporan' => $request->tipe_laporan,
            'jenis_kelamin' => $request->jenis_kelamin,
            'pelapor_email' => $request->pelapor_email,
            'tanggal_kejadian' => $request->tanggal_kejadian,
            'lokasi_kejadian' => $request->lokasi_kejadian,
            'jenis_kekerasan' => $request->tipe_laporan === 'kekerasan_bullying' ? $request->jenis_kekerasan : null,
            'jalur' => $request->tipe_laporan === 'preventif_konseling' ? $request->jalur : null,
            'pts_nama' => $user->pts_nama ?? 'LLDIKTI Wilayah III',
            'judul' => $request->judul,
            'deskripsi' => $request->deskripsi,
            'status' => $status,
        ]);

        return redirect()->route('laporan.index')->with('success', 'Laporan/Aduan baru berhasil diajukan dan sedang diproses.');
    }

    public function show(Laporan $laporan)
    {
        $user = Auth::user();
        
        // Authorization check: pelapor only see their own, rektor/satgas/etc see their PTS, LLDIKTI see all.
        if ($user->isMahasiswaDosenRole() && $laporan->user_id !== $user->id) {
            abort(403);
        }
        if (!$user->isAdmin() && !$user->isMahasiswaDosenRole() && $laporan->pts_nama !== $user->pts_nama) {
            abort(403);
        }

        // Load all step relations
        $laporan->load([
            'tindakanSatgas.satgas',
            'tindakanPenilai.penilai',
            'catatanKlinisPsikolog.psikolog',
            'eksekusiRektor.rektor',
        ]);

        return view('laporan.show', compact('laporan'));
    }

    public function export(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:laporans,id',
        ]);

        $laporan = Laporan::with([
            'tindakanSatgas.satgas',
            'tindakanPenilai.penilai',
            'catatanKlinisPsikolog.psikolog',
            'eksekusiRektor.rektor',
        ])->findOrFail($request->id);

        $user = Auth::user();
        if ($user->isMahasiswaDosenRole() && $laporan->user_id !== $user->id) {
            abort(403);
        }
        if (!$user->isAdmin() && !$user->isMahasiswaDosenRole() && $laporan->pts_nama !== $user->pts_nama) {
            abort(403);
        }

        $pdf = app('dompdf.wrapper')->loadView('laporan.pdf', compact('laporan'));
        
        $filename = 'KITA-Laporan-' . $laporan->id . '-' . date('Ymd') . '.pdf';
        
        if ($request->has('download') && $request->download == 1) {
            return $pdf->download($filename);
        }
        
        return $pdf->stream($filename);
    }

    public function edit(Laporan $laporan)
    {
        $user = Auth::user();
        
        // Admin authorization check: Satgas or LLDIKTI
        if (!$user->isAdmin()) {
            abort(403, 'Akses khusus Admin (Satgas atau LLDIKTI).');
        }

        // Load relations
        $laporan->load([
            'tindakanSatgas',
            'tindakanPenilai',
            'catatanKlinisPsikolog',
            'eksekusiRektor'
        ]);

        return view('laporan.edit', compact('laporan'));
    }

    public function update(Request $request, Laporan $laporan)
    {
        $user = Auth::user();
        
        // Admin authorization check: Satgas or LLDIKTI
        if (!$user->isAdmin()) {
            abort(403, 'Akses khusus Admin (Satgas atau LLDIKTI).');
        }
        // General validation rules
        $rules = [
            'pelapor_nama' => 'required|string|max:255',
            'pelapor_tipe' => 'required|in:Mahasiswa,Dosen,Tenaga Kependidikan,Masyarakat Umum',
            'jenis_identitas' => 'required|in:KTM,NIDN/NIP,KTP,SIM,Paspor',
            'pelapor_nim_nidn' => 'required|string|max:100',
            'no_telepon' => 'required|string|max:20',
            'jenis_kelamin' => 'required|in:Laki-Laki,Perempuan',
            'pelapor_email' => 'required|email|max:255',
            'tanggal_kejadian' => 'required|date',
            'lokasi_kejadian' => 'required|string|max:255',
            'tipe_laporan' => 'required|in:preventif_konseling,kekerasan_bullying,integritas_akademik',
            'status' => 'required|string',
            'judul' => 'required|string|max:255',
            'deskripsi' => 'required|string',
        ];

        // Status-specific validation rules
        if ($request->status === 'menunggu_satgas') {
            $rules['satgas_keputusan'] = 'required|in:Terima,Tolak';
            if ($request->satgas_keputusan === 'Terima') {
                $rules['satgas_bantuan'] = 'required|string';
                $rules['satgas_catatan'] = 'nullable|string';
            } else {
                $rules['alasan_penolakan'] = 'required|string';
            }
        } elseif ($request->status === 'menunggu_psikolog') {
            $rules['psikolog_keputusan'] = 'required|in:Terima,Tolak';
            if ($request->psikolog_keputusan === 'Terima') {
                $rules['psikolog_hari'] = 'required|string|max:50';
                $rules['psikolog_tanggal'] = 'required|date';
                $rules['psikolog_jam'] = 'required|string|max:50';
            } else {
                $rules['alasan_penolakan'] = 'required|string';
            }
        } elseif ($request->status === 'menunggu_penilai') {
            $rules['penilai_keputusan'] = 'required|in:Terima,Tolak';
            if ($request->penilai_keputusan === 'Terima') {
                $rules['penilai_sidang_hari'] = 'required|string|max:50';
                $rules['penilai_sidang_tanggal'] = 'required|date';
                $rules['penilai_sidang_jam'] = 'required|string|max:50';
                $rules['penilai_plagiat_score'] = 'required|integer|min:0|max:100';
                $rules['penilai_rekomendasi'] = 'required|string';
            } else {
                $rules['alasan_penolakan'] = 'required|string';
            }
        } elseif ($request->status === 'menunggu_rektor') {
            $rules['rektor_keputusan'] = 'required|in:Terima,Tolak';
            if ($request->rektor_keputusan === 'Terima') {
                $rules['rektor_sanksi'] = 'required|string';
                $rules['rektor_catatan'] = 'nullable|string';
            } else {
                $rules['alasan_penolakan'] = 'required|string';
            }
        }

        $validated = $request->validate($rules);

        // Update general Laporan attributes
        $laporan->update([
            'pelapor_nama' => $request->pelapor_nama,
            'pelapor_tipe' => $request->pelapor_tipe,
            'jenis_identitas' => $request->jenis_identitas,
            'pelapor_nim_nidn' => $request->pelapor_nim_nidn,
            'no_telepon' => $request->no_telepon,
            'jenis_kelamin' => $request->jenis_kelamin,
            'pelapor_email' => $request->pelapor_email,
            'tanggal_kejadian' => $request->tanggal_kejadian,
            'lokasi_kejadian' => $request->lokasi_kejadian,
            'tipe_laporan' => $request->tipe_laporan,
            'judul' => $request->judul,
            'deskripsi' => $request->deskripsi,
            'status' => $request->status,
        ]);

        // Process Decision
        if ($request->status === 'menunggu_satgas') {
            if ($request->satgas_keputusan === 'Terima') {
                \App\Models\TindakanSatgas::updateOrCreate(
                    ['laporan_id' => $laporan->id],
                    [
                        'satgas_id' => $user->id,
                        'lindungi_korban' => true,
                        'bantuan_hukum_rumah_aman' => $request->satgas_bantuan,
                        'catatan' => $request->satgas_catatan,
                    ]
                );
                
                // Progress status to menunggu_psikolog
                $laporan->update([
                    'status' => 'menunggu_psikolog',
                    'alasan_penolakan' => null
                ]);
            } else {
                // Deny/Tolak
                $laporan->update([
                    'status' => 'ditolak',
                    'alasan_penolakan' => $request->alasan_penolakan
                ]);
                
                $this->sendRejectionEmail($laporan, $request->alasan_penolakan);
            }
        } elseif ($request->status === 'menunggu_psikolog') {
            if ($request->psikolog_keputusan === 'Terima') {
                // Save schedule
                \App\Models\CatatanKlinisPsikolog::updateOrCreate(
                    ['laporan_id' => $laporan->id],
                    [
                        'psikolog_id' => $user->id,
                        'sesi_konseling_online' => 'Tatap Muka Langsung - Hari ' . $request->psikolog_hari . ', Tanggal ' . date('d-m-Y', strtotime($request->psikolog_tanggal)) . ' Jam ' . $request->psikolog_jam,
                        'jadwal_hari' => $request->psikolog_hari,
                        'jadwal_tanggal' => $request->psikolog_tanggal,
                        'jadwal_jam' => $request->psikolog_jam,
                    ]
                );
                
                // Progress status to menunggu_rektor
                $laporan->update([
                    'status' => 'menunggu_rektor',
                    'alasan_penolakan' => null
                ]);
            } else {
                // Deny/Tolak
                $laporan->update([
                    'status' => 'ditolak',
                    'alasan_penolakan' => $request->alasan_penolakan
                ]);
                
                $this->sendRejectionEmail($laporan, $request->alasan_penolakan);
            }
        } elseif ($request->status === 'menunggu_penilai') {
            if ($request->penilai_keputusan === 'Terima') {
                \App\Models\TindakanPenilai::updateOrCreate(
                    ['laporan_id' => $laporan->id],
                    [
                        'penilai_id' => $user->id,
                        'sidang_etik_detail' => 'Sidang Etik - Hari ' . $request->penilai_sidang_hari . ', Tanggal ' . date('d-m-Y', strtotime($request->penilai_sidang_tanggal)) . ' Jam ' . $request->penilai_sidang_jam,
                        'cek_plagiat_score' => $request->penilai_plagiat_score,
                        'rekomendasi_sanksi' => $request->penilai_rekomendasi,
                        'sidang_etik_hari' => $request->penilai_sidang_hari,
                        'sidang_etik_tanggal' => $request->penilai_sidang_tanggal,
                        'sidang_etik_jam' => $request->penilai_sidang_jam,
                    ]
                );

                // Progress status to menunggu_rektor
                $laporan->update([
                    'status' => 'menunggu_rektor',
                    'alasan_penolakan' => null
                ]);
            } else {
                $laporan->update([
                    'status' => 'ditolak',
                    'alasan_penolakan' => $request->alasan_penolakan
                ]);

                $this->sendRejectionEmail($laporan, $request->alasan_penolakan);
            }
        } elseif ($request->status === 'menunggu_rektor') {
            if ($request->rektor_keputusan === 'Terima') {
                \App\Models\EksekusiRektor::updateOrCreate(
                    ['laporan_id' => $laporan->id],
                    [
                        'rektor_id' => $user->id,
                        'sanksi_eksekusi' => $request->rektor_sanksi,
                        'catatan' => $request->rektor_catatan,
                    ]
                );

                // Case Selesai
                $laporan->update([
                    'status' => 'selesai',
                    'alasan_penolakan' => null
                ]);
            } else {
                $laporan->update([
                    'status' => 'ditolak',
                    'alasan_penolakan' => $request->alasan_penolakan
                ]);

                $this->sendRejectionEmail($laporan, $request->alasan_penolakan);
            }
        } elseif ($request->status === 'selesai') {
            // Update Eksekusi Rektor if fields are present
            if ($request->has('rektor_sanksi')) {
                \App\Models\EksekusiRektor::updateOrCreate(
                    ['laporan_id' => $laporan->id],
                    [
                        'rektor_id' => $user->id,
                        'sanksi_eksekusi' => $request->rektor_sanksi,
                        'catatan' => $request->rektor_catatan,
                    ]
                );
            }
        }

        return redirect()->route('laporan.show', $laporan->id)->with('success', 'Laporan/Aduan berhasil diperbarui oleh Admin.');
    }

    private function sendRejectionEmail(Laporan $laporan, $reason)
    {
        try {
            \Illuminate\Support\Facades\Mail::raw("Halo {$laporan->pelapor_nama},\n\nLaporan Anda dengan judul \"{$laporan->judul}\" telah ditinjau oleh Admin dan dinyatakan DITOLAK dengan alasan:\n\n\"{$reason}\"\n\nTerima kasih atas perhatian Anda.", function ($message) use ($laporan) {
                $message->to($laporan->pelapor_email)
                        ->subject("Pemberitahuan Status Laporan KITA #" . str_pad($laporan->id, 4, '0', STR_PAD_LEFT));
            });
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error("Gagal mengirim email penolakan: " . $e->getMessage());
        }
    }

    public function togglePantauLldikti(Laporan $laporan)
    {
        if (!Auth::user()->isAdmin()) {
            abort(403, 'Akses ditolak.');
        }

        $laporan->update([
            'dipantau_lldikti' => !$laporan->dipantau_lldikti
        ]);

        return back()->with('success', 'Status pemantauan LLDIKTI berhasil diperbarui.');
    }
}
