<?php

namespace App\Controllers;

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

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

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

    public function dashboard()
    {
        $waliId = session()->get('user_id');

        // Get children (santri)
        $children = $this->santriModel->getByWali($waliId);
        
        // Get permits history
        $permits = $this->perizinanModel->getByWali($waliId);

        // Count states
        $counts = [
            'aktif'   => 0,
            'pending' => 0,
            'total'   => count($permits)
        ];

        foreach ($permits as $p) {
            if ($p['status'] === 'active') {
                $counts['aktif']++;
            } elseif ($p['status'] === 'pending') {
                $counts['pending']++;
            }
        }

        return view('wali/dashboard', [
            'title'    => 'Dashboard Wali Santri - Sistem Perizinan IBK',
            'children' => $children,
            'permits'  => $permits,
            'counts'   => $counts,
        ]);
    }

    public function riwayat()
    {
        $waliId = session()->get('user_id');
        $permits = $this->perizinanModel->getByWali($waliId);

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

    public function pengajuan()
    {
        $waliId = session()->get('user_id');
        $children = $this->santriModel->getByWali($waliId);

        return view('wali/pengajuan', [
            'title'    => 'Ajukan Izin - Sistem Perizinan IBK',
            'children' => $children,
        ]);
    }

    public function submitPengajuan()
    {
        $waliId = session()->get('user_id');
        $santriId = $this->request->getPost('santri_id');
        
        // Security check: Verify the santri belongs to this Wali
        $santri = $this->santriModel->where('id', $santriId)->where('wali_id', $waliId)->first();
        if (!$santri) {
            return redirect()->to('/wali/pengajuan')->with('error', 'Data santri tidak valid.');
        }

        // 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('/wali/pengajuan')->withInput()->with('error', 'Gagal mengajukan izin: ' . implode(' ', $validation->getErrors()));
        }

        $waktuKeluar = $this->request->getPost('waktu_keluar');
        $waktuKembali = $this->request->getPost('waktu_kembali');

        // Logical Validation: Waktu kembali must be after waktu keluar
        if (strtotime($waktuKembali) <= strtotime($waktuKeluar)) {
            return redirect()->to('/wali/pengajuan')->withInput()->with('error', 'Waktu kembali harus setelah waktu keluar.');
        }

        // Generate secure token
        $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($waktuKeluar)),
            'waktu_kembali' => date('Y-m-d H:i:s', strtotime($waktuKembali)),
            'alasan'        => $this->request->getPost('alasan'),
            'status'        => 'pending',
            'token_izin'    => $token,
            'created_by'    => $waliId,
        ];

        try {
            if ($this->perizinanModel->insert($data)) {
                return redirect()->to('/wali/riwayat')->with('success', 'Pengajuan perizinan berhasil dikirim. Silakan tunggu persetujuan Kesantrian.');
            }
            return redirect()->to('/wali/pengajuan')->withInput()->with('error', 'Terjadi kesalahan sistem saat menyimpan data.');
        } catch (\Exception $e) {
            log_message('error', '[Submit Izin Error] ' . $e->getMessage());
            return redirect()->to('/wali/pengajuan')->withInput()->with('error', 'Terjadi kesalahan internal server.');
        }
    }

    public function viewPermit($id)
    {
        $waliId = session()->get('user_id');
        $permit = $this->perizinanModel->getDetailed($id);

        if (!$permit) {
            return redirect()->to('/wali/dashboard')->with('error', 'Surat izin tidak ditemukan.');
        }

        // Security check: Verify the santri belongs to this Wali
        $santri = $this->santriModel->where('id', $permit['santri_id'])->where('wali_id', $waliId)->first();
        if (!$santri) {
            return redirect()->to('/wali/dashboard')->with('error', 'Akses ditolak.');
        }

        return view('wali/permit_details', [
            'title'  => 'Surat Izin Digital - ' . $permit['santri_nama'],
            'permit' => $permit
        ]);
    }
}
