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

class Farmasiobatkronis extends CI_Controller
{
     public function dataobatkronis()
    {
        if (isset($_POST['TANGGAL_AWAL']) && isset($_POST['TANGGAL_AKHIR'])) {
            // Mengambil input tanggal dari form
            $tanggalawal = $_POST['TANGGAL_AWAL'];
            $tanggalakhir = $_POST['TANGGAL_AKHIR'];

            // Mengonversi format tanggal ke dd/mm/yyyy
            $tanggal_awal = date('d/m/Y', strtotime($tanggalawal));
            $tanggal_akhir = date('d/m/Y', strtotime($tanggalakhir));
        

            // Mengambil data dari API
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_obat_kronis',
                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(
                    'TANGGAL_AWAL' => $tanggal_awal,
                    'TANGGAL_AKHIR' => $tanggal_akhir
         
                ),
            ));

            $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 unduhobatkronis()
    {

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

        $tanggal_awal = $this->input->get('TANGGAL_AWAL');
        $tanggal_akhir = $this->input->get('TANGGAL_AKHIR');

        // Ubah format tanggal jika diperlukan
        $tanggal_awali = date('d/m/Y', strtotime($tanggal_awal));
        $tanggal_akhiri = date('d/m/Y', strtotime($tanggal_akhir));



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

            ),
        ));

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

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

        ];
        $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) {
                $decoded = json_decode($response, true);
                $data = isset($decoded['response']) ? $decoded['response'] : [];

                if (empty($data)) {
                    die("Data tidak ditemukan untuk periode tersebut.");
                }

                require_once APPPATH . '../vendor/autoload.php';
                $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
                $sheet = $spreadsheet->getActiveSheet();

                // Set Header Kolom
                $sheet->setCellValue('A1', 'Kode Registrasi');
                $sheet->setCellValue('B1', 'Nama Pasien');
                $sheet->setCellValue('C1', 'No SJP');
                $sheet->setCellValue('D1', 'No SEP');
                $sheet->setCellValue('E1', 'Kode Penjualan');
                $sheet->setCellValue('F1', 'Kode Obat');
                $sheet->setCellValue('G1', 'Nama Obat');
                $sheet->setCellValue('H1', 'Nama Obat BPJS');
                $sheet->setCellValue('I1', 'Qty Jual');
                $sheet->setCellValue('J1', 'Sub Total');
                $sheet->setCellValue('K1', 'Total');
                $sheet->setCellValue('L1', 'Total Harga Jual');
                $sheet->setCellValue('M1', 'Harga Satuan');
                $sheet->setCellValue('N1', 'Nama Pabrik');
                $sheet->setCellValue('O1', 'Kode Produksi');
                $sheet->setCellValue('P1', 'Total Harga Beli');
                $sheet->setCellValue('Q1', 'Total Harga BPJS');

                // ISI DATA - PASTIKAN $row++ ADA DI DALAM FOREACH
                $row = 2;
                foreach ($data as $item) {
                    $sheet->setCellValue('A' . $row, $item['kd_registrasi'] ?? '');
                    $sheet->setCellValue('B' . $row, $item['nm_pasien'] ?? '');
                    $sheet->setCellValue('C' . $row, $item['nosjp'] ?? '');
                    $sheet->setCellValue('D' . $row, $item['no_sep'] ?? '');
                    $sheet->setCellValue('E' . $row, $item['kd_jual'] ?? '');
                    $sheet->setCellValue('F' . $row, $item['kd_obat'] ?? '');
                    $sheet->setCellValue('G' . $row, $item['nama_obat'] ?? '');
                    $sheet->setCellValue('H' . $row, $item['nm_obat_bpjs'] ?? '');
                    $sheet->setCellValue('I' . $row, $item['qty_jual'] ?? '');
                    $sheet->setCellValue('J' . $row, $item['sub_total'] ?? '');
                    $sheet->setCellValue('K' . $row, $item['total'] ?? '');
                    $sheet->setCellValue('L' . $row, $item['total_harga_jual'] ?? '');
                    $sheet->setCellValue('M' . $row, $item['harga_satuan'] ?? '');
                    $sheet->setCellValue('N' . $row, $item['nama_pabrik'] ?? '');
                    $sheet->setCellValue('O' . $row, $item['kode_produksi'] ?? '');
                    $sheet->setCellValue('P' . $row, $item['total_harga_beli'] ?? '');
                    $sheet->setCellValue('Q' . $row, $item['total_harga_bpjs'] ?? '');
                    $row++; // INI SANGAT PENTING: Harus bertambah setiap loop
                }

                // Bersihkan buffer untuk mencegah file rusak
                if (ob_get_contents()) ob_end_clean();

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

                $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
                $writer->save('php://output');
                exit();
            } else {
                echo json_encode(['error' => 'Gagal mengambil data dari API.']);
            }
        }


    public function datadtlobatkronis()
    {
        if (isset($_POST['TANGGAL_AWAL']) && isset($_POST['TANGGAL_AKHIR'])) {
            // Mengambil input tanggal dari form
            $tanggalawal = $_POST['TANGGAL_AWAL'];
            $tanggalakhir = $_POST['TANGGAL_AKHIR'];

            // Mengonversi format tanggal ke dd/mm/yyyy
            $tanggal_awal = date('d/m/Y', strtotime($tanggalawal));
            $tanggal_akhir = date('d/m/Y', strtotime($tanggalakhir));
        

            // Mengambil data dari API
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_obat_kronis_detail',
                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(
                    'TANGGAL_AWAL' => $tanggal_awal,
                    'TANGGAL_AKHIR' => $tanggal_akhir
         
                ),
            ));

            $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 unduhdetailobtkronis()
    {

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

        $tanggal_awal = $this->input->get('TANGGAL_AWAL');
        $tanggal_akhir = $this->input->get('TANGGAL_AKHIR');

        // Ubah format tanggal jika diperlukan
        $tanggal_awali = date('d/m/Y', strtotime($tanggal_awal));
        $tanggal_akhiri = date('d/m/Y', strtotime($tanggal_akhir));



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

            ),
        ));

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

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

        ];
        $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) {
                $decoded = json_decode($response, true);
                $data = isset($decoded['response']) ? $decoded['response'] : [];

                if (empty($data)) {
                    die("Data tidak ditemukan untuk periode tersebut.");
                }

                require_once APPPATH . '../vendor/autoload.php';
                $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
                $sheet = $spreadsheet->getActiveSheet();

                // Set Header Kolom
                    $sheet->setCellValue('A1', 'Kode Penjualan');
                    $sheet->setCellValue('B1', 'No SJP');
                    $sheet->setCellValue('C1', 'Nama Pasien');
                    $sheet->setCellValue('D1', 'No Kartu');
                    $sheet->setCellValue('E1', 'Kode Obat');
                    $sheet->setCellValue('F1', 'Nama Obat');
                    $sheet->setCellValue('G1', 'Qty Jual');
                    $sheet->setCellValue('H1', 'Harga Jual');
                    $sheet->setCellValue('I1', 'Harga Beli');
                    $sheet->setCellValue('J1', 'Nama Obat BPJS');
                    $sheet->setCellValue('K1', 'Jumlah Obat');
                    $sheet->setCellValue('L1', 'Jenis Obat');
                    $sheet->setCellValue('M1', 'Harga BPJS');
                    $sheet->setCellValue('N1', 'Selisih');
                    $sheet->setCellValue('O1', 'Kode Registrasi');
                    $sheet->setCellValue('P1', 'Total Qty Jual');
                    $sheet->setCellValue('Q1', 'Total Qty BPJS Jual');
                    $sheet->setCellValue('R1', 'Total Qty Beli');
                    $sheet->setCellValue('S1', 'Total Qty BPJS');

                // ISI DATA - PASTIKAN $row++ ADA DI DALAM FOREACH
                $row = 2;
                foreach ($data as $item) {
                    $sheet->setCellValue('A' . $row, $item['kd_jual'] ?? '');
                    $sheet->setCellValue('B' . $row, $item['nosjp'] ?? '');
                    $sheet->setCellValue('C' . $row, $item['nama'] ?? '');
                    $sheet->setCellValue('D' . $row, $item['no_kartu'] ?? '');
                    $sheet->setCellValue('E' . $row, $item['kd_obat'] ?? '');
                    $sheet->setCellValue('F' . $row, $item['nama_obat'] ?? '');
                    $sheet->setCellValue('G' . $row, $item['qty_jual'] ?? '');
                    $sheet->setCellValue('H' . $row, $item['harga_jual'] ?? '');
                    $sheet->setCellValue('I' . $row, $item['harga_beli'] ?? '');
                    $sheet->setCellValue('J' . $row, $item['nm_obat'] ?? '');
                    $sheet->setCellValue('K' . $row, $item['jml_obat'] ?? '');
                    $sheet->setCellValue('L' . $row, $item['jenis_obat'] ?? '');
                    $sheet->setCellValue('M' . $row, $item['harga_bpjs'] ?? '');
                    $sheet->setCellValue('N' . $row, $item['selisih'] ?? '');
                    $sheet->setCellValue('O' . $row, $item['kd_registrasi'] ?? '');
                    $sheet->setCellValue('P' . $row, $item['total_qty_jual'] ?? '');
                    $sheet->setCellValue('Q' . $row, $item['total_qty_bpjs_jual'] ?? '');
                    $sheet->setCellValue('R' . $row, $item['total_qty_beli'] ?? '');
                    $sheet->setCellValue('S' . $row, $item['total_qty_bpjs'] ?? '');

                    $row++; // INI SANGAT PENTING: Harus bertambah setiap loop
                }

                // Bersihkan buffer untuk mencegah file rusak
                if (ob_get_contents()) ob_end_clean();

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

                $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
                $writer->save('php://output');
                exit();
            } else {
                echo json_encode(['error' => 'Gagal mengambil data dari API.']);
            }
        }
}