<?php

namespace App\Controllers;

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

class KesantrianController extends BaseController
{
    public function index()
    {
        $perizinanModel = new PerizinanModel();
        
        // Ambil semua perizinan pending
        $db = \Config\Database::connect();
        $builder = $db->table('perizinan');
        $builder->select('perizinan.*, santri.nama_santri, santri.kelas');
        $builder->join('santri', 'santri.id = perizinan.santri_id');
        $builder->where('perizinan.status_approval', 'pending');
        $builder->orderBy('perizinan.created_at', 'DESC');
        $pendingRequests = $builder->get()->getResultArray();
        
        $data = [
            'user' => session()->get(),
            'pending_requests' => $pendingRequests
        ];
        return view('kesantrian/dashboard', $data);
    }

    public function approve($id)
    {
        $perizinanModel = new PerizinanModel();
        
        // Generate QR Token
        $qr_token = bin2hex(random_bytes(16));
        
        $data = [
            'status_approval' => 'approved',
            'disetujui_oleh' => session()->get('id'),
            'qr_token' => $qr_token
        ];
        
        $perizinanModel->update($id, $data);
        
        return redirect()->to('/kesantrian')->with('success', 'Izin disetujui, QR Code diterbitkan.');
    }

    public function permits()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('perizinan');
        $builder->select('perizinan.*, santri.nama_santri, santri.kelas, users.nama_lengkap as wali_nama');
        $builder->join('santri', 'santri.id = perizinan.santri_id');
        $builder->join('users', 'users.id = perizinan.pembuat_user_id', 'left');
        $builder->orderBy('perizinan.created_at', 'DESC');
        $all_permits = $builder->get()->getResultArray();

        $data = [
            'user' => session()->get(),
            'permits' => $all_permits
        ];

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