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

class Loket extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->database();
	}

	public function index()
	{
		$this->render('loket/loket');
	}

	public function loket_pendaftaran()
	{
		$this->render('loket/loket_pendaftaran');
	}

	// Tampilan monitoring antrian poli
	public function loket_poli()
	{
		$this->render('loket/loket_poli');
	}

	// Buat antrian loket - SANGAT SEDERHANA
	public function buat_antrian_loket()
	{
		try {
			// Generate nomor antrian
			$nomor_antrian = $this->generate_nomor_antrian();

			// Simpan langsung ke tb_antrian saja
			$antrian_data = [
				'antrian_id' => $this->generate_uuid(),
				'id_registrasi' => $this->generate_uuid(), // ID dummy, hanya untuk memenuhi constraint
				'nomor_antrian' => $nomor_antrian,
				'loket' => 'LOKET_1',
				'status_antrian' => 'MENUNGGU',
				'created_at' => date('Y-m-d H:i:s'),
				'updated_at' => date('Y-m-d H:i:s')
			];

			$insert_antrian = $this->db->insert('tb_antrian', $antrian_data);

			if (!$insert_antrian) {
				$error = $this->db->error();
				throw new Exception('Gagal menyimpan antrian: ' . $error['message']);
			}

			$response = [
				'success' => true,
				'nomor_antrian' => $nomor_antrian,
				'antrian_id' => $antrian_data['antrian_id']
			];
		} catch (Exception $e) {
			$response = [
				'success' => false,
				'message' => $e->getMessage()
			];
		}

		$this->output->set_content_type('application/json')->set_output(json_encode($response));
	}

	// Generate nomor antrian
	private function generate_nomor_antrian()
	{
		$today = date('Y-m-d');

		$this->db->where('DATE(created_at)', $today);
		$this->db->where('loket', 'LOKET_1');

		$last_number = $this->db->count_all_results('tb_antrian');

		return $last_number + 1;
	}

	// Generate UUID sederhana
	private function generate_uuid()
	{
		return 'A' . date('YmdHis') . mt_rand(1000, 9999);
	}

	// Get antrian menunggu
	// public function antrian_menunggu()
	// {
	//     $antrian = $this->db
	//         ->select('antrian_id, nomor_antrian, status_antrian, created_at')
	//         ->where('status_antrian', 'MENUNGGU')
	//         ->where('loket', 'LOKET_1')
	//         ->order_by('nomor_antrian', 'ASC')
	//         ->get('tb_antrian')
	//         ->result();

	//     $this->output->set_content_type('application/json')->set_output(json_encode($antrian));
	// }

	// Panggil antrian
	public function panggil_antrian()
	{
		$this->db->trans_begin();

		// Ambil antrian tertua yang menunggu
		$antrian = $this->db
			->where('status_antrian', 'MENUNGGU')
			->where('loket', 'LOKET_1')
			->order_by('nomor_antrian', 'ASC')
			->limit(1)
			->get('tb_antrian')
			->row();

		if ($antrian) {
			// Update status menjadi DIPANGGIL
			$this->db
				->where('antrian_id', $antrian->antrian_id)
				->update('tb_antrian', [
					'status_antrian' => 'DIPANGGIL',
					'waktu_panggil' => date('Y-m-d H:i:s'),
					'updated_at' => date('Y-m-d H:i:s')
				]);

			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				$response = ['success' => false, 'message' => 'Gagal memanggil antrian'];
			} else {
				$this->db->trans_commit();
				$response = [
					'success' => true,
					'message' => 'Antrian berhasil dipanggil',
					'data' => [
						'nomor_antrian' => $antrian->nomor_antrian,
						'antrian_id' => $antrian->antrian_id
					]
				];
			}
		} else {
			$response = ['success' => false, 'message' => 'Tidak ada antrian menunggu'];
		}

		$this->output->set_content_type('application/json')->set_output(json_encode($response));
	}

	// Selesaikan antrian
	public function selesai_antrian($antrian_id)
	{
		$updated = $this->db
			->where('antrian_id', $antrian_id)
			->update('tb_antrian', [
				'status_antrian' => 'SELESAI',
				'updated_at' => date('Y-m-d H:i:s')
			]);

		$response = [
			'success' => (bool)$updated,
			'message' => $updated ? 'Antrian diselesaikan' : 'Gagal menyelesaikan antrian'
		];

		$this->output->set_content_type('application/json')->set_output(json_encode($response));
	}

	// Get antrian sekarang (yang sedang dipanggil)
	public function antrian_sekarang()
	{
		$antrian = $this->db
			->select('antrian_id, nomor_antrian, status_antrian, waktu_panggil')
			->where('status_antrian', 'DIPANGGIL')
			->where('loket', 'LOKET_1')
			->order_by('waktu_panggil', 'DESC')
			->limit(1)
			->get('tb_antrian')
			->row();

		$this->output->set_content_type('application/json')->set_output(json_encode($antrian ?: []));
	}

	// Statistik
	// public function statistik()
	// {
	//     $today = date('Y-m-d');

	//     $total_antrian = $this->db
	//         ->where('DATE(created_at)', $today)
	//         ->where('loket', 'LOKET_1')
	//         ->count_all_results('tb_antrian');

	//     $antrian_selesai = $this->db
	//         ->where('DATE(created_at)', $today)
	//         ->where('loket', 'LOKET_1')
	//         ->where('status_antrian', 'SELESAI')
	//         ->count_all_results('tb_antrian');

	//     $antrian_menunggu = $this->db
	//         ->where('DATE(created_at)', $today)
	//         ->where('loket', 'LOKET_1')
	//         ->where('status_antrian', 'MENUNGGU')
	//         ->count_all_results('tb_antrian');

	//     $antrian_dipanggil = $this->db
	//         ->where('DATE(created_at)', $today)
	//         ->where('loket', 'LOKET_1')
	//         ->where('status_antrian', 'DIPANGGIL')
	//         ->count_all_results('tb_antrian');

	//     $response = [
	//         'total_antrian' => $total_antrian,
	//         'antrian_selesai' => $antrian_selesai,
	//         'antrian_menunggu' => $antrian_menunggu,
	//         'antrian_dipanggil' => $antrian_dipanggil
	//     ];

	//     $this->output->set_content_type('application/json')->set_output(json_encode($response));
	// }

	// Cari reservasi berdasarkan kode
	// Cari reservasi berdasarkan kode - VERSI YANG BENAR
	public function cari_reservasi($kode_reservasi = null)
	{
		try {
			if (!$kode_reservasi) {
				throw new Exception('Kode reservasi tidak valid');
			}

			// Query dengan join yang benar berdasarkan struktur database
			$this->db->select('r.*, p.nama_lengkap, pl.nama_poli, pt.nama_lengkap as nama_dokter');
			$this->db->from('tb_registrasi r');
			$this->db->join('tb_pasien p', 'r.id_pasien = p.pasien_id');
			$this->db->join('tb_poli pl', 'r.id_poli = pl.poli_id');
			$this->db->join('tb_dokter d', 'r.id_dokter = d.dokter_id', 'left');
			$this->db->join('tb_petugas pt', 'd.id_petugas = pt.petugas_id', 'left');
			$this->db->where('r.kode_verifikasi', $kode_reservasi);
			$this->db->where('r.status_verifikasi', 'BELUM');
			$this->db->where('r.tanggal_registrasi >=', date('Y-m-d'));

			$reservasi = $this->db->get()->row();

			if (!$reservasi) {
				throw new Exception('Reservasi tidak ditemukan atau sudah dikonfirmasi');
			}

			$response = [
				'success' => true,
				'data' => [
					'registrasi_id' => $reservasi->registrasi_id,
					'nomor_reservasi' => $reservasi->nomor_reservasi,
					'nama_lengkap' => $reservasi->nama_lengkap,
					'nama_poli' => $reservasi->nama_poli,
					'nama_dokter' => $reservasi->nama_dokter,
					'tanggal_registrasi' => $reservasi->tanggal_registrasi,
					'jam_registrasi' => $reservasi->jam_registrasi,
					'tipe_pembayaran' => $reservasi->tipe_pembayaran
				]
			];
		} catch (Exception $e) {
			$response = [
				'success' => false,
				'message' => $e->getMessage()
			];
		}

		$this->output->set_content_type('application/json')->set_output(json_encode($response));
	}

	// Konfirmasi reservasi dan buat antrian poli
	public function konfirmasi_reservasi()
{
    $this->db->trans_begin();

    try {
        $registrasi_id = $this->input->post('registrasi_id');

        if (!$registrasi_id) {
            throw new Exception('ID registrasi tidak valid');
        }

        // 1. Ambil data registrasi
        $registrasi = $this->db
            ->where('registrasi_id', $registrasi_id)
            ->where('status_verifikasi', 'BELUM')
            ->get('tb_registrasi')
            ->row();

        if (!$registrasi) {
            throw new Exception('Registrasi tidak ditemukan atau sudah dikonfirmasi');
        }

        // 2. Gunakan fungsi generate nomor antrian poli yang SAMA dengan registrasi
        $nomor_antrian_poli = $this->generate_nomor_antrian_poli($registrasi->id_poli);

        // 3. Update status registrasi
        $this->db
            ->where('registrasi_id', $registrasi_id)
            ->update('tb_registrasi', [
                'id_petugas'          => $this->session->userdata('id_petugas') ? $this->session->userdata('id_petugas') : NULL,
                'id_petugas_pj'       => $this->session->userdata('id_petugas_pj') ? $this->session->userdata('id_petugas_pj') : NULL,
                'status_verifikasi'   => 'SUDAH', // Pastikan sama dengan registrasi
                'status_registrasi'   => 'TERDAFTAR', // Tambahkan ini
                'status_kehadiran'    => 'HADIR', // Pastikan sama
                'updated_at'          => date('Y-m-d H:i:s')
            ]);

        // 4. Buat antrian poli dengan struktur yang SAMA seperti registrasi
        $antrian_data = [
            'antrian_id'      => $this->generate_uuid(),
            'id_registrasi'   => $registrasi_id,
            'nomor_antrian'   => $nomor_antrian_poli,
            'jenis_antrian'   => 'POLI', // Pastikan sama
            'loket'           => null,
            'status_antrian'  => 'MENUNGGU', // Pastikan sama
            'id_poli'         => $registrasi->id_poli,
            'created_at'      => date('Y-m-d H:i:s'),
            'updated_at'      => date('Y-m-d H:i:s')
        ];

        $this->db->insert('tb_antrian', $antrian_data);

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            throw new Exception('Gagal mengkonfirmasi reservasi');
        }

        $this->db->trans_commit();

        $response = [
            'success' => true,
            'message' => 'Reservasi berhasil dikonfirmasi',
            'nomor_antrian' => $nomor_antrian_poli,
            'antrian_id'    => $antrian_data['antrian_id'], // Tambahkan ini untuk print
            'data' => $antrian_data
        ];
        
    } catch (Exception $e) {
        $this->db->trans_rollback();
        $response = [
            'success' => false,
            'message' => $e->getMessage()
        ];
    }

    $this->output->set_content_type('application/json')->set_output(json_encode($response));
}
	public function konfirmasi_reservasi2()
	{
		$this->db->trans_begin();

		try {
			$registrasi_id = $this->input->post('registrasi_id');

			if (!$registrasi_id) {
				throw new Exception('ID registrasi tidak valid');
			}

			// 1. Ambil data registrasi
			$registrasi = $this->db
				->where('registrasi_id', $registrasi_id)
				->where('status_verifikasi', 'BELUM')
				->get('tb_registrasi')
				->row();

			if (!$registrasi) {
				throw new Exception('Registrasi tidak ditemukan atau sudah dikonfirmasi');
			}

			// 2. Generate nomor antrian poli untuk hari ini
			$nomor_antrian_poli = $this->generate_nomor_antrian_poli($registrasi->id_poli);

			// 3. Update status registrasi
			$this->db
				->where('registrasi_id', $registrasi_id)
				->update('tb_registrasi', [
					'id_petugas'          => $this->session->userdata('id_petugas') ? $this->session->userdata('id_petugas') : NULL,
					'id_petugas_pj'       => $this->session->userdata('id_petugas_pj') ? $this->session->userdata('id_petugas_pj') : NULL,
					'status_verifikasi' => 'SUDAH',
					'status_kehadiran' => 'HADIR',
					'updated_at' => date('Y-m-d H:i:s')
				]);

			// 4. Buat antrian poli
			$antrian_data = [
				'antrian_id' => $this->generate_uuid(),
				'id_registrasi' => $registrasi_id,
				'nomor_antrian' => $nomor_antrian_poli,
				'loket' => null,
				'status_antrian' => 'MENUNGGU',
				'jenis_antrian' => 'POLI',
				'id_poli' => $registrasi->id_poli,
				'created_at' => date('Y-m-d H:i:s'),
				'updated_at' => date('Y-m-d H:i:s')
			];

			$this->db->insert('tb_antrian', $antrian_data);

			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				throw new Exception('Gagal mengkonfirmasi reservasi');
			}

			$this->db->trans_commit();

			$response = [
				'success' => true,
				'message' => 'Reservasi berhasil dikonfirmasi',
				'nomor_antrian' => $nomor_antrian_poli,
				'data' => $antrian_data
			];
		} catch (Exception $e) {
			$this->db->trans_rollback();
			$response = [
				'success' => false,
				'message' => $e->getMessage()
			];
		}

		$this->output->set_content_type('application/json')->set_output(json_encode($response));
	}

	// Generate nomor antrian poli
	private function generate_nomor_antrian_poli($id_poli)
	{
		$today = date('Y-m-d');

		$this->db->where('DATE(created_at)', $today);
		$this->db->where('id_poli', $id_poli);
		$this->db->where('jenis_antrian', 'POLI');

		$last_number = $this->db->count_all_results('tb_antrian');

		return $last_number + 1;
	}

	// Tambahkan di class Loket.php

