<?php

namespace App\Controllers;

use App\Models\PerizinanModel;
use App\Models\SantriModel;

class WaliController extends BaseController
{
    public function index()
    {
        $session = session();
        $user = $session->get();
        
        $santriModel = new SantriModel();
        $perizinanModel = new PerizinanModel();
        
        // Ambil data santri yang diwalikan oleh user ini
        $santri = $santriModel->where('wali_user_id', $user['id'])->findAll();
        
        // Ambil riwayat/tiket perizinan untuk santri-santri tersebut
        $santriIds = array_column($santri, 'id');
        $perizinan = [];
        if (!empty($santriIds)) {
            $perizinan = $perizinanModel->whereIn('santri_id', $santriIds)->orderBy('created_at', 'DESC')->findAll();
        }
        
        $data = [
            'user' => $user,
            'santri' => $santri,
            'perizinan' => $perizinan
        ];
        return view('wali/dashboard', $data);
    }

    public function submit()
    {
        $perizinanModel = new PerizinanModel();
        $session = session();
        
        $kode_izin = 'REQ-' . time(); // Simple unique code
        
        $data = [
            'kode_izin' => $kode_izin,
            'santri_id' => $this->request->getPost('santri_id'),
            'pembuat_user_id' => $session->get('id'),
            'sumber_izin' => 'wali',
            'kategori_izin' => $this->request->getPost('category'),
            'tgl_mulai' => $this->request->getPost('tgl_mulai'),
            'tgl_kembali_rencana' => $this->request->getPost('tgl_kembali_rencana'),
            'alasan' => $this->request->getPost('alasan'),
            'status_approval' => 'pending',
            'status_gerbang' => 'belum_keluar'
        ];
        
        $perizinanModel->insert($data);
        
        return redirect()->to('/wali')->with('success', 'Pengajuan berhasil dikirim.');
    }
}
