<?php

use Clegginabox\PDFMerger\PDFMerger as Merger;
class Pdfmerger extends MY_Controller
{

    /**
     * Get All Data from this method.
     *
     * @return Response
     */
    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        $this->load->database();
    }

    public function note_get()
    {
        $noteids = $this->input->get('noteids');
        $this->load->model('Note_model', 'notes_model');
        $notes = $this->notes_model->getByIds($noteids);
        // print_r($notes);
        $date = date('Y-m-d');
        $guid = $this->GUID();
        $uploadpath = UPLOADSPATH . DS . $notes[0]['tenant_no'] . DS . "notes" . DS;
        $filename = $guid . '.pdf';
        $filepath = $uploadpath . $filename;
        $pdf = new Merger();
        foreach ($notes as $k => $v) {
            //           log_message('debug','filepath:'.$uploadpath.$v['filename']);
            $file = str_replace(array('jpg', 'xlsx'), array('pdf', 'pdf'), $v['filename']);
            $pdf->addPDF($uploadpath . $file, 'all');
        }
        $pdf->merge('file', $filepath);

        $ret = array('filename' => $filename, 'success' => true);
        $this->response($ret, MY_Controller::HTTP_OK);
    }

    function GUID()
    {
        if (function_exists('com_create_guid') === true) {
            return trim(com_create_guid(), '{}');
        }

        return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
    }
}