public function print_antrian_loket($antrian_id = null)
{
    if (!$antrian_id) {
        show_404();
        return;
    }

    // Ambil data antrian
    $antrian = $this->db
        ->select('a.*, r.nomor_reservasi, p.nama_lengkap, pl.nama_poli')
        ->from('tb_antrian a')
        ->join('tb_registrasi r', 'a.id_registrasi = r.registrasi_id', 'left')
        ->join('tb_pasien p', 'r.id_pasien = p.pasien_id', 'left')
        ->join('tb_poli pl', 'a.id_poli = pl.poli_id', 'left')
        ->where('a.antrian_id', $antrian_id)
        ->get()->row();

    if (!$antrian) {
        show_404();
        return;
    }

    $data['antrian'] = $antrian;
    $data['title'] = 'Struk Antrian Loket';
    
    $this->load->view('print/struk_antrian_loket', $data);
}

public function print_registrasi_pasien($registrasi_id = null)
{
    if (!$registrasi_id) {
        show_404();
        return;
    }

    // Ambil data registrasi lengkap
    $registrasi = $this->db
        ->select('r.*, p.nama_lengkap, p.nik, p.rme_no, pl.nama_poli, 
                 pt.nama_lengkap as nama_dokter, a.nomor_antrian')
        ->from('tb_registrasi r')
        ->join('tb_pasien p', 'r.id_pasien = p.pasien_id')
        ->join('tb_poli pl', 'r.id_poli = pl.poli_id')
        ->join('tb_dokter d', 'r.id_dokter = d.dokter_id', 'left')
        ->join('tb_petugas pt', 'd.id_petugas = pt.petugas_id', 'left')
        ->join('tb_antrian a', 'r.registrasi_id = a.id_registrasi', 'left')
        ->where('r.registrasi_id', $registrasi_id)
        ->get()->row();

    if (!$registrasi) {
        show_404();
        return;
    }

    $data['registrasi'] = $registrasi;
    $data['title'] = 'Struk Registrasi Pasien';
    
    $this->load->view('print/struk_registrasi_pasien', $data);
}

	// Get antrian menunggu (update method yang sudah ada)
	public function antrian_menunggu()
	{
		$this->db->select('a.*, p.nama_lengkap, pl.nama_poli, r.nomor_reservasi');
		$this->db->from('tb_antrian a');
		$this->db->join('tb_registrasi r', 'a.id_registrasi = r.registrasi_id', 'left');
		$this->db->join('tb_pasien p', 'r.id_pasien = p.pasien_id', 'left');
		$this->db->join('tb_poli pl', 'a.id_poli = pl.poli_id', 'left');
		$this->db->where('a.status_antrian', 'MENUNGGU');
		$this->db->where('a.jenis_antrian', 'POLI'); // Hanya tampilkan antrian poli
		$this->db->order_by('a.nomor_antrian', 'ASC');

		$antrian = $this->db->get()->result();

		$this->output->set_content_type('application/json')->set_output(json_encode($antrian));
	}

	// Update statistik untuk menampilkan data online
	public function statistik()
	{
		$today = date('Y-m-d');

		// Total antrian poli
		$total_antrian_poli = $this->db
			->where('DATE(created_at)', $today)
			->where('jenis_antrian', 'POLI')
			->count_all_results('tb_antrian');

		// Antrian poli selesai
		$antrian_poli_selesai = $this->db
			->where('DATE(created_at)', $today)
			->where('jenis_antrian', 'POLI')
			->where('status_antrian', 'SELESAI')
			->count_all_results('tb_antrian');

		// Antrian poli menunggu
		$antrian_poli_menunggu = $this->db
			->where('DATE(created_at)', $today)
			->where('jenis_antrian', 'POLI')
			->where('status_antrian', 'MENUNGGU')
			->count_all_results('tb_antrian');

		// Antrian poli dipanggil
		$antrian_poli_dipanggil = $this->db
			->where('DATE(created_at)', $today)
			->where('jenis_antrian', 'POLI')
			->where('status_antrian', 'DIPANGGIL')
			->count_all_results('tb_antrian');

		// Registrasi online terkonfirmasi hari ini
		$online_terkonfirmasi = $this->db
			->where('DATE(updated_at)', $today)
			->where('sumber_registrasi', 'ONLINE')
			->where('status_verifikasi', 'SUDAH')
			->count_all_results('tb_registrasi');

		$response = [
			'total_antrian' => $total_antrian_poli,
			'antrian_selesai' => $antrian_poli_selesai,
			'antrian_menunggu' => $antrian_poli_menunggu,
			'antrian_dipanggil' => $antrian_poli_dipanggil,
			'online_terkonfirmasi' => $online_terkonfirmasi
		];

		$this->output->set_content_type('application/json')->set_output(json_encode($response));
	}

	// Loket pendaftaran resources
	public function get_loket_list()
	{
		$loket = $this->db
			->select('loket')
			->from('tb_antrian')
			->where('loket IS NOT NULL', null, false)
			->group_by('loket')
			->order_by('loket', 'ASC')
			->get()->result();

		// fallback minimal 1 loket default
		if (!$loket) {
			$loket = [
				(object)['loket' => 'LOKET_1']
			];
		}

		$this->output->set_content_type('application/json')->set_output(json_encode($loket));
	}

	public function get_antrian_loket()
	{
		$loket_code = $this->input->get('loket');
		$status = $this->input->get('status');
		$start_date = $this->input->get('start_date') ?: date('Y-m-d');
		$end_date = $this->input->get('end_date') ?: date('Y-m-d');

		$this->db->select('a.*, p.nama_lengkap, r.nomor_reservasi');
		$this->db->from('tb_antrian a');
		$this->db->join('tb_registrasi r', 'a.id_registrasi = r.registrasi_id', 'left');
		$this->db->join('tb_pasien p', 'r.id_pasien = p.pasien_id', 'left');
		$this->db->where('a.loket IS NOT NULL', null, false);
		$this->db->where('DATE(a.created_at) >=', $start_date);
		$this->db->where('DATE(a.created_at) <=', $end_date);

		if ($loket_code && $loket_code !== 'all') {
			$this->db->where('a.loket', $loket_code);
		}

		if ($status && $status !== 'all') {
			$this->db->where('a.status_antrian', $status);
		}

		$this->db->order_by('a.created_at', 'DESC');
		$this->db->order_by('a.nomor_antrian', 'ASC');

		$antrian = $this->db->get()->result();

		$this->output->set_content_type('application/json')->set_output(json_encode($antrian));
	}

	public function statistik_loket()
	{
		$loket_code = $this->input->get('loket');
		$start_date = $this->input->get('start_date') ?: date('Y-m-d');
		$end_date = $this->input->get('end_date') ?: date('Y-m-d');

		$response = [
			'total' => $this->count_loket_antrian($loket_code, $start_date, $end_date),
			'menunggu' => $this->count_loket_antrian($loket_code, $start_date, $end_date, 'MENUNGGU'),
			'dipanggil' => $this->count_loket_antrian($loket_code, $start_date, $end_date, 'DIPANGGIL'),
			'selesai' => $this->count_loket_antrian($loket_code, $start_date, $end_date, 'SELESAI')
		];

		$this->output->set_content_type('application/json')->set_output(json_encode($response));
	}

	private function count_loket_antrian($loket_code, $start_date, $end_date, $status = null)
	{
		$this->db->where('DATE(created_at) >=', $start_date);
		$this->db->where('DATE(created_at) <=', $end_date);
		$this->db->where('loket IS NOT NULL', null, false);

		if ($loket_code && $loket_code !== 'all') {
			$this->db->where('loket', $loket_code);
		}

		if ($status) {
			$this->db->where('status_antrian', $status);
		}

		return $this->db->count_all_results('tb_antrian');
	}
}
