<?php

namespace App\Controllers;

use App\Models\PerizinanModel;
use App\Models\LogGerbangModel;

class SatpamController extends BaseController
{
    protected $perizinanModel;
    protected $logGerbangModel;

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

    public function dashboard()
    {
        return view('satpam/dashboard', [
            'title' => 'Scanner Gerbang Satpam - Sistem Perizinan IBK',
        ]);
    }

    public function log()
    {
        // Get all log gerbang history
        $logs = $this->logGerbangModel->db->table('log_gerbang')
            ->select('log_gerbang.*, perizinan.token_izin, perizinan.jenis_izin, santri.nama as santri_nama, santri.nis as santri_nis, users.nama_lengkap as petugas_nama')
            ->join('perizinan', 'perizinan.id = log_gerbang.perizinan_id')
            ->join('santri', 'santri.id = perizinan.santri_id')
            ->join('users', 'users.id = log_gerbang.petugas_id')
            ->orderBy('log_gerbang.waktu_scan', 'DESC')
            ->get()->getResultArray();

        return view('satpam/log', [
            'title' => 'Log Aktivitas Gerbang - Sistem Perizinan IBK',
            'logs'  => $logs,
        ]);
    }

    public function scan()
    {
        $token = trim($this->request->getPost('token_izin'));
        
        if (empty($token)) {
            return redirect()->to('/satpam/dashboard')->with('error', 'Token izin kosong.');
        }

        // Search permit
        $permit = $this->perizinanModel->getByToken($token);

        if (!$permit) {
            return redirect()->to('/satpam/dashboard')->with('error', 'Surat Izin dengan Token "' . esc($token) . '" TIDAK DITEMUKAN atau tidak valid.');
        }

        $now = date('Y-m-d H:i:s');
        $petugasId = session()->get('user_id');

        switch ($permit['status']) {
            case 'approved':
                // Check-out: mark active (outside)
                $this->perizinanModel->update($permit['id'], ['status' => 'active']);
                
                // Record gate log
                $this->logGerbangModel->insert([
                    'perizinan_id' => $permit['id'],
                    'waktu_scan'   => $now,
                    'jenis_scan'   => 'keluar',
                    'petugas_id'   => $petugasId
                ]);

                return redirect()->to('/satpam/dashboard')->with('success', 'VALIDASI BERHASIL: Santri "' . $permit['santri_nama'] . '" diizinkan KELUAR pondok.');

            case 'active':
                // Check-in: mark done (returned)
                $this->perizinanModel->update($permit['id'], ['status' => 'done']);

                // Record gate log
                $this->logGerbangModel->insert([
                    'perizinan_id' => $permit['id'],
                    'waktu_scan'   => $now,
                    'jenis_scan'   => 'masuk',
                    'petugas_id'   => $petugasId
                ]);

                return redirect()->to('/satpam/dashboard')->with('success', 'VALIDASI BERHASIL: Santri "' . $permit['santri_nama'] . '" terdaftar KEMBALI masuk pondok.');

            case 'pending':
                return redirect()->to('/satpam/dashboard')->with('error', 'VALIDASI GAGAL: Perizinan santri "' . $permit['santri_nama'] . '" masih MENUNGGU persetujuan kesantrian.');

            case 'rejected':
                return redirect()->to('/satpam/dashboard')->with('error', 'VALIDASI GAGAL: Perizinan santri "' . $permit['santri_nama'] . '" telah DITOLAK oleh kesantrian.');

            case 'done':
                return redirect()->to('/satpam/dashboard')->with('error', 'VALIDASI GAGAL: Surat izin untuk "' . $permit['santri_nama'] . '" sudah SELESAI digunakan (expired).');

            default:
                return redirect()->to('/satpam/dashboard')->with('error', 'Status perizinan tidak dikenali.');
        }
    }
}
