<?php
	defined('BASEPATH') OR exit('No direct script access allowed');
	
	use PhpOffice\PhpSpreadsheet\Spreadsheet;
	use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
	
	class Export extends CI_Controller {
		
		public function __construct()
		{
			parent::__construct();
			// Load helper untuk download
			$this->load->helper('download');
		}
		
		public function index()
		{
			$data['title'] = 'Export';
			$this->load->view("export", $data);
		}
		
		// Controller dengan URL untuk download file
		public function export_to_excel()
		{
			// Mengambil data dari POST
			$data = $this->input->post('data');
			
			if (empty($data)) {
				echo json_encode(['error' => 'No data received']);
				return;
			}
			
			// Membuat objek Spreadsheet
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet();
			
			// Memasukkan data ke dalam worksheet
			$row = 1;
			foreach ($data as $rowData) {
				$col = 1;
				foreach ($rowData as $cell) {
					$sheet->setCellValueByColumnAndRow($col, $row, $cell);
					$col++;
				}
				$row++;
			}
			
			// Menyimpan file Excel sementara
			$filename = 'exported_data.xlsx';
			$file_path = './uploads/' . $filename;
			
			$writer = new Xlsx($spreadsheet);
			$writer->save($file_path);
			
			// Menanggapi dengan URL untuk file yang disimpan
			echo json_encode(['url' => base_url('uploads/' . $filename)]);
		}
		
	}
