<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Guru;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;

class GuruController extends Controller
{
    protected function storagePath()
    {
        return env('STORAGE_PATH', public_path('penyimpanan'));
    }

    public function index()
    {
        $data = Guru::orderBy('id_guru', 'desc')->paginate(15);
        return view('admin.guru', compact('data'));
    }

    public function create()
    {
        return view('admin.form-guru');
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama' => 'required|string|max:255',
            'nip_nuptk' => 'required|numeric|digits_between:0,18|unique:guru,nip_nuptk',
            'mata_pelajaran' => 'nullable|string|max:100',
            'foto' => 'nullable|image|mimes:jpg,jpeg,png,gif,bmp,webp',
            'tanggal_lahir' => 'nullable|date',
            'tanggal_masuk' => 'nullable|date',
            'jenis_kelamin' => 'required|in:Laki-laki,Perempuan',
        ]);

        $data = $request->all();
        $data['id_user'] = Auth::id();
        
        $storagePath = $this->storagePath();

        // Handle upload foto
        if ($request->hasFile('foto')) {
            if (!file_exists($storagePath . '/foto_guru')) {
                mkdir($storagePath . '/foto_guru', 0755, true);
            }
            $filename = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $request->file('foto')->getClientOriginalName());
            $request->file('foto')->move($storagePath . '/foto_guru', $filename);
            $data['foto'] = 'foto_guru/' . $filename;
        }

        Guru::create($data);

        return redirect()->route('guru.index')->with('success', 'Data berhasil ditambahkan');
    }

    public function edit($id_guru)
    {
        $guru = Guru::findOrFail($id_guru);
        return view('admin.edit-guru', compact('guru'));
    }

    public function update(Request $request, $id_guru)
    {
        $guru = Guru::findOrFail($id_guru);

        $request->validate([
            'nama' => 'required|string|max:255',
            'nip_nuptk' => 'required|numeric|digits_between:0,18|unique:guru,nip_nuptk,' .$id_guru . ',id_guru',
            'mata_pelajaran' => 'nullable|string|max:100',
            'foto' => 'nullable|image|mimes:jpg,jpeg,png,gif,bmp,webp',
            'tanggal_lahir' => 'nullable|date',
            'tanggal_masuk' => 'nullable|date',
            'jenis_kelamin' => 'required|in:Laki-laki,Perempuan',
        ]);

        $data = $request->all();
        $storagePath = $this->storagePath();

        // Handle upload foto baru
        if ($request->hasFile('foto')) {
            // Hapus foto lama jika ada
            if ($guru->foto && file_exists($storagePath . '/' . $guru->foto)) {
                unlink($storagePath . '/' . $guru->foto);
            }
            
            if (!file_exists($storagePath . '/foto_guru')) {
                mkdir($storagePath . '/foto_guru', 0755, true);
            }
            $filename = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $request->file('foto')->getClientOriginalName());
            $request->file('foto')->move($storagePath . '/foto_guru', $filename);
            $data['foto'] = 'foto_guru/' . $filename;
        } else {
            unset($data['foto']);
        }

        $guru->update($data);

        return redirect()->route('guru.index')->with('success', 'Data berhasil diupdate');
    }

    public function destroy($id_guru)
    {
        $guru = Guru::findOrFail($id_guru);
        
        $storagePath = $this->storagePath();
        if ($guru->foto && file_exists($storagePath . '/' . $guru->foto)) {
            unlink($storagePath . '/' . $guru->foto);
        }
        
        $guru->delete();
        return redirect()->route('guru.index')->with('success', 'Data berhasil dihapus');
    }
}