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

class Farmasidatastock extends CI_Controller
{

    public function tampildatastokfarmasi()
    {


        if (isset($_POST['KD_GUDANG'])) {
            // Mengambil input tanggal dari form
            $kdgudang = $_POST['KD_GUDANG'];

            // Mengambil data dari API
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_stock',
                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 => array(
                    'KD_GUDANG' => $kdgudang
                ),
            ));

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

            // Mengembalikan respons API dalam format JSON
            if ($response) {
                // Jika response bukan JSON, kirimkan error
                json_decode($response);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    echo json_encode(['error' => 'Data tidak valid.']);
                } else {
                    echo $response; // Kirimkan kembali data yang benar
                }
            } else {
                echo json_encode(['error' => 'Tidak ada data yang ditemukan atau terjadi kesalahan.']);
            }
        }
    }

    public function unduhstockdatafarmasi()
    {


        ini_set('memory_limit', '1024M'); // Menaikkan batas memori menjadi 1GB
        ini_set('max_execution_time', 0); // Agar proses tidak time-out jika loadingnya lama
        // --------------------------------------------

        $nm_user = $this->session->userdata('nm_user');
        $kd_user = $this->session->userdata('kd_user');

        $kdgudang = $this->input->get('KD_GUDANG');


        // Memanggil API menggunakan cURL
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_stock',
            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 => array(
                'KD_GUDANG' => $kdgudang
            ),
        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data Stok Farmasi."

        ];
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/sinaran_download',
            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,
        ]);

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

        if ($response) {
            $data = json_decode($response, true)['response'];

            // Load library PhpSpreadsheet
            //require_once APPPATH . 'third_party/PhpSpreadsheet/src/Bootstrap.php';

            // Load library PhpSpreadsheet
            require_once APPPATH . '../vendor/autoload.php';

            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            // Set header kolom
            $sheet->setCellValue('A1', 'Kd Stok');
            $sheet->setCellValue('B1', 'Kd Obat');
            $sheet->setCellValue('C1', 'Tgl Masuk');
            $sheet->setCellValue('D1', 'Expired Date');
            $sheet->setCellValue('E1', 'Kode Produksi');
            $sheet->setCellValue('F1', 'Nama Pabrik');
            $sheet->setCellValue('G1', 'Nama Obat');
            $sheet->setCellValue('H1', 'Qty Terhitung');
            $sheet->setCellValue('I1', 'Qty Terpakai');
            $sheet->setCellValue('J1', 'Qty Sisa');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_stock']);
                $sheet->setCellValue('B' . $row, $item['kd_obat']);
                $sheet->setCellValue('C' . $row, $item['tgl_masuk']);
                $sheet->setCellValue('D' . $row, $item['expired_date']);
                $sheet->setCellValue('E' . $row, $item['kode_produksi']);
                $sheet->setCellValue('F' . $row, $item['nama_pabrik']);
                $sheet->setCellValue('G' . $row, $item['nama_obat']);
                $sheet->setCellValue('H' . $row, $item['qty_hitung']);
                $sheet->setCellValue('I' . $row, $item['qty_terpakai']);
                $sheet->setCellValue('J' . $row, $item['qty_sisa']);
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="Data_Stok_Farmasi.xlsx"');
            header('Cache-Control: max-age=0');

            // Output ke file
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
            exit();
        } else {
            echo json_encode(['error' => 'Tidak ada data yang ditemukan.']);
        }
    }


    public function datafarmasistokperobat()
    {
        if (isset($_POST['KD_GUDANG']) && isset($_POST['KD_OBAT'])) {
            // Mengambil input tanggal dari form
            $kdgudang = $_POST['KD_GUDANG'];
            $kdobat = $_POST['KD_OBAT'];

            // Mengambil data dari API
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_stock_perobat',
                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 => array(
                    'KD_GUDANG' => $kdgudang,
                    'KD_OBAT' => $kdobat

                ),
            ));

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

            // Mengembalikan respons API dalam format JSON
            if ($response) {
                // Jika response bukan JSON, kirimkan error
                json_decode($response);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    echo json_encode(['error' => 'Data tidak valid.']);
                } else {
                    echo $response; // Kirimkan kembali data yang benar
                }
            } else {
                echo json_encode(['error' => 'Tidak ada data yang ditemukan atau terjadi kesalahan.']);
            }
        }
    }

    public function unduhfarmasistokperobat()
    {

        $nm_user = $this->session->userdata('nm_user');
        $kd_user = $this->session->userdata('kd_user');

        $kdgudang = $this->input->get('KD_GUDANG');
        $kdobat = $this->input->get('KD_OBAT');


        // Memanggil API menggunakan cURL
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_stock_perobat',
            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 => array(
                'KD_GUDANG' => $kdgudang,
                'KD_OBAT' => $kdobat
            ),
        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data Stok Farmasi Pearobat."

        ];
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/sinaran_download',
            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,
        ]);

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

        if ($response) {
            $data = json_decode($response, true)['response'];

            // Load library PhpSpreadsheet
            //require_once APPPATH . 'third_party/PhpSpreadsheet/src/Bootstrap.php';

            // Load library PhpSpreadsheet
            require_once APPPATH . '../vendor/autoload.php';

            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            // Set header kolom
            $sheet->setCellValue('A1', 'Kd Stok');
            $sheet->setCellValue('B1', 'Kd Obat');
            $sheet->setCellValue('C1', 'Tgl Masuk');
            $sheet->setCellValue('D1', 'Expired Date');
            $sheet->setCellValue('E1', 'Kode Produksi');
            $sheet->setCellValue('F1', 'Nama Pabrik');
            $sheet->setCellValue('G1', 'Nama Obat');
            $sheet->setCellValue('H1', 'Qty Terhitung');
            $sheet->setCellValue('I1', 'Qty Terpakai');
            $sheet->setCellValue('J1', 'Qty Sisa');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_stock']);
                $sheet->setCellValue('B' . $row, $item['kd_obat']);
                $sheet->setCellValue('C' . $row, $item['tgl_masuk']);
                $sheet->setCellValue('D' . $row, $item['expired_date']);
                $sheet->setCellValue('E' . $row, $item['kode_produksi']);
                $sheet->setCellValue('F' . $row, $item['nama_pabrik']);
                $sheet->setCellValue('G' . $row, $item['nama_obat']);
                $sheet->setCellValue('H' . $row, $item['qty_hitung']);
                $sheet->setCellValue('I' . $row, $item['qty_terpakai']);
                $sheet->setCellValue('J' . $row, $item['qty_sisa']);
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="Data_Stok_Farmasi_Perobat.xlsx"');
            header('Cache-Control: max-age=0');

            // Output ke file
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
            exit();
        } else {
            echo json_encode(['error' => 'Tidak ada data yang ditemukan.']);
        }
    }


    public function tampildatastokfarmasirekap()
    {
        if (isset($_POST['KD_GUDANG'])) {
            // Mengambil input tanggal dari form
            $kdgudang = $_POST['KD_GUDANG'];

            // Mengambil data dari API
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_stock_rekap',
                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 => array(
                    'KD_GUDANG' => $kdgudang
                ),
            ));

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

            // Mengembalikan respons API dalam format JSON
            if ($response) {
                // Jika response bukan JSON, kirimkan error
                json_decode($response);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    echo json_encode(['error' => 'Data tidak valid.']);
                } else {
                    echo $response; // Kirimkan kembali data yang benar
                }
            } else {
                echo json_encode(['error' => 'Tidak ada data yang ditemukan atau terjadi kesalahan.']);
            }
        }
    }

    public function unduhstockdatafarmasirekap()
    {

        $nm_user = $this->session->userdata('nm_user');
        $kd_user = $this->session->userdata('kd_user');

        $kdgudang = $this->input->get('KD_GUDANG');


        // Memanggil API menggunakan cURL
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_stock_rekap',
            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 => array(
                'KD_GUDANG' => $kdgudang
            ),
        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data Stok Farmasi Rekap."

        ];
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/sinaran_download',
            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,
        ]);

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

        if ($response) {
            $data = json_decode($response, true)['response'];

            // Load library PhpSpreadsheet
            //require_once APPPATH . 'third_party/PhpSpreadsheet/src/Bootstrap.php';

            // Load library PhpSpreadsheet
            require_once APPPATH . '../vendor/autoload.php';

            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            // Set header kolom
            $sheet->setCellValue('A1', 'Kd Obat');
            $sheet->setCellValue('B1', 'Nama Obat');
            $sheet->setCellValue('C1', 'Total Sisa');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_obat']);
                $sheet->setCellValue('B' . $row, $item['nama_obat']);
                $sheet->setCellValue('C' . $row, $item['total_sisa']);
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="Data_Stok_Farmasi_Rekap.xlsx"');
            header('Cache-Control: max-age=0');

            // Output ke file
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
            exit();
        } else {
            echo json_encode(['error' => 'Tidak ada data yang ditemukan.']);
        }
    }

    public function datafarmasiSO()
    {
        if (isset($_POST['KD_OPNAME'])) {
            // Mengambil input tanggal dari form
            $kdopname = $_POST['KD_OPNAME'];


            // Mengambil data dari API
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_data_opname',
                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 => array(
                    'KD_OPNAME' => $kdopname

                ),
            ));

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

            // Mengembalikan respons API dalam format JSON
            if ($response) {
                // Jika response bukan JSON, kirimkan error
                json_decode($response);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    echo json_encode(['error' => 'Data tidak valid.']);
                } else {
                    echo $response; // Kirimkan kembali data yang benar
                }
            } else {
                echo json_encode(['error' => 'Tidak ada data yang ditemukan atau terjadi kesalahan.']);
            }
        }
    }

    public function unduhdataSOfarmasi()
    {

        $nm_user = $this->session->userdata('nm_user');
        $kd_user = $this->session->userdata('kd_user');

        $kdopname = $this->input->get('KD_OPNAME');



        // Memanggil API menggunakan cURL
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_data_opname',
            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 => array(
                'KD_OPNAME' => $kdopname

            ),
        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data SO Farmasi."

        ];
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/sinaran_download',
            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,
        ]);

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

        if ($response) {
            $data = json_decode($response, true)['response'];

            // Load library PhpSpreadsheet
            //require_once APPPATH . 'third_party/PhpSpreadsheet/src/Bootstrap.php';

            // Load library PhpSpreadsheet
            require_once APPPATH . '../vendor/autoload.php';

            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            // Set header kolom
            $sheet->setCellValue('A1', 'Kode Opname');
            $sheet->setCellValue('B1', 'Nama Gudang');
            $sheet->setCellValue('C1', 'Kode Obat');
            $sheet->setCellValue('D1', 'Nama Obat');
            $sheet->setCellValue('E1', 'Qty Asal');
            $sheet->setCellValue('F1', 'Qty Opname');
            $sheet->setCellValue('G1', 'Qty Koreksi');
            $sheet->setCellValue('H1', 'Harga Beli Terakhir');
            $sheet->setCellValue('I1', 'Total HPP Koreksi');
            $sheet->setCellValue('J1', 'Kode Satuan');
            $sheet->setCellValue('K1', 'Nama Satuan');
            $sheet->setCellValue('L1', 'Keterangan');
            $sheet->setCellValue('M1', 'Catatan');
            $sheet->setCellValue('N1', 'Harga Satuan Terakhir');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_opname']);
                $sheet->setCellValue('B' . $row, $item['nm_gudang']);
                $sheet->setCellValue('C' . $row, $item['kd_obat']);
                $sheet->setCellValue('D' . $row, $item['nama_obat']);
                $sheet->setCellValue('E' . $row, $item['qty_asal']);
                $sheet->setCellValue('F' . $row, $item['qty_opname']);
                $sheet->setCellValue('G' . $row, $item['qty_koreksi']);
                $sheet->setCellValue('H' . $row, $item['harga_beli_terakhir']);
                $sheet->setCellValue('I' . $row, $item['tot_hpp_koreksi']);
                $sheet->setCellValue('J' . $row, $item['kd_satuan_volume']);
                $sheet->setCellValue('K' . $row, $item['nm_satuan_volume']);
                $sheet->setCellValue('L' . $row, $item['keterangan']);
                $sheet->setCellValue('M' . $row, $item['catatan']);
                $sheet->setCellValue('N' . $row, $item['harga_satuan_terakhir']);
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="Data_SO_FARMASI.xlsx"');
            header('Cache-Control: max-age=0');

            // Output ke file
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
            exit();
        } else {
            echo json_encode(['error' => 'Tidak ada data yang ditemukan.']);
        }
    }

    public function refmasterSOfarmasi()
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'http://103.255.241.146/api/service_rs/farmasi_master_opname',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0, // Waktu tunggu permintaan selama 30 detik
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            // Metode diatur ke POST sesuai kebutuhan API backend
            CURLOPT_CUSTOMREQUEST => 'POST',
            // Mengirim body kosong secara eksplisit menggunakan sintaks array() yang kompatibel
            CURLOPT_POSTFIELDS => array(),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl); // Menangkap error dari cURL jika ada

        curl_close($curl);

        // Selalu atur header Content-Type agar browser tahu ini adalah JSON
        header('Content-Type: application/json');

        if ($err) {
            // Jika terjadi error pada cURL (misal: tidak bisa terhubung ke API)
            echo json_encode(['error' => 'Gagal terhubung ke server API eksternal: ' . $err]);
        } elseif ($response) {
            // Cek apakah respons adalah JSON yang valid sebelum dikirim
            json_decode($response);
            if (json_last_error() !== JSON_ERROR_NONE) {
                echo json_encode(['error' => 'Respons dari API eksternal bukan JSON yang valid.']);
            } else {
                // Kirimkan kembali data JSON yang benar dari API
                echo $response;
            }
        } else {
            // Jika tidak ada respons sama sekali dari API
            echo json_encode(['error' => 'Tidak ada respons dari server API eksternal.']);
        }
    }


    public function datastokallfarmasi()
    {
        // 1. Dihapus: if (isset($_POST['KD_OPNAME'])) karena memang tidak butuh inputan

        // Mengambil data dari API
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_stock_all',
            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',
            // 2. Dihapus: CURLOPT_POSTFIELDS karena body/inputan kosong sesuai Postman
        ));

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

        // Mengembalikan respons API dalam format JSON
        if ($response) {
            // Cek apakah response benar-benar JSON yang valid dari API-nya
            json_decode($response);
            if (json_last_error() !== JSON_ERROR_NONE) {
                echo json_encode(['error' => 'Data tidak valid.']);
            } else {
                echo $response; // Kirimkan kembali data yang benar ke View
            }
        } else {
            echo json_encode(['error' => 'Tidak ada data yang ditemukan atau terjadi kesalahan.']);
        }
    }

    public function unduhdatastokallFarmasi()
    {

        $nm_user = $this->session->userdata('nm_user');
        $kd_user = $this->session->userdata('kd_user');

        // Memanggil API menggunakan cURL
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_stock_all',
            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',

        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data Stok All Farmasi."

        ];
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/sinaran_download',
            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,
        ]);

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

        if ($response) {
            $data = json_decode($response, true)['response'];

            // Load library PhpSpreadsheet
            //require_once APPPATH . 'third_party/PhpSpreadsheet/src/Bootstrap.php';

            // Load library PhpSpreadsheet
            require_once APPPATH . '../vendor/autoload.php';

            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            // Set header kolom
            $sheet->setCellValue('A1', 'Kode Obat');
            $sheet->setCellValue('B1', 'Nama Obat');
            $sheet->setCellValue('C1', 'Nama Pabrik');
            $sheet->setCellValue('D1', 'Stok Gudang Utama');
            $sheet->setCellValue('E1', 'Stok Rawat Jalan');
            $sheet->setCellValue('F1', 'Stok Rawat Inap');
            $sheet->setCellValue('G1', 'Total Stok');
            $sheet->setCellValue('H1', 'Qty Ideal');
            $sheet->setCellValue('I1', 'Qty Volume Satuan');
            $sheet->setCellValue('J1', 'Standar Ideal Total');
            $sheet->setCellValue('K1', 'Qty Minimal');
            $sheet->setCellValue('L1', 'Standar Minimal Total');
            $sheet->setCellValue('M1', 'Selisih dari Ideal');
            $sheet->setCellValue('N1', 'Persen Pemenuhan Ideal (%)');
            $sheet->setCellValue('O1', 'Status Gudang Utama');
            $sheet->setCellValue('P1', 'Status Rawat Jalan');
            $sheet->setCellValue('Q1', 'Status Rawat Inap');
            $sheet->setCellValue('R1', 'Status Total');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_obat']);
                $sheet->setCellValue('B' . $row, $item['nama_obat']);
                $sheet->setCellValue('C' . $row, $item['nama_pabrik']);
                $sheet->setCellValue('D' . $row, $item['stock_gudang_utama']);
                $sheet->setCellValue('E' . $row, $item['stock_rawat_jalan']);
                $sheet->setCellValue('F' . $row, $item['stock_rawat_inap']);
                $sheet->setCellValue('G' . $row, $item['total_stock']);
                $sheet->setCellValue('H' . $row, $item['qty_ideal']);
                $sheet->setCellValue('I' . $row, $item['qty_vol_satuan']);
                $sheet->setCellValue('J' . $row, $item['standar_ideal_total']);
                $sheet->setCellValue('K' . $row, $item['qty_minimal']);
                $sheet->setCellValue('L' . $row, $item['standar_minimal_total']);
                $sheet->setCellValue('M' . $row, $item['selisih_dari_ideal']);
                $sheet->setCellValue('N' . $row, $item['persen_pemenuhan_ideal']);
                $sheet->setCellValue('O' . $row, $item['status_gudang_utama']);
                $sheet->setCellValue('P' . $row, $item['status_rawat_jalan']);
                $sheet->setCellValue('Q' . $row, $item['status_rawat_inap']);
                $sheet->setCellValue('R' . $row, $item['status_total']);
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="Data_Stok_All_Farmasi.xlsx"');
            header('Cache-Control: max-age=0');

            // Output ke file
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
            exit();
        } else {
            echo json_encode(['error' => 'Tidak ada data yang ditemukan.']);
        }
    }

    public function farmasistok_rekapdataperobat()
    {
        if (isset($_POST['KD_OBAT'])) {
            // Mengambil input tanggal dari form
            $kdobat = $_POST['KD_OBAT'];

            // Mengambil data dari API
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_stock_rekap_per_obat',
                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 => array(
                    'KD_OBAT' => $kdobat
                ),
            ));

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

            // Mengembalikan respons API dalam format JSON
            if ($response) {
                // Jika response bukan JSON, kirimkan error
                json_decode($response);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    echo json_encode(['error' => 'Data tidak valid.']);
                } else {
                    echo $response; // Kirimkan kembali data yang benar
                }
            } else {
                echo json_encode(['error' => 'Tidak ada data yang ditemukan atau terjadi kesalahan.']);
            }
        }
    }


    public function datastokallfarmasisum_perpabarik()
    {
        // 1. Dihapus: if (isset($_POST['KD_OPNAME'])) karena memang tidak butuh inputan

        // Mengambil data dari API
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_stock_all_sum_pabrik',
            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',
            // 2. Dihapus: CURLOPT_POSTFIELDS karena body/inputan kosong sesuai Postman
        ));

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

        // Mengembalikan respons API dalam format JSON
        if ($response) {
            // Cek apakah response benar-benar JSON yang valid dari API-nya
            json_decode($response);
            if (json_last_error() !== JSON_ERROR_NONE) {
                echo json_encode(['error' => 'Data tidak valid.']);
            } else {
                echo $response; // Kirimkan kembali data yang benar ke View
            }
        } else {
            echo json_encode(['error' => 'Tidak ada data yang ditemukan atau terjadi kesalahan.']);
        }
    }

    public function unduhdatastokallFarmasi_sumAll()
    {

        $nm_user = $this->session->userdata('nm_user');
        $kd_user = $this->session->userdata('kd_user');

        // Memanggil API menggunakan cURL
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_stock_all_sum_pabrik',
            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',

        ));

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

        //log harian download
        $datai = [
            "NIP_PETUGAS" => $kd_user,
            "CATATAN" => "Akun " . $nm_user . " berhasil download data Stok All Farmasi SUM PERBARIK."

        ];
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => '103.255.241.146/api/service_rs/sinaran_download',
            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,
        ]);

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

        if ($response) {
            $data = json_decode($response, true)['response'];

            // Load library PhpSpreadsheet
            //require_once APPPATH . 'third_party/PhpSpreadsheet/src/Bootstrap.php';

            // Load library PhpSpreadsheet
            require_once APPPATH . '../vendor/autoload.php';

            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            // Set header kolom
            $sheet->setCellValue('A1', 'Kode Obat');
            $sheet->setCellValue('B1', 'Nama Obat');
            $sheet->setCellValue('C1', 'Stok Gudang Utama');
            $sheet->setCellValue('D1', 'Stok Rawat Jalan');
            $sheet->setCellValue('E1', 'Stok Rawat Inap');
            $sheet->setCellValue('F1', 'Total Stok');
            $sheet->setCellValue('G1', 'Qty Ideal');
            $sheet->setCellValue('H1', 'Qty Volume Satuan');
            $sheet->setCellValue('I1', 'Standar Ideal Total');
            $sheet->setCellValue('J1', 'Qty Minimal');
            $sheet->setCellValue('K1', 'Standar Minimal Total');
            $sheet->setCellValue('L1', 'Selisih dari Ideal');
            $sheet->setCellValue('M1', 'Persen Pemenuhan Ideal (%)');
            $sheet->setCellValue('N1', 'Status Gudang Utama');
            $sheet->setCellValue('O1', 'Status Rawat Jalan');
            $sheet->setCellValue('P1', 'Status Rawat Inap');
            $sheet->setCellValue('Q1', 'Status Total');

            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_obat']);
                $sheet->setCellValue('B' . $row, $item['nama_obat']);
                $sheet->setCellValue('C' . $row, $item['stock_gudang_utama']);
                $sheet->setCellValue('D' . $row, $item['stock_rawat_jalan']);
                $sheet->setCellValue('E' . $row, $item['stock_rawat_inap']);
                $sheet->setCellValue('F' . $row, $item['total_stock']);
                $sheet->setCellValue('G' . $row, $item['qty_ideal']);
                $sheet->setCellValue('H' . $row, $item['qty_vol_satuan']);
                $sheet->setCellValue('I' . $row, $item['standar_ideal_total']);
                $sheet->setCellValue('J' . $row, $item['qty_minimal']);
                $sheet->setCellValue('K' . $row, $item['standar_minimal_total']);
                $sheet->setCellValue('L' . $row, $item['selisih_dari_ideal']);
                $sheet->setCellValue('M' . $row, $item['persen_pemenuhan_ideal']);
                $sheet->setCellValue('N' . $row, $item['status_gudang_utama']);
                $sheet->setCellValue('O' . $row, $item['status_rawat_jalan']);
                $sheet->setCellValue('P' . $row, $item['status_rawat_inap']);
                $sheet->setCellValue('Q' . $row, $item['status_total']);
                $row++;
            }

            // Mengatur header untuk unduhan
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="Data_Stok_All_Farmasi_SUM_PERPABRIK.xlsx"');
            header('Cache-Control: max-age=0');

            // Output ke file
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
            exit();
        } else {
            echo json_encode(['error' => 'Tidak ada data yang ditemukan.']);
        }
    }
}
