<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Kelas;
// DidikPokok may not exist in some installs; reference conditionally later

class PendukungController extends Controller
{
    public function walimurid()
    {
        try {
            if (auth()->check() && (optional(auth()->user())->role ?? '') === 'guru') {
                $kelasList = Kelas::where('walikelas_id', auth()->id())->orderBy('nama')->get();
            } else {
                $kelasList = Kelas::orderBy('nama')->get();
            }
        } catch (\Throwable $e) {
            $kelasList = collect();
        }

        $selected = null;
        $pesertas = collect();

        // support optional GET param `kelas_id` to filter peserta
        if (request()->filled('kelas_id')) {
            try {
                $selected = Kelas::find(request('kelas_id'));
            } catch (\Throwable $e) {
                $selected = null;
            }
        } elseif (auth()->check() && (optional(auth()->user())->role ?? '') === 'guru') {
            try {
                $selected = Kelas::where('walikelas_id', auth()->id())->first();
            } catch (\Throwable $e) {
                $selected = null;
            }
        }

        if ($selected && class_exists(\App\Models\DidikPokok::class)) {
            try {
                $q = \App\Models\DidikPokok::where('kelas', $selected->nama);
                if (!is_null($selected->rombel)) {
                    $q->where('rombel', $selected->rombel);
                }
                if (!is_null($selected->fase)) {
                    $q->where('fase', $selected->fase);
                }
                $pesertas = $q->orderBy('nama')->get();
            } catch (\Throwable $e) {
                $pesertas = collect();
            }
        }

        $prefix = request()->is('guru/*') ? 'guru' : 'admin';
        return view($prefix . '.pendukung.walimurid.index', compact('kelasList', 'selected', 'pesertas'));
    }

    public function kehadiran()
    {
        try {
            if (auth()->check() && (optional(auth()->user())->role ?? '') === 'guru') {
                $kelasList = \App\Models\Kelas::where('walikelas_id', auth()->id())->orderBy('nama')->get();
            } else {
                $kelasList = \App\Models\Kelas::orderBy('nama')->get();
            }
        } catch (\Throwable $e) {
            $kelasList = collect();
        }

        $selected = null;
        $pesertas = collect();

        if (request()->filled('kelas_id')) {
            try {
                $selected = \App\Models\Kelas::find(request('kelas_id'));
            } catch (\Throwable $e) {
                $selected = null;
            }
        } elseif (auth()->check() && (optional(auth()->user())->role ?? '') === 'guru') {
            try {
                $selected = \App\Models\Kelas::where('walikelas_id', auth()->id())->first();
            } catch (\Throwable $e) {
                $selected = null;
            }
        }

        if ($selected && class_exists(\App\Models\DidikPokok::class)) {
            try {
                $q = \App\Models\DidikPokok::where('kelas', $selected->nama);
                if (!is_null($selected->rombel)) {
                    $q->where('rombel', $selected->rombel);
                }
                if (!is_null($selected->fase)) {
                    $q->where('fase', $selected->fase);
                }
                $pesertas = $q->orderBy('nama')->get();
            } catch (\Throwable $e) {
                $pesertas = collect();
            }
        }

        $prefix = request()->is('guru/*') ? 'guru' : 'admin';
        return view($prefix . '.pendukung.kehadiran.index', compact('kelasList', 'selected', 'pesertas'));
    }

    public function updateKehadiran(Request $request)
    {
        $request->validate([
            'kelas_id' => 'required|integer',
            'attendance' => 'required|array',
        ]);

        $attendance = $request->input('attendance', []);
        $errors = 0;

        foreach ($attendance as $id => $vals) {
            try {
                $p = \App\Models\DidikPokok::findOrFail($id);
                $data = [
                    'sakit' => isset($vals['sakit']) ? (int)$vals['sakit'] : 0,
                    'ijin' => isset($vals['ijin']) ? (int)$vals['ijin'] : 0,
                    'tanpa_keterangan' => isset($vals['tanpa_keterangan']) ? (int)$vals['tanpa_keterangan'] : 0,
                ];
                $p->update($data);
            } catch (\Throwable $e) {
                $errors++;
            }
        }

        if ($errors > 0) {
            return redirect()->back()->withErrors('Beberapa baris gagal disimpan.');
        }

        return redirect()->back()->with('status', 'Kehadiran berhasil disimpan.');
    }

    // --- Walimurid CRUD stubs ---
    public function create()
    {
        // Simply show a minimal create page or redirect back if create is not used
        $prefix = request()->is('guru/*') ? 'guru' : 'admin';
        return view($prefix . '.pendukung.walimurid.create');
    }

    public function store(Request $request)
    {
        // Placeholder: no model available for walimurid. Redirect back with info.
        return redirect()->back()->with('status', 'Store action not implemented.');
    }

    public function edit($id)
    {
        // try to load the peserta (didik_pokok) record so the form can be populated
        $p = null;
        try {
            $p = \App\Models\DidikPokok::findOrFail($id);
        } catch (\Throwable $e) {
            return redirect()->back()->withErrors('Peserta tidak ditemukan');
        }

        $prefix = request()->is('guru/*') ? 'guru' : 'admin';
        return view($prefix . '.pendukung.walimurid.edit', compact('p'));
    }

    public function update(Request $request, $id)
    {
        // Validate common guardian fields; adjust rules if table differs
        $data = $request->validate([
            'nama_ayah' => 'nullable|string|max:255',
            'pekerjaan_ayah' => 'nullable|string|max:255',
            'nama_ibu' => 'nullable|string|max:255',
            'pekerjaan_ibu' => 'nullable|string|max:255',
            'alamat' => 'nullable|string',
            'nomor_hp' => 'nullable|string|max:50',
            'tempat_lahir' => 'nullable|string|max:255',
            'tanggal_lahir' => 'nullable|date',
        ]);

        try {
            $p = \App\Models\DidikPokok::findOrFail($id);
            // Only update fields that exist on the model/table
            $p->fill($data);
            $p->save();
            $base = request()->is('guru/*') ? 'guru' : 'admin';
            return redirect(url($base . '/pendukung/walimurid'))->with('status', 'Data wali murid berhasil diperbarui.');
        } catch (\Throwable $e) {
            return redirect()->back()->withErrors('Gagal memperbarui data.');
        }
    }

    public function destroy($id)
    {
        // Placeholder destroy
        return redirect()->back()->with('status', 'Destroy action not implemented.');
    }
}
