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

class Loginrawatinap extends CI_Controller
{


    public function index()
    {

        // Cek apakah user sudah login
        if ($this->session->userdata('berhasil_loginu') === true) {
            // Jika user sudah login, arahkan ke dashboard
            redirect(base_url('dashboard/utama'));
        } else {
            // Jika belum login, tampilkan halaman login
            $this->load->view('loginrawatinap');
        }
    }

    public function authlogin()
    {
        $kd_userus = $_POST['kd_user'];
        $passwordus = base64_decode($this->input->post('password'));
        $blocked_users = ['DIREKTUR', 'MANAJER'];

        if (in_array(strtoupper($kd_userus), $blocked_users)) {
            echo json_encode([
                'status' => 'error',
                'message' => 'Akses Ditolak: Akun Direksi/Manajemen tidak dapat digunakan di portal ini.'
            ]);
            return; // Hentikan eksekusi kode, jangan teruskan ke API
        }

        $data = [
            "KD_USER" => $kd_userus,
            "PASSWORD" => $passwordus,
        ];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/d_reg_online/tampil_apikkan_user',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $data,
        ]);

        $response = curl_exec($curl);
        curl_close($curl);

        log_message('debug', 'API Response: ' . $response);

        $json = json_decode($response);

        if (json_last_error() !== JSON_ERROR_NONE) {
            log_message('error', 'Kesalahan Dekode JSON: ' . json_last_error_msg());
            echo json_encode(['status' => 'error', 'message' => 'Format respons yang tidak terduga dari server.']);
            redirect(base_url(''));
            return;
        }

        if (isset($json->status) && $json->status) {
            $userFound = false;

            foreach ($json->response->list as $row) {
                if ($row->kd_app === "RMI" || $row->kd_app === "RAD") {
                    $kd_user = $row->kd_user;
                    $password = $row->password;

                    if ($kd_userus === $kd_user && $passwordus === $password) {
                        $this->session->berhasil_loginu = true;

                        $datai = [
                            "NIP_PETUGAS" => $kd_userus,
                            "CATATAN" => "Akun dengan nama " . $kd_userus . " berhasil login menu RAWATINAP."

                        ];

                        $curl = curl_init();
                        curl_setopt_array($curl, [
                            CURLOPT_URL => '103.255.241.146/api/service_rs/sinaran_login',
                            CURLOPT_RETURNTRANSFER => true,
                            CURLOPT_ENCODING => '',
                            CURLOPT_MAXREDIRS => 10,
                            CURLOPT_TIMEOUT => 0,
                            CURLOPT_FOLLOWLOCATION => true,
                            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                            CURLOPT_CUSTOMREQUEST => 'POST',
                            CURLOPT_POSTFIELDS => $datai,
                        ]);

                        $response = curl_exec($curl);
                        curl_close($curl);


                        $this->session->set_userdata('nm_user', $row->nm_user);
                        $this->session->set_userdata('kd_akses', $row->kd_akses);
                        $this->session->set_userdata('kd_app', $row->kd_app);
                        $this->session->set_userdata('nip', $row->nip);
                        $userFound = true;
                        echo json_encode(['status' => 'success', 'redirect' => base_url('dashboard/utama')]);
                        return;
                    }
                }
            }

            // Jika pengguna tidak ditemukan

            if (!$userFound) {
                echo json_encode(['status' => 'error', 'message' => 'Mas dan Mba sekalian passwordnya salah iya']);
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Mas dan Mba sekalian passwordnya salah iya.']);
        }
    }


    function logout()
    {
        $this->session->sess_destroy();
        redirect(base_url(''));
    }
}
