<?php

namespace App\Http\Controllers;

use App\Models\PertanyaanKuesioner;
use App\Models\Rujukan;
use App\Models\Spesialis;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class RujukanController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $data['rujukan'] = Rujukan::all();
        return view('tindak-lanjut.rujukan-spesialis.index', $data);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // dd($request->all());

        $request->validate([
            'id_siswa' => 'required|exists:siswas,id_siswa',
            'selected_siswa' => 'nullable|array',
            'selected_siswa.*' => 'exists:pertanyaan_kuesioners,id',
            'tujuan_rujukan' => 'required|in:Psikolog,Psikiater'
        ]);

        $permasalahan = [];
        if ($request->filled('selected_siswa')) {
            $permasalahan = PertanyaanKuesioner::whereIn('id', $request->selected_siswa)
                ->pluck('pertanyaan')
                ->toArray();
        }

        $lastSurat = Rujukan::whereYear('created_at', now()->year)
            ->orderByDesc('id_rujukan')
            ->first();

        $lastNumber = 0;
        if ($lastSurat && preg_match('/^\d+/', $lastSurat->nomor_surat, $matches)) {
            $lastNumber = (int) $matches[0];
        }

        $newNumber = str_pad($lastNumber + 1, 3, '0', STR_PAD_LEFT);
        $bulanRomawi = [1 => 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII'];
        $nomorSurat = $newNumber . '/BK/SMKN1BJP/' . $bulanRomawi[date('n')] . '/' . date('Y');

        Rujukan::create([
            'id_siswa' => $request->id_siswa,
            'permasalahan' => implode("\n", $permasalahan),
            'tujuan_rujukan' => $request->tujuan_rujukan,
            'nomor_surat' => $nomorSurat
        ]);

        return redirect()->route('tindak-lanjut.rujukan-spesialis.index')
            ->with([
                'message' => "Data rujukan berhasil dibuat",
                'alert-type' => 'success'
            ]);
    }

    public function show(string $id)
    {
        //
    }

    public function edit(string $id)
    {
        //
    }


    public function update(Request $request, string $id_rujukan)
    {
        $rujukan = Rujukan::findOrFail($id_rujukan);

        $validated = $request->validate([
            'id_siswa' => 'required|exists:siswas,id_siswa',
            'selected_siswa' => 'required|array',
            'selected_siswa.*' => 'exists:pertanyaan_kuesioners,id',
            'tujuan_rujukan' => 'required|in:Psikolog,Psikiater'
        ]);

        // Get the selected questions text
        $permasalahan = [];
        foreach ($request->selected_siswa as $pertanyaanId) {
            $pertanyaan = PertanyaanKuesioner::find($pertanyaanId);
            if ($pertanyaan) {
                $permasalahan[] = $pertanyaan->pertanyaan;
            }
        }

        $rujukan->update([
            'id_siswa' => $request->id_siswa,
            'permasalahan' => implode("\n", $permasalahan),
            'tujuan_rujukan' => $request->tujuan_rujukan,
        ]);

        $notification = array(
            'message' => "Data rujukan berhasil dibuat",
            'alert-type' => 'success'
        );

        return redirect()->route('tindak-lanjut.rujukan-spesialis.index')
            ->with($notification);
    }

    public function destroy(string $id_rujukan)
    {
        $rujukan = Rujukan::findOrFail($id_rujukan);

        $rujukan->delete();

        $notificaton = array(
            'message' => 'Data rujukan berhasil dihapus',
            'alert-type' => 'success'
        );

        return redirect()->route('tindak-lanjut.rujukan-spesialis.index')->with($notificaton);
    }

    public function print($id_rujukan)
    {
        $rujukan = Rujukan::with('siswa')->findOrFail($id_rujukan);

        $template = strtolower($rujukan->tujuan_rujukan) === 'psikiater'
            ? 'tindak-lanjut.rujukan-spesialis.komponen.print-psikiater'
            : 'tindak-lanjut.rujukan-spesialis.komponen.print-psikolog';

        $pdf = Pdf::loadView($template, compact('rujukan'))
            ->setPaper('A4', 'portrait');

        return $pdf->stream('Surat Rujukan.pdf');
    }
}
