<?php

namespace App\Http\Controllers\Admin\DataUmum;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Sekolah;

class SekolahController extends Controller
{
    public function store(Request $request)
    {
        $data = $request->validate([
            'nama' => 'required|string|max:255',
            'nss' => 'nullable|string|max:100',
            'npsn' => 'nullable|string|max:50',
            'tanggal_rapot_1' => 'nullable|string|max:255',
            'tanggal_rapot_2' => 'nullable|string|max:255',
            'kepala_sekolah' => 'nullable|string|max:255',
            'nip' => 'nullable|string|max:50',
            'alamat' => 'nullable|string',
            'kelurahan' => 'nullable|string|max:150',
            'kecamatan' => 'nullable|string|max:150',
            'kota_kabupaten' => 'nullable|string|max:150',
            'provinsi' => 'nullable|string|max:150',
            'telepon' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
        ]);

        try {
            $sekolah = Sekolah::create($data);
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Gagal menyimpan sekolah: ' . $e->getMessage());
        }

        return redirect()->back()->with('success', 'Sekolah berhasil ditambahkan.');
    }

    public function update(Request $request, $id)
    {
        $sekolah = Sekolah::findOrFail($id);

        $data = $request->validate([
            'nama' => 'required|string|max:255',
            'nss' => 'nullable|string|max:100',
            'npsn' => 'nullable|string|max:50',
            'tanggal_rapot_1' => 'nullable|string|max:255',
            'tanggal_rapot_2' => 'nullable|string|max:255',
            'kepala_sekolah' => 'nullable|string|max:255',
            'nip' => 'nullable|string|max:50',
            'alamat' => 'nullable|string',
            'kelurahan' => 'nullable|string|max:150',
            'kecamatan' => 'nullable|string|max:150',
            'kota_kabupaten' => 'nullable|string|max:150',
            'provinsi' => 'nullable|string|max:150',
            'telepon' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
        ]);

        $sekolah->update($data);

        return redirect()->back()->with('success', 'Sekolah berhasil diperbarui.');
    }

    public function destroy($id)
    {
        $sekolah = Sekolah::findOrFail($id);
        $sekolah->delete();

        return redirect()->back()->with('success', 'Sekolah berhasil dihapus.');
    }
}
