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

class FarmasiPO extends CI_Controller
{
    public function datafarmasiPO()
    {
        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_po',
                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 unduhdataFarmasiPO()
    {

        $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_po',
            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 PO."

        ];
        $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 PO');
                $sheet->setCellValue('B1', 'No Urut');
                $sheet->setCellValue('C1', 'No PO');
                $sheet->setCellValue('D1', 'Tanggal PO');
                $sheet->setCellValue('E1', 'Kode Suplier');
                $sheet->setCellValue('F1', 'Nama Suplier');
                $sheet->setCellValue('G1', 'Alamat Suplier');
                $sheet->setCellValue('H1', 'Kota');
                $sheet->setCellValue('I1', 'Kode Pos');
                $sheet->setCellValue('J1', 'No Telp');
                $sheet->setCellValue('K1', 'Fax');
                $sheet->setCellValue('L1', 'NPWP');
                $sheet->setCellValue('M1', 'CP Suplier');
                $sheet->setCellValue('N1', 'HP CP Suplier');
                $sheet->setCellValue('O1', 'Nama Bank');
                $sheet->setCellValue('P1', 'No Rekening');
                $sheet->setCellValue('Q1', 'Status Suplier');
                $sheet->setCellValue('R1', 'CP Internal');
                $sheet->setCellValue('S1', 'HP CP Internal');
                $sheet->setCellValue('T1', 'Penanggung Jawab (ID)');
                $sheet->setCellValue('U1', 'Nama Penanggung Jawab');
                $sheet->setCellValue('V1', 'Pencatat (ID)');
                $sheet->setCellValue('W1', 'Nama Pencatat');
                $sheet->setCellValue('X1', 'Kode Gudang');
                $sheet->setCellValue('Y1', 'Nama Gudang');
                $sheet->setCellValue('Z1', 'Sub Total');
                $sheet->setCellValue('AA1', 'Diskon (%)');
                $sheet->setCellValue('AB1', 'Nilai Diskon');
                $sheet->setCellValue('AC1', 'Pajak (%)');
                $sheet->setCellValue('AD1', 'Nilai Pajak');
                $sheet->setCellValue('AE1', 'Total Akhir');
                $sheet->setCellValue('AF1', 'Status ID');
                $sheet->setCellValue('AG1', 'Status PO');
                $sheet->setCellValue('AH1', 'Keterangan');
                $sheet->setCellValue('AI1', 'Catatan');
                $sheet->setCellValue('AJ1', 'Tgl Insert');
                $sheet->setCellValue('AK1', 'Tgl Update');

                // ISI DATA - PASTIKAN $row++ ADA DI DALAM FOREACH
                $row = 2;
                foreach ($data as $item) {
                    // --- Identitas PO ---
                    $sheet->setCellValue('A' . $row, $item['kd_po']);
                    $sheet->setCellValue('B' . $row, $item['urut_nomor']);
                    $sheet->setCellValue('C' . $row, $item['no_po']);
                    $sheet->setCellValue('D' . $row, $item['tgl_po']);
                    
                    // --- Data Suplier Lengkap ---
                    $sheet->setCellValue('E' . $row, $item['kd_suplier']);
                    $sheet->setCellValue('F' . $row, $item['nm_suplier']);
                    $sheet->setCellValue('G' . $row, $item['alamat']);
                    $sheet->setCellValue('H' . $row, $item['kd_kota']);
                    $sheet->setCellValue('I' . $row, $item['kd_pos']);
                    $sheet->setCellValue('J' . $row, $item['telp']);
                    $sheet->setCellValue('K' . $row, $item['fax']);
                    $sheet->setCellValue('L' . $row, $item['no_npwp']);
                    $sheet->setCellValue('M' . $row, $item['cp_suplier']);
                    $sheet->setCellValue('N' . $row, $item['hp_cp_suplier']);
                    $sheet->setCellValue('O' . $row, $item['nm_bank']);
                    $sheet->setCellValue('P' . $row, $item['no_rekening']);
                    $sheet->setCellValue('Q' . $row, $item['status_suplier']);

                    // --- Internal RS (CP & PJ) ---
                    $sheet->setCellValue('R' . $row, $item['cp']);
                    $sheet->setCellValue('S' . $row, $item['hp_cp']);
                    $sheet->setCellValue('T' . $row, $item['penanggung_jawab']);
                    $sheet->setCellValue('U' . $row, $item['nm_penanggung_jawab']);
                    $sheet->setCellValue('V' . $row, $item['pencatat']);
                    $sheet->setCellValue('W' . $row, $item['nm_pencatat']);
                    
                    // --- Gudang ---
                    $sheet->setCellValue('X' . $row, $item['kd_gudang']);
                    $sheet->setCellValue('Y' . $row, $item['nm_gudang']);

                    // --- Nilai Keuangan ---
                    $sheet->setCellValue('Z' . $row,  $item['sub_total']);
                    $sheet->setCellValue('AA' . $row, $item['prosen_disc']);
                    $sheet->setCellValue('AB' . $row, $item['nilai_disc']);
                    $sheet->setCellValue('AC' . $row, $item['prosen_pajak']);
                    $sheet->setCellValue('AD' . $row, $item['nilai_pajak']);
                    $sheet->setCellValue('AE' . $row, $item['total']);

                    // --- Status & Ket ---
                    $sheet->setCellValue('AF' . $row, $item['status']);
                    $sheet->setCellValue('AG' . $row, $item['status_po']);
                    $sheet->setCellValue('AH' . $row, $item['keterangan']);
                    $sheet->setCellValue('AI' . $row, $item['catatan']);
                    
                    // --- Timestamp ---
                    $sheet->setCellValue('AJ' . $row, $item['tgl_insert']);
                    $sheet->setCellValue('AK' . $row, $item['tgl_update']);
                    $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_Farmasi_PO_OBAT.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 tampildatadtlPO() // Pastikan nama fungsi sesuai dengan Routes Anda
    {
        // 1. Ambil Input (Gunakan style CodeIgniter agar lebih aman)
        $kd_po = $this->input->post('KD_PO');

        // Validasi sederhana
        if (empty($kd_po)) {
            echo "Kode PO tidak ditemukan.";
            return;
        }

        // 2. Ambil data dari API
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => '103.255.241.146/api/service_rs/farmasi_po_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(
                'KD_PO' => $kd_po,
            ),
        ));

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

