<?php
namespace Modules\Form_contato\Controllers;

use App\Controllers\BaseController;
use Modules\Form_contato\Models\model_form_contato;

require "Libraries/phpspreadsheet/autoload.php";

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

class Form_contato extends BaseController {
	public function __construct() {
		$this->model_form_contato = new Model_form_contato;
	}

	public function index() {
	}
	
	public function listagem() {
		$dados['form_contato'] = $this->model_form_contato->getCadastros();

		$this->dataHelper->DH_actionRecord();
		$this->_cms('Modules\Form_contato\Views\view_form_contato_listar', $dados);
	}

	public function alterar($id) {
		$dados['id']            = $id;
		$dados['form_contato']  = $this->model_form_contato->alterar($id);

		$this->dataHelper->DH_actionRecord($id);
		$this->_cms('Modules\Form_contato\Views\view_form_contato_cadastrar', $dados);
	}

	public function deletar($id) {
		$this->model_form_contato->deletar($id);
		$this->dataHelper->DH_actionRecord($id);
		service('session')->set('msg', array('titulo' => 'Remoção realizada', 'descricao' => 'Cadastro foi removido com sucesso', 'tipo' => 'success'));
		return redirect()->to(site_url(service('request')->uri->getSegment(1)));
	}

	public function xlsx() {
		$today    = date("Y-m-d");
		$filename = "listagem-de-contatos-" . $today . ".xlsx";

		$alfabeto = range('A', 'Z');
		$colunas  = $this->dataHelper->DH_getTableColumns('form_contato');

		$spreadsheet = new Spreadsheet();

		foreach ($colunas as $key => $coluna) {
			$c = $alfabeto[$key] . '1';
			$spreadsheet->getActiveSheet()->setCellValue($c, $coluna);
		}

		$firstReg = $alfabeto[0] . '1';
		$lastKey 	= array_key_last($colunas);
		$lastReg 	= $alfabeto[$lastKey] . '1';

		$spreadsheet->getActiveSheet()->getStyle($firstReg . ":" . $lastReg)->applyFromArray(array('font' => ['bold' => true]));

		$rowCount = 2;
		$consulta = $this->model_form_contato->getCadastros();

		foreach($consulta as $kc => $valor) {
			foreach ($colunas as $k => $coluna) {
				$c = $alfabeto[$k] . $rowCount;
				$spreadsheet->getActiveSheet()->SetCellValue($c, mb_strtoupper($valor->$coluna,'UTF-8'));
			}

			$rowCount++;
		}

		$this->dataHelper->DH_actionRecord();

		header('Content-Type: application/vnd.ms-excel'); 
		header('Content-Disposition: attachment;filename="' . $filename . '"'); 
		header('Cache-Control: max-age=0'); 

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

		die();
	}
}