<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Cameraqrscan extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('DynamicModel', 'dm');

        // Cek apakah user sudah login
        if (!$this->session->userdata('logged_in')) {
            redirect('login');
        }
    }

    public function index($type = 'masuk')
    {
        // pastikan hanya masuk/keluar
        $type = strtolower($type);
        if (!in_array($type, ['masuk', 'keluar'])) {
            show_404();
            return;
        }

        $data = [
            "active_menu" => "",
            "scan_type"   => $type  // passing ke view
        ];

        $this->load->view('partials/header', $data);
        $this->load->view('scan/qr_scan', $data);
        $this->load->view('partials/footer');
    }

    public function get_data()
    {
        $qr_code   = $this->input->post('qr_code');
        $scan_type = $this->input->post('scan_type'); // masuk / keluar

        if (!$qr_code) {
            echo json_encode(['status' => false, 'message' => 'QR Code tidak ditemukan']);
            return;
        }

        // ============================================================
        // AMBIL DATA SISWA
        // ============================================================
        $siswa = $this->db->get_where('v_siswa', ['qr_id' => $qr_code])->row_array();

        if (!$siswa) {
            echo json_encode([
                'status' => false,
                'message' => 'Data siswa tidak ditemukan'
            ]);
            return;
        }

        $id_siswa = $siswa['id'];
        $id_kelas = $siswa['id_kelas'];
        $id_kamar = $siswa['id_kamar'];

        // ============================================================
        // CEGAH DUPLIKAT 5 MENIT (PostgreSQL)
        // ============================================================
        // Hitung waktu 5 menit yang lalu
        $datetimeNow = date('Y-m-d H:i:s');
        $datetime5MenitLalu = date('Y-m-d H:i:s', strtotime('-5 minutes'));

        $cek = $this->db->query("
            SELECT id 
            FROM kunjungan 
            WHERE id_siswa = ?
              AND created_at >= ?
            ORDER BY created_at DESC
            LIMIT 1
        ", [$id_siswa, $datetime5MenitLalu])->row_array();

        if ($cek) {
            echo json_encode([
                'status' => true,
                'data'   => $siswa,
                'scan_type' => $scan_type,
                'message' => "Sudah tercatat dalam 5 menit terakhir"
            ]);
            return;
        }

        // ============================================================
        // AMBIL TEMPLATE PESAN
        // ============================================================
        $template = $this->db->get_where('template_pesan', ['jenis' => $scan_type])->row_array();

        if (!$template) {
            echo json_encode([
                'status' => false,
                'message' => 'Template pesan tidak ditemukan => ' . $scan_type
            ]);
            return;
        }

        $pesan = $template['isi_template'];
        $pesanType = $template['type'];


        // ============================================================
        // REPLACE TEMPLATE {{column}}
        // ============================================================
        foreach ($siswa as $key => $value) {
            $pesan = str_replace('{{'.$key.'}}', $value, $pesan);
        }

        // Tambahan otomatis
        $pesan = str_replace('{{tanggal}}', date('Y-m-d'), $pesan);
        $pesan = str_replace('{{jam}}', date('H:i:s'), $pesan);


        // ============================================================
        // INSERT KUNJUNGAN
        // ============================================================
        $this->db->insert('kunjungan', [
            'id_siswa'   => $id_siswa,
            'type'       => $scan_type,
            'id_users'   => $this->session->userdata('user_id'),
            'id_kelas'   => $id_kelas,
            'id_kamar'   => $id_kamar,
            'created_at' => date('Y-m-d H:i:s'),
            'media_type' => 'qr'
        ]);

        $new_id = $this->db->insert_id();


        // ============================================================
        // INSERT NOTIFIKASI WA
        // ============================================================
        $this->db->insert('notifikasi', [
            'type'           => $pesanType,
            'pesan'          => $pesan,
            'status'         => 'pending',
            'nomor_whatsapp' => $siswa['nomor_whatsapp'],
            'created_at'     => date('Y-m-d H:i:s'),
        ]);


        // ============================================================
        // RESPONSE
        // ============================================================
        $info = ($scan_type === 'masuk')
            ? "Berhasil scan MASUK"
            : "Berhasil scan KELUAR";

        // tampilkan data lengkap dari v_kunjungan
        $dataSiswa = $this->db->get_where('v_kunjungan_detail', ['id' => $new_id])->row();

        echo json_encode([
            'status' => true,
            'data'   => $dataSiswa,
            'scan_type' => $scan_type,
            'message' => $info
        ]);
    }


}
