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

class Kasirbilling extends CI_Controller
{

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     * 		http://example.com/index.php/welcome
     *	- or -
     * 		http://example.com/index.php/welcome/index
     *	- or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/userguide3/general/urls.html
     */

    public function datakasirall()
    {
        // Atur header sebagai JSON di awal untuk semua kemungkinan output
        header('Content-Type: application/json');

        // Pastikan ini adalah request POST
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            // Mengirim error jika bukan method POST
            echo json_encode(['status' => 'error', 'message' => 'Metode request tidak valid.']);
            return;
        }

        if (!isset($_POST['TANGGAL_AWAL']) || !isset($_POST['TANGGAL_AKHIR'])) {
            echo json_encode(['status' => 'error', 'message' => 'Parameter tanggal tidak lengkap.']);
            return;
        }


        try {
            // Mengambil dan memformat tanggal
            $tanggal_awal_input = $_POST['TANGGAL_AWAL'];
            $tanggal_akhir_input = $_POST['TANGGAL_AKHIR'];

            $tanggal_awal_formatted = date('d/m/Y', strtotime($tanggal_awal_input));
            $tanggal_akhir_formatted = date('d/m/Y', strtotime($tanggal_akhir_input));

            // --- 1. PANGGIL API UNTUK DATA UTAMA (TABEL T2) ---
            $curl_main = curl_init();
            curl_setopt_array($curl_main, array(
                CURLOPT_URL => 'http://103.255.241.146/api/service_rs/kasir_all', // Tambahkan http://
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => ['TANGGAL_AWAL' => $tanggal_awal_formatted, 'TANGGAL_AKHIR' => $tanggal_akhir_formatted],
            ));
            $response_main_raw = curl_exec($curl_main);
            $curl_error_main = curl_error($curl_main);
            curl_close($curl_main);

            // --- 2. PANGGIL API UNTUK DATA RINGKASAN (TABEL T1) ---
            $curl_summary = curl_init();
            curl_setopt_array($curl_summary, array(
                CURLOPT_URL => 'http://103.255.241.146/api/service_rs/kasir_all_sum', // Tambahkan http://
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => ['TANGGAL_AWAL' => $tanggal_awal_formatted, 'TANGGAL_AKHIR' => $tanggal_akhir_formatted],
            ));
            $response_summary_raw = curl_exec($curl_summary);
            $curl_error_summary = curl_error($curl_summary);
            curl_close($curl_summary);

            if ($curl_error_main || $curl_error_summary) {
                throw new Exception('Gagal terhubung ke API layanan.');
            }

            $data_main = json_decode($response_main_raw, true);
            $data_summary = json_decode($response_summary_raw, true);

            // Periksa apakah JSON valid setelah decode
            if (json_last_error() !== JSON_ERROR_NONE) {
                throw new Exception('Gagal mem-parsing data dari API.');
            }

            // --- 3. GABUNGKAN KEDUA HASIL MENJADI SATU ARRAY ---
            $final_response = [
                'status'   => 'success',
                'response' => $data_main['response'] ?? [],
                'summary'  => $data_summary['response'] ?? []
            ];

            echo json_encode($final_response);
        } catch (Exception $e) {
            // Menangkap semua kemungkinan error dan mengirimkannya sebagai JSON
            echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    public function unduhbillingkasirall()
    {
        $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/kasir_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',
            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 Billing Kasir All."

        ];
        $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 Bayar');
            $sheet->setCellValue('B1', 'No Bayar');
            $sheet->setCellValue('C1', 'Kode Registrasi');
            $sheet->setCellValue('D1', 'Jumlah');
            $sheet->setCellValue('E1', 'Selisih');
            $sheet->setCellValue('F1', 'Biaya Transaksi');
            $sheet->setCellValue('G1', 'Tgl Catat');
            $sheet->setCellValue('H1', 'Tgl Bayar');
            $sheet->setCellValue('I1', 'Tgl Cair');
            $sheet->setCellValue('J1', 'Pencatat');
            $sheet->setCellValue('K1', 'Keterangan');
            $sheet->setCellValue('L1', 'Catatan');
            $sheet->setCellValue('M1', 'No Index Transaksi');
            $sheet->setCellValue('N1', 'No Tagihan');
            $sheet->setCellValue('O1', 'Jumlah Tagihan Pribadi');
            $sheet->setCellValue('P1', 'Total Tagihan');
            $sheet->setCellValue('Q1', 'NIP Petugas');



            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_bayar']);
                $sheet->setCellValue('B' . $row, $item['no_bayar']);
                $sheet->setCellValue('C' . $row, $item['kd_registrasi']);
                $sheet->setCellValue('D' . $row, $item['jumlah']);
                $sheet->setCellValue('E' . $row, $item['selisih']);
                $sheet->setCellValue('F' . $row, $item['biaya_transaksi']);
                $sheet->setCellValue('G' . $row, $item['tgl_catat']);
                $sheet->setCellValue('H' . $row, $item['tgl_bayar']);
                $sheet->setCellValue('I' . $row, $item['tgl_cair']);
                $sheet->setCellValue('J' . $row, $item['pencatat']);
                $sheet->setCellValue('K' . $row, $item['keterangan']);
                $sheet->setCellValue('L' . $row, $item['catatan']);
                $sheet->setCellValue('M' . $row, $item['no_index_transaksi']);
                $sheet->setCellValue('N' . $row, $item['no_tagihan']);
                $sheet->setCellValue('O' . $row, $item['jumlah_tagihan_pribadi']);
                $sheet->setCellValue('P' . $row, $item['total_tagihan']);
                $sheet->setCellValue('Q' . $row, $item['nip_pencatat']);
                $row++;
            }

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

