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

class Tracking_model extends CI_Model
{
    public function get_tracking_data($filters = [])
    {
        $this->db->select('
            r.registrasi_id,
            r.tanggal_registrasi,
            r.jam_registrasi,
            r.created_at as waktu_mulai_registrasi,
            r.updated_at as waktu_selesai_registrasi,
            p.nama_lengkap as nama_pasien,
            p.rme_no,
            poli.nama_poli,
            dokter.nama_lengkap as nama_dokter,
            petugas.nama_lengkap as nama_petugas,
            petugas_pj.nama_lengkap as nama_petugas_pj,
            r.status_registrasi,
            r.status_kehadiran,
            TIMESTAMPDIFF(MINUTE, r.created_at, r.updated_at) as durasi_menit
        ');
        
        $this->db->from('tb_registrasi r');
        $this->db->join('tb_pasien p', 'r.id_pasien = p.pasien_id');
        $this->db->join('tb_poli poli', 'r.id_poli = poli.poli_id');
        $this->db->join('tb_dokter d', 'r.id_dokter = d.dokter_id', 'left');
        $this->db->join('tb_petugas dokter', 'd.id_petugas = dokter.petugas_id', 'left');
        $this->db->join('tb_petugas petugas', 'r.id_petugas = petugas.petugas_id', 'left');
        $this->db->join('tb_petugas petugas_pj', 'r.id_petugas_pj = petugas_pj.petugas_id', 'left');

        // Apply filters
        if (!empty($filters['start_date'])) {
            $this->db->where('DATE(r.created_at) >=', $filters['start_date']);
        }
        
        if (!empty($filters['end_date'])) {
            $this->db->where('DATE(r.created_at) <=', $filters['end_date']);
        }
        
        if (!empty($filters['id_petugas'])) {
            $this->db->where('r.id_petugas', $filters['id_petugas']);
        }
        
        if (!empty($filters['id_petugas_pj'])) {
            $this->db->where('r.id_petugas_pj', $filters['id_petugas_pj']);
        }

        $this->db->order_by('r.created_at', 'DESC');
        
        return $this->db->get()->result();
    }

    public function get_all_petugas()
    {
        return $this->db->select('petugas_id, nama_lengkap')
                       ->where('status_aktif', 1)
                       ->get('tb_petugas')
                       ->result();
    }
}
