<?php

namespace App\Controllers;

use App\Libraries\Pdf;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

use App\Models\ModelLaporan;
use App\Models\ModelBookings;
use CodeIgniter\Controller;

class Laporan extends Controller
{
    protected $modelLaporan;
    protected $modelBookings;
    protected $modelRekening;
    protected $modelSiswa;

    public function __construct()
    {
        $this->modelLaporan = new ModelLaporan();
        $this->modelBookings = new ModelBookings();
    }

    public function Bookings()
    {
        $dataBookings = $this->modelBookings->getAllData();

        $data = [
            'Breadcumb' => 'Laporan Bookings',
            'bookings' => $dataBookings
        ];

        return view('laporan/bookings', $data);
    }

    public function filterBookings()
    {
        $tanggal_awal = $this->request->getPost('tanggal_awal');
        $tanggal_akhir = $this->request->getPost('tanggal_akhir');

        $query = $this->modelBookings
            ->select('bookings.*, customer.name as customer_name, services.name as service_name, services.price')
            ->join('customer', 'customer.id_customer = bookings.id_customer')
            ->join('services', 'services.id_service = bookings.id_service');

        if ($tanggal_awal && $tanggal_akhir) {
            $query->where('DATE(bookings.booking_time) >=', $tanggal_awal)
                ->where('DATE(bookings.booking_time) <=', $tanggal_akhir);
        }

        $data = $query->orderBy('bookings.booking_time', 'DESC')->findAll();

        return $this->response->setJSON($data);
    }

    public function mutasi()
    {
        $dataRekening = $this->modelRekening->getAllData();
        $dataSiswa = $this->modelSiswa->getAllData();
        $dataTransaksi = $this->modelTransaksi->getAllData();

        $data = [
            'Breadcumb' => 'Laporan Mutasi',
            'rekening' => $dataRekening,
            'siswa' => $dataSiswa,
            'transaksi' => $dataTransaksi
        ];

        return view('laporan/mutasi', $data);
    }

    public function filterMutasi()
    {
        $tanggal_awal = $this->request->getPost('tanggal_awal');
        $tanggal_akhir = $this->request->getPost('tanggal_akhir');
        $id_siswa = $this->request->getPost('id_siswa');

        $data = $this->modelTransaksi->getFilteredData($tanggal_awal, $tanggal_akhir, $id_siswa);
        return $this->response->setJSON($data);
    }

    public function cetakPDF()
    {
        $tanggalAwal = $this->request->getGet('tanggal_awal') . ' 00:00:00';
        $tanggalAkhir = $this->request->getGet('tanggal_akhir') . ' 23:59:59';

        $tableName = 'balita';  // Nama tabel yang diterima dari form atau parameter

        // Menetapkan tabel dinamis
        $this->ModelLaporan->setTableName($tableName);

        $data['laporan'] = $this->ModelLaporan->filterLaporan($tanggalAwal, $tanggalAkhir);
        $data['tanggalAwal'] = $tanggalAwal;
        $data['tanggalAkhir'] = $tanggalAkhir;

        // Ambil data dari tabel settings untuk header
        $settingsModel = new SettingsModel();

        // Ambil data berdasarkan kolom yang diinginkan (nilai, keterangan, logo)
        $settingsData = $settingsModel->getSettingValue();

        // Mengambil nilai, keterangan, dan logo dari data settings
        foreach ($settingsData as $setting) {
            $data['company_name'] = $setting['nilai'];        // Menyimpan nama perusahaan
            $data['company_address'] = $setting['keterangan']; // Menyimpan alamat perusahaan
            $data['company_logo'] = $setting['logo'];         // Menyimpan logo perusahaan
        }


        // Inisialisasi PDF dengan menggunakan library yang lebih sederhana
        $pdf = new Pdf();  // Pastikan Anda sudah memiliki library Pdf dengan method load_view
        $pdf->load_view('laporan/laporanbalitapdf', $data); // Proses render dan tampilkan PDF
    }

    public function exportExcel()
    {
        // Ambil data filter tanggal
        $tanggalAwal = $this->request->getGet('tanggal_awal') . ' 00:00:00';
        $tanggalAkhir = $this->request->getGet('tanggal_akhir') . ' 23:59:59';

        // Load Models
        $ModelLaporan = new ModelLaporan();
        $settingsModel = new SettingsModel();

        // Ambil data perusahaan dari tabel settings
        $settingsData = $settingsModel->getSettingValue();
        $companyName = '';  // Default value
        $companyAddress = '';  // Default value
        $companyLogo = '';  // Default value

        foreach ($settingsData as $setting) {
            $companyName = $setting['nilai'];        // Nama Perusahaan
            $companyAddress = $setting['keterangan']; // Alamat Perusahaan
            $companyLogo = $setting['logo'];         // Logo Perusahaan
        }

        // Set table name and get data
        $ModelLaporan->setTableName('balita');
        $laporanData = $ModelLaporan->filterLaporan($tanggalAwal, $tanggalAkhir);

        // Buat objek Spreadsheet baru
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // Tambahkan Nama Perusahaan, Alamat dan Logo
        $sheet->setCellValue('A1', $companyName);  // Nama Perusahaan
        $sheet->mergeCells('A1:L1');  // Merge cells for company name
        $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(16);  // Bold & larger font for company name

        $sheet->setCellValue('A2', $companyAddress);  // Alamat Perusahaan
        $sheet->mergeCells('A2:L2');  // Merge cells for company address
        $sheet->getStyle('A2')->getFont()->setItalic(true)->setSize(12);  // Italic font for address

        // If company logo exists, insert it into the spreadsheet
        if ($companyLogo) {
            $logoPath = WRITEPATH . 'uploads/logos/' . $companyLogo; // Assuming logo is stored in this path
            if (file_exists($logoPath)) {
                $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                $drawing->setName('Company Logo');
                $drawing->setPath($logoPath);
                $drawing->setHeight(60); // Set height of the logo
                $drawing->setCoordinates('A3');
                $drawing->setWorksheet($sheet);
            }
        }

        // Set header untuk tabel data
        $sheet->setCellValue('A4', 'No');
        $sheet->setCellValue('B4', 'Nama');
        $sheet->setCellValue('C4', 'NIK');
        $sheet->setCellValue('D4', 'Alamat');
        $sheet->setCellValue('E4', 'Nama Ibu');
        $sheet->setCellValue('F4', 'Nama Ayah');
        $sheet->setCellValue('G4', 'Jenis Kelamin');
        $sheet->setCellValue('H4', 'Tanggal Lahir');
        $sheet->setCellValue('I4', 'Berat Badan');
        $sheet->setCellValue('J4', 'Tinggi Badan');
        $sheet->setCellValue('K4', 'Status Imunisasi');
        $sheet->setCellValue('L4', 'Tanggal Dibuat');

        // Isi data laporan ke sheet
        $row = 5; // Mulai dari baris ke-5 untuk data
        foreach ($laporanData as $index => $data) {
            $sheet->setCellValue('A' . $row, $index + 1);
            $sheet->setCellValue('B' . $row, $data['nama']);
            $sheet->setCellValue('C' . $row, $data['nik']);
            $sheet->setCellValue('D' . $row, $data['alamat']);
            $sheet->setCellValue('E' . $row, $data['nama_ibu']);
            $sheet->setCellValue('F' . $row, $data['nama_ayah']);
            $sheet->setCellValue('G' . $row, $data['jenis_kelamin']);
            $sheet->setCellValue('H' . $row, date('d-m-Y', strtotime($data['tanggal_lahir'])));
            $sheet->setCellValue('I' . $row, number_format($data['berat_badan'], 2));
            $sheet->setCellValue('J' . $row, number_format($data['tinggi_badan'], 2));
            $sheet->setCellValue('K' . $row, $data['status_imunisasi']);
            $sheet->setCellValue('L' . $row, date('d-m-Y', strtotime($data['created_at'])));
            $row++;
        }

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

        // Tulis file Excel dan outputkan
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
    }
}