            // 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 datakasirperbank()
    {

        // Atur header sebagai JSON di awal untuk semua kemungkinan output
        header('Content-Type: application/json');

        // Pastikan ini adalah request POST
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            // Mengirim error jika bukan method POST
            echo json_encode(['status' => 'error', 'message' => 'Metode request tidak valid.']);
            return;
        }

        if (!isset($_POST['TANGGAL_AWAL']) || !isset($_POST['TANGGAL_AKHIR']) || !isset($_POST['KD_BANK'])) {
            echo json_encode(['status' => 'error', 'message' => 'Parameter tanggal tidak lengkap.']);
            return;
        }


        try {
            // Mengambil dan memformat tanggal
            $tanggal_awal_input = $_POST['TANGGAL_AWAL'];
            $tanggal_akhir_input = $_POST['TANGGAL_AKHIR'];
            $kdbank = $_POST['KD_BANK'];

            $tanggal_awal_formatted = date('d/m/Y', strtotime($tanggal_awal_input));
            $tanggal_akhir_formatted = date('d/m/Y', strtotime($tanggal_akhir_input));

            // --- 1. PANGGIL API UNTUK DATA UTAMA (TABEL T2) ---
            $curl_main = curl_init();
            curl_setopt_array($curl_main, array(
                CURLOPT_URL => 'http://103.255.241.146/api/service_rs/kasir_perbank', // Tambahkan http://
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => ['TANGGAL_AWAL' => $tanggal_awal_formatted, 'TANGGAL_AKHIR' => $tanggal_akhir_formatted, 'KD_BANK' => $kdbank],
            ));
            $response_main_raw = curl_exec($curl_main);
            $curl_error_main = curl_error($curl_main);
            curl_close($curl_main);

            // --- 2. PANGGIL API UNTUK DATA RINGKASAN (TABEL T1) ---
            $curl_summary = curl_init();
            curl_setopt_array($curl_summary, array(
                CURLOPT_URL => 'http://103.255.241.146/api/service_rs/kasir_perbank_sum', // Tambahkan http://
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => ['TANGGAL_AWAL' => $tanggal_awal_formatted, 'TANGGAL_AKHIR' => $tanggal_akhir_formatted, 'KD_BANK' => $kdbank],
            ));
            $response_summary_raw = curl_exec($curl_summary);
            $curl_error_summary = curl_error($curl_summary);
            curl_close($curl_summary);

            if ($curl_error_main || $curl_error_summary) {
                throw new Exception('Gagal terhubung ke API layanan.');
            }

            $data_main = json_decode($response_main_raw, true);
            $data_summary = json_decode($response_summary_raw, true);

            // Periksa apakah JSON valid setelah decode
            if (json_last_error() !== JSON_ERROR_NONE) {
                throw new Exception('Gagal mem-parsing data dari API.');
            }

            // --- 3. GABUNGKAN KEDUA HASIL MENJADI SATU ARRAY ---
            $final_response = [
                'status'   => 'success',
                'response' => $data_main['response'] ?? [],
                'summary'  => $data_summary['response'] ?? []
            ];

            echo json_encode($final_response);
        } catch (Exception $e) {
            // Menangkap semua kemungkinan error dan mengirimkannya sebagai JSON
            echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
    }

    public function unduhkasirperbankanall()
    {
        $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/kasir_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',
            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 Billing Kasir All."

        ];
        $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 Bayar');
            $sheet->setCellValue('B1', 'No Bayar');
            $sheet->setCellValue('C1', 'Kode Registrasi');
            $sheet->setCellValue('D1', 'Jumlah');
            $sheet->setCellValue('E1', 'Selisih');
            $sheet->setCellValue('F1', 'Biaya Transaksi');
            $sheet->setCellValue('G1', 'Tgl Catat');
            $sheet->setCellValue('H1', 'Tgl Bayar');
            $sheet->setCellValue('I1', 'Pencatat');
            $sheet->setCellValue('J1', 'Keterangan');
            $sheet->setCellValue('K1', 'Catatan');
            $sheet->setCellValue('L1', 'No Index Transaksi');
            $sheet->setCellValue('M1', 'No Tagihan');
            $sheet->setCellValue('N1', 'Jumlah Tagihan Pribadi');
            $sheet->setCellValue('O1', 'Total Tagihan');
            $sheet->setCellValue('P1', 'NIP Petugas');



            // Isi data
            $row = 2;
            foreach ($data as $item) {
                $sheet->setCellValue('A' . $row, $item['kd_bayar']);
                $sheet->setCellValue('B' . $row, $item['no_bayar']);
                $sheet->setCellValue('C' . $row, $item['kd_registrasi']);
                $sheet->setCellValue('D' . $row, $item['jumlah']);
                $sheet->setCellValue('E' . $row, $item['selisih']);
                $sheet->setCellValue('F' . $row, $item['biaya_transaksi']);
                $sheet->setCellValue('G' . $row, $item['tgl_catat']);
                $sheet->setCellValue('H' . $row, $item['tgl_bayar']);
                $sheet->setCellValue('I' . $row, $item['pencatat']);
                $sheet->setCellValue('J' . $row, $item['keterangan']);
                $sheet->setCellValue('K' . $row, $item['catatan']);
                $sheet->setCellValue('L' . $row, $item['no_index_transaksi']);
                $sheet->setCellValue('M' . $row, $item['no_tagihan']);
                $sheet->setCellValue('N' . $row, $item['jumlah_tagihan_pribadi']);
                $sheet->setCellValue('O' . $row, $item['total_tagihan']);
                $sheet->setCellValue('P' . $row, $item['nip_pencatat']);
                $row++;
            }

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

            // 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 kasirtotalpendapatan()
    {
        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/kasir_all_sum_grand',
                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.']);
            }
        }
    }

    
}
