<?php

class ControllerCatalogPdfUpload extends Controller
{

    public function index()
    {
        $language = $this->language->load('catalog/pdf_upload');
        $this->data = array_merge($this->data, $language);

        $this->document->setTitle($this->language->get('heading_title'));
        $this->document->addScript('view/javascript/template/catalog/pdf_upload.js');

        $this->breadcrumbs();
        $this->load->type('tipocomum');

        $this->children = array(
            'common/header',
            'common/footer'
        );

        $this->data['data'] = $this->getAllPdfs();
        
        $this->response->setOutput($this->render('catalog/pdf_upload'));
    }

    private function breadcrumbs()
    {
        $this->data['breadcrumbs'] = array();

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => false
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('catalog/pdf_upload', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => ' :: '
        );
    }

    private function getAllPdfs()
    {
        $basePath = DIR_DOWNLOAD . 'pdf/';
        $pdfs = $this->recursivePdfFiles($basePath);

        return $pdfs;
    }

    public function recursivePdfFiles($directory = DIR_DOWNLOAD . 'pdf/')
    {
        $results = [];

        $files = glob(rtrim($directory, '/') . '/*');

        foreach ($files as $file) {
            if (is_dir($file)) {
                $results = array_merge($results, $this->recursivePdfFiles($file));
            } elseif (is_file($file) && strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'pdf') {
                $relativePath = utf8_substr($file, utf8_strlen(DIR_DOWNLOAD));
                $results[] = [
                    'filename' => basename($file),
                    'relative' => $relativePath,
                    'linkdireto' => $this->getBaseDownloadUrl() . 'pdf/' . utf8_substr($relativePath, strlen('pdf/'))
                ];                
            }
        }

        return $results;
    }

    private function getBaseDownloadUrl()
    {
        $baseUrl = $this->config->get('config_linkproducao_ssl');

        if (substr($baseUrl, -1) !== '/') {
            $baseUrl .= '/';
        }

        return $baseUrl . 'download/';
    }
}