<?php

namespace App\Controllers;

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

class KesantrianController extends BaseController
{
    protected $santriModel;
    protected $perizinanModel;

    public function __construct()
    {
        $this->santriModel = new SantriModel();
        $this->perizinanModel = new PerizinanModel();
    }

    public function dashboard()
    {
        // Get detailed list of all perizinan
        $permits = $this->perizinanModel->getDetailed();
        
        $pendingPermits = [];
        foreach ($permits as $p) {
            if ($p['status'] === 'pending') {
                $pendingPermits[] = $p;
            }
        }

        return view('kesantrian/dashboard', [
            'title'          => 'Dashboard Kesantrian - Sistem Perizinan IBK',
            'pendingPermits' => $pendingPermits,
        ]);
    }

    public function riwayat()
    {
        $permits = $this->perizinanModel->getDetailed();
        
        $otherPermits = [];
        foreach ($permits as $p) {
            if ($p['status'] !== 'pending') {
                $otherPermits[] = $p;
            }
        }

        return view('kesantrian/riwayat', [
            'title'        => 'Riwayat Perizinan - Sistem Perizinan IBK',
            'otherPermits' => $otherPermits,
        ]);
    }

    public function formBypass()
    {
        $santri = $this->santriModel->orderBy('nama', 'ASC')->findAll();

        return view('kesantrian/bypass', [
            'title'      => 'Bypass Izin Darurat - Sistem Perizinan IBK',
            'santriList' => $santri,
        ]);
    }

    public function approve($id)
    {
        $permit = $this->perizinanModel->find($id);
        if (!$permit) {
            return redirect()->to('/kesantrian/dashboard')->with('error', 'Data perizinan tidak ditemukan.');
        }

        $this->perizinanModel->update($id, ['status' => 'approved']);
        return redirect()->to('/kesantrian/dashboard')->with('success', 'Perizinan santri berhasil disetujui.');
    }

    public function reject($id)
    {
        $permit = $this->perizinanModel->find($id);
        if (!$permit) {
            return redirect()->to('/kesantrian/dashboard')->with('error', 'Data perizinan tidak ditemukan.');
        }

        $reason = $this->request->getPost('catatan_tolak');
        if (empty($reason)) {
            return redirect()->to('/kesantrian/dashboard')->with('error', 'Alasan penolakan harus diisi.');
        }

        $this->perizinanModel->update($id, [
            'status'        => 'rejected',
            'catatan_tolak' => $reason
        ]);
        
        return redirect()->to('/kesantrian/dashboard')->with('success', 'Perizinan santri berhasil ditolak.');
    }

    public function bypass()
    {
        // Direct Creation by Kesantrian
        $santriId = $this->request->getPost('santri_id');
        $santri = $this->santriModel->find($santriId);
        if (!$santri) {
            return redirect()->to('/kesantrian/form-bypass')->with('error', 'Data santri tidak ditemukan.');
        }

        // Validate
        $validation = \Config\Services::validation();
        $validation->setRules([
            'jenis_izin'    => 'required|min_length[3]|max_length[100]',
            'waktu_keluar'  => 'required|valid_date[Y-m-d\TH:i]',
            'waktu_kembali' => 'required|valid_date[Y-m-d\TH:i]',
            'alasan'        => 'required|min_length[5]',
        ]);

        if (!$validation->withRequest($this->request)->run()) {
            return redirect()->to('/kesantrian/form-bypass')->with('error', 'Gagal membuat perizinan: ' . implode(' ', $validation->getErrors()));
        }

        $token = 'IZN-' . strtoupper(bin2hex(random_bytes(6)));

        $data = [
            'santri_id'     => $santriId,
            'jenis_izin'    => $this->request->getPost('jenis_izin'),
            'waktu_keluar'  => date('Y-m-d H:i:s', strtotime($this->request->getPost('waktu_keluar'))),
            'waktu_kembali' => date('Y-m-d H:i:s', strtotime($this->request->getPost('waktu_kembali'))),
            'alasan'        => $this->request->getPost('alasan'),
            'status'        => 'approved', // Directly approved/active ready for scan
            'token_izin'    => $token,
            'created_by'    => session()->get('user_id'),
        ];

        if ($this->perizinanModel->insert($data)) {
            return redirect()->to('/kesantrian/riwayat')->with('success', 'Perizinan bypass mandiri berhasil dibuat.');
        }

        return redirect()->to('/kesantrian/form-bypass')->with('error', 'Gagal menyimpan perizinan.');
    }

    public function monitoring()
    {
        // Get all active licenses (santri currently outside)
        $detailed = $this->perizinanModel->getDetailed();
        
        $activeList = [];
        $overdueCount = 0;
        $now = time();

        foreach ($detailed as $p) {
            if ($p['status'] === 'active') {
                $returnTime = strtotime($p['waktu_kembali']);
                $p['is_overdue'] = ($now > $returnTime);
                if ($p['is_overdue']) {
                    $overdueCount++;
                }
                $activeList[] = $p;
            }
        }

        return view('kesantrian/monitoring', [
            'title'        => 'Monitoring Real-time Santri - Sistem Perizinan IBK',
            'activeList'   => $activeList,
            'overdueCount' => $overdueCount,
        ]);
    }
}
