<?php

/*
 * Copyright (c) 2018 Earworks.
 * Codeigniter Project Template Modification
 * Please contact our email for more information :
 *  contact@earworks.co.id
 */
defined('BASEPATH') OR exit('No direct script access allowed');
include_once APPPATH . '/third_party/phpexcel/PHPExcel.php';

/**
 * Description of Excel_lib
 *
 * @author Andhy Taslin <andhy@earworks.co.id>
 * @since 1.0
 */
class Excel_lib {

    public $filename;
    public $sheets;
    public $options;
    public $format = 'Excel2007';
    private $objExcel;

    public function __construct($config = array()) {
        foreach ($config as $key => $val) {
            if (property_exists('Excel_lib', $key)) {
                $this->$key = $val;
            }
        }
        $this->init();
    }
    public function init() {

        if (!class_exists('PHPExcel')) {
            exit('Class "PHPExcel" UNDEFINED');
        }

        // create Excel Object
        $this->objExcel = new PHPExcel();

        if (is_array($this->sheets)) {
            foreach ($this->sheets as $key => $val) {
                $this->createSheet($key, $val);
            }
        } elseif (is_string($this->sheets)) {
            $this->createSheet(0, $this->sheets);
        } else {
            $this->createSheet(0, 'worksheet');
        }
    }

    private function createSheet($index, $name = null) {
        $this->objExcel->addSheet(new PHPExcel_Worksheet($this->objExcel, $name), $index);
    }

    public function write($source = array(), $onSheet = 0) {
        if (is_string($onSheet)) {
            $this->objExcel->setActiveSheetIndexByName($onSheet);
        } else {
            $this->objExcel->setActiveSheetIndex($onSheet);
        }
        if (isset($this->options['columnWidth'])) {
            foreach ($this->options['columnWidth'][$this->objExcel->getActiveSheetIndex()] as $key => $val) {
                $this->objExcel->getActiveSheet()->getColumnDimension($key)->setWidth($val);
            }
        }
        $this->objExcel->getActiveSheet()->fromArray($source);
    }

    public function output() {
        
       header('Content-Type: application/vnd.ms-excel');
       header('Content-Disposition: attachment;filename="' . $this->filename . '"');
       header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($this->objExcel, $this->format);
        $objWriter->save('php://output');
        exit;
    }

    public function readexcel($file = null) {
        try {
            $inputFileType = PHPExcel_IOFactory::identify($file);
            $objReader = PHPExcel_IOFactory::createReaderForFile($file);
            $objPHPExcel = $objReader->load($file);
            $sheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
            return $sheet;
        } catch (Exception $e) {
            die('Error loading file "' . pathinfo($file, PATHINFO_BASENAME) . '": ' . $e->getMessage());
        }
    }

}