        // 3. Proses Data untuk View
        $data_api = json_decode($response, true);

        // Siapkan array data untuk dikirim ke View
        // Pastikan key 'response' sesuai dengan struktur JSON API Anda
        $data['detail_po'] = isset($data_api['response']) ? $data_api['response'] : [];
        $data['kd_po_title'] = $kd_po;

        // 4. Load View HTML (Bukan echo JSON)
        // Pastikan nama file view ini sesuai dengan file view baru yang Anda buat
        $this->load->view('view_detail_po_tab', $data);
    }


    public function unduhdataPOfarmasidetail()
    {

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

        $kdPO = $this->input->get('KD_PO');


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

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

        

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

        ];
        $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) {
            $res_array = json_decode($response, true);
            
            // Pastikan mengambil key 'response' dan pastikan itu array
            $data = isset($res_array['response']) ? $res_array['response'] : [];

            if (empty($data)) {
                die("Data kosong dari API.");
            }

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

            // Set header kolom (A1 - M1)
            $sheet->setCellValue('A1', 'Kode PO');
            $sheet->setCellValue('B1', 'Kode Obat');
            $sheet->setCellValue('C1', 'Nama Barang');
            $sheet->setCellValue('D1', 'Expired Date');
            $sheet->setCellValue('E1', 'Nama Suplier');
            $sheet->setCellValue('F1', 'Tgl PO');
            $sheet->setCellValue('G1', 'Qty PO');
            $sheet->setCellValue('H1', 'Harga PO');
            $sheet->setCellValue('I1', 'Subtotal PO');
            $sheet->setCellValue('J1', 'Diskon PO');
            $sheet->setCellValue('K1', 'Total PO');
            $sheet->setCellValue('L1', 'Tgl Beli (Realisasi)');
            $sheet->setCellValue('M1', 'No Nota');
            $sheet->setCellValue('N1', 'Qty Beli');
            $sheet->setCellValue('O1', 'Harga Beli');
            $sheet->setCellValue('P1', 'Subtotal Beli');
            $sheet->setCellValue('Q1', 'Diskon Beli');
            $sheet->setCellValue('R1', 'Total Beli');
            $sheet->setCellValue('S1', 'Selisih Qty');
            $sheet->setCellValue('T1', '% Pemenuhan');

            // ISI DATA
            $row = 2; // Mulai dari baris 2
            foreach ($data as $item) {
            // --- DATA PO (RENCANA) ---
            $sheet->setCellValue('A' . $row, $item['kd_po']);
            $sheet->setCellValue('B' . $row, $item['kd_obat']);
            $sheet->setCellValue('C' . $row, $item['nm_barang']);
            $sheet->setCellValue('D' . $row, $item['expired_date']);
            $sheet->setCellValue('E' . $row, $item['nm_suplier']);
            $sheet->setCellValue('F' . $row, $item['tgl_po']);
            
            // Angka PO
            $sheet->setCellValue('G' . $row, $item['qty_po']);
            $sheet->setCellValue('H' . $row, $item['harga_po']);
            $sheet->setCellValue('I' . $row, $item['subtotal_po']);
            $sheet->setCellValue('J' . $row, $item['diskon_po']);
            $sheet->setCellValue('K' . $row, $item['total_po']);

            // --- DATA PEMBELIAN (REALISASI) ---
            // Menggunakan ?? '' atau ?? 0 karena di JSON nilainya null
            $sheet->setCellValue('L' . $row, $item['tgl_beli'] ?? '-');
            $sheet->setCellValue('M' . $row, $item['no_nota'] ?? '-');
            $sheet->setCellValue('N' . $row, $item['qty_pembelian'] ?? 0);
            $sheet->setCellValue('O' . $row, $item['harga_pembelian'] ?? 0);
            $sheet->setCellValue('P' . $row, $item['subtotal_pembelian'] ?? 0);
            $sheet->setCellValue('Q' . $row, $item['diskon_pembelian'] ?? 0);
            $sheet->setCellValue('R' . $row, $item['total_pembelian'] ?? 0);

            // --- ANALISA ---
            $sheet->setCellValue('S' . $row, $item['selisih_qty']);
            $sheet->setCellValue('T' . $row, $item['persentase_pemenuhan']);
                
                $row++; // Memastikan baris bertambah untuk data berikutnya
            }

            // Tambahkan ini agar file tidak korup/kosong
            if (ob_get_contents()) ob_end_clean();

            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="Data_Farmasi_PO_Detail.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.']);
        }
    }
}