<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv as Csv_writer;

class Csv_export
{

    public function export($type = '', $tags = '')
    {
        $ci = get_instance();

        $ci->load->model('newsletter/newsletter_email_tmodel');
        if (!empty($tags)) {
            $ci->newsletter_email_tmodel->set_predicates(['tags' => $tags]);
        }
        $data = $ci->newsletter_email_tmodel->set_select('email')->fetch_all();

        $spreadsheet = new Spreadsheet();
        $spreadsheet->getProperties()->setCreator('Ciext');
        $sheet = $spreadsheet->getActiveSheet();
        
        $i = 1;
        foreach ($data as $item) {
            $sheet->setCellValue('A' . $i, $item['email']);
            $i++;
        }

        header('Content-type: text/csv');
        header('Content-Disposition: attachment;filename="newsletter_' . $type . '_' . date('Y-m-d') . '.csv"');
        header('Cache-Control: max-age=0');

        $writer = new Csv_writer($spreadsheet);
        $writer->save('php://output');
        exit;
    }

}
