<?php

namespace App\Controllers;

use App\Models\PerizinanModel;

class SatpamController extends BaseController
{
    public function index()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('perizinan');
        $builder->where('status_gerbang', 'diluar');
        $active_permits = $builder->countAllResults();

        $data = [
            'user' => session()->get(),
            'active_permits' => $active_permits
        ];
        return view('satpam/dashboard_main', $data);
    }

    public function scan()
    {
        $data = [
            'user' => session()->get()
        ];
        return view('satpam/dashboard', $data);
    }

    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->whereIn('perizinan.status_approval', ['approved']);
        $builder->orderBy('perizinan.created_at', 'DESC');
        $all_permits = $builder->get()->getResultArray();

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

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

    public function process_scan()
    {
        $token = $this->request->getJSON()->token ?? '';
        $action = $this->request->getJSON()->action ?? 'out'; // 'out' or 'in'
        
        if (empty($token)) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Token kosong.']);
        }
        
        $perizinanModel = new PerizinanModel();
        
        $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('qr_token', $token);
        $builder->where('status_approval', 'approved');
        
        $izin = $builder->get()->getRowArray();
        
        if (!$izin) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'QR Code tidak valid atau izin belum disetujui.']);
        }
        
        $updateData = [];
        $pesan = '';
        
        if ($action == 'out') {
            if ($izin['status_gerbang'] != 'belum_keluar') {
                return $this->response->setJSON(['status' => 'error', 'message' => 'Santri sudah keluar sebelumnya.']);
            }
            $updateData = [
                'status_gerbang' => 'diluar',
                'waktu_keluar_riil' => date('Y-m-d H:i:s'),
                'petugas_keluar_id' => session()->get('id')
            ];
            $pesan = "Berhasil Check-Out: " . $izin['nama_santri'];
        } else {
            if ($izin['status_gerbang'] != 'diluar') {
                return $this->response->setJSON(['status' => 'error', 'message' => 'Santri belum keluar atau sudah kembali.']);
            }
            
            // Cek apakah terlambat
            $batas_kembali = strtotime($izin['tgl_kembali_rencana']);
            $sekarang = time();
            $status_gerbang = ($sekarang > $batas_kembali) ? 'terlambat' : 'selesai';
            
            $updateData = [
                'status_gerbang' => $status_gerbang,
                'waktu_kembali_riil' => date('Y-m-d H:i:s'),
                'petugas_kembali_id' => session()->get('id')
            ];
            $pesan = "Berhasil Check-In: " . $izin['nama_santri'] . ($status_gerbang == 'terlambat' ? ' (Terlambat)' : '');
        }
        
        $perizinanModel->update($izin['id'], $updateData);
        
        return $this->response->setJSON([
            'status' => 'success',
            'message' => $pesan,
            'data' => [
                'nama' => $izin['nama_santri'],
                'kelas' => $izin['kelas'],
                'kategori' => $izin['kategori_izin']
            ]
        ]);
    }
}
