<?php

namespace App\Http\Controllers;

use App\Models\Santri;
use App\Models\User;
use App\Models\Kelas;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Http\Requests\StoreSantriRequest;
use App\Http\Requests\UpdateSantriRequest;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\SantrisImport;

class SantriController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $search = $request->input('search');
        $santris = Santri::query();

        if ($search) {
            $santris->where('nama', 'like', '%' . $search . '%');
        }

        $santris = $santris->paginate(10);
        $view = auth()->user()->isGuru() ? 'guru.santris.index' : 'santris.index';
        return view($view, compact('santris', 'search'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $kelas = Kelas::all();
        $nisBaru = Santri::generateNis();
        $view = auth()->user()->isGuru() ? 'guru.santris.create' : 'santris.create';
        return view($view, compact('kelas', 'nisBaru'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreSantriRequest $request)
    {
        $validated = $request->validated();

        DB::transaction(function () use ($validated) {
            $nisBaru = Santri::generateNis();

            $user = User::create([
                'name' => $validated['nama'],
                'username' => $nisBaru,
                'password' => bcrypt($nisBaru),
                'role' => 'santri',
                'status' => 'aktif',
            ]);

            $data = [
                'user_id' => $user->id,
                'nama' => $validated['nama'],
                'nis' => $nisBaru,
                'kelas_id' => $validated['kelas_id'],
                'alamat' => $validated['alamat'],
                'no_telp' => $validated['no_telp'],
                'tanggal_lahir' => $validated['tanggal_lahir'],
                'jenis_kelamin' => $validated['jenis_kelamin'],
            ];

            if (request()->hasFile('foto')) {
                $data['foto'] = request()->file('foto')->store('santri', 'public');
            }

            Santri::create($data);
        });

        return redirect()->route('santris.index')->with('success', 'Santri dan akun pengguna berhasil ditambahkan');
    }

    /**
     * Display the specified resource.
     */
    public function show(Santri $santri)
    {
        $view = auth()->user()->isGuru() ? 'guru.santris.show' : 'santris.show';
        return view($view, compact('santri'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Santri $santri)
    {
        $kelas = Kelas::all();
        $view = auth()->user()->isGuru() ? 'guru.santris.edit' : 'santris.edit';
        return view($view, compact('santri', 'kelas'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateSantriRequest $request, Santri $santri)
    {
        $data = $request->validated();

        if ($request->hasFile('foto')) {
            if ($santri->foto && \Storage::disk('public')->exists($santri->foto)) {
                \Storage::disk('public')->delete($santri->foto);
            }
            $data['foto'] = $request->file('foto')->store('santri', 'public');
        }

        $santri->update($data);
        return redirect()->route('santris.index')->with('success', 'Santri berhasil diupdate');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Santri $santri)
    {
        $santri->delete();
        return redirect()->route('santris.index')->with('success', 'Santri berhasil dihapus');
    }

    public function importStore(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xlsx,csv,xls',
        ]);
        Excel::import(new SantrisImport, $request->file('file'));
        return redirect()->route('santris.index')->with('success', 'Santri berhasil diimport.');
    }

    public function import()
    {
        return view('santris.import');
    }
}
