<?php

namespace App\Controllers;

use App\Models\SantriModel;
use App\Models\UserModel;

class SantriController extends BaseController
{
    public function index()
    {
        $santriModel = new SantriModel();
        $userModel = new UserModel();

        // Get all santri
        $santri = $santriModel->findAll();
        
        // Get all wali for dropdown when adding/editing
        $waliUsers = $userModel->where('role', 'wali')->findAll();

        $data = [
            'santri' => $santri,
            'waliUsers' => $waliUsers,
            'user' => session()->get()
        ];

        return view('kesantrian/students', $data);
    }

    public function store()
    {
        $santriModel = new SantriModel();

        $data = [
            'nis' => $this->request->getPost('nis'),
            'nama_santri' => $this->request->getPost('nama_santri'),
            'asrama' => $this->request->getPost('asrama'),
            'kelas' => $this->request->getPost('kelas'),
            'wali_user_id' => $this->request->getPost('wali_user_id'),
        ];

        $santriModel->insert($data);

        return redirect()->to('/santri')->with('success', 'Data santri berhasil ditambahkan.');
    }

    public function update($id)
    {
        $santriModel = new SantriModel();

        $data = [
            'nis' => $this->request->getPost('nis'),
            'nama_santri' => $this->request->getPost('nama_santri'),
            'asrama' => $this->request->getPost('asrama'),
            'kelas' => $this->request->getPost('kelas'),
            'wali_user_id' => $this->request->getPost('wali_user_id'),
        ];

        $santriModel->update($id, $data);

        return redirect()->to('/santri')->with('success', 'Data santri berhasil diperbarui.');
    }

    public function delete($id)
    {
        $santriModel = new SantriModel();
        $santriModel->delete($id);

        return redirect()->to('/santri')->with('success', 'Data santri berhasil dihapus.');
    }
}
