<?php

class PdfExportController extends Controller {

    public function filters() {
        return array(
            array('application.filters.SyslogFilter'),
        );
    }

    /**
     * returns the user pdf repository DirectoryIterator
     * @return DirectoryIterator the user pdf folder iterator
     * */
    private function getUserRepositoryIterator($username = null) {
        $repo = $this->getUserRepositoryPath($username);

        $dirit = new DirectoryIterator($repo);
        $dirit->folder_path = $repo;
        return $dirit;
    }

    /**
     * returns the user pdf repository path
     * @return string the user pdf folder path
     * */
    private function getUserRepositoryPath($username = null) {
        if (empty($username))
            $username = user()->model->username;
        $repo = paramdeep('pdfRepositoryBaseFolder') . $username . '\\';

        if (!file_exists($repo))
            mkdir($repo, null, true);

        return $repo;
    }

    public function actionGetFromRepository($pdfId = null, $userId = null) {
        access_denied_check('pdf_view_repository');

        $me = user()->model;
        if ($userId == null || $userId == $me->id) {
            $user = $me;
        } else {
            access_denied_check('pdf_view_repository_full');
            $user = User::model()->findByPk($userId);
            if ($user === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }

        $repository = $this->getUserRepositoryIterator($user->username);
        $pdf = null;
        foreach ($repository as $pdf_file) {
            if (!$pdf_file->isDot() && $pdf_file->isFile()) {
                $currId = md5($pdf_file->getPathname());
                if ($pdfId == $currId) {
                    $pdf = $pdf_file;
                    break;
                }
            }
        }
        if ($pdf == null)
            throw new CHttpException(404, "File not found");
        prepare_download($pdf_file->getFilename());
        readfile($pdf_file->getPathname());
        exit;
    }

    public function actionPdfRepository($id = null) {
        access_denied_check('pdf_view_repository');

        $me = user()->model;
        if ($id == null || $id == $me->id) {
            $user = $me;
        } else {
            access_denied_check('pdf_view_repository_full');
            $user = User::model()->findByPk($id);
            if ($user === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }

        $dirit = $this->getUserRepositoryIterator($user->username);
        $this->render('pdfRepository', array('repository' => $dirit, 'user' => $user));
    }

    public function actionExportPdf($htmlVarData, $htmlVarPreview, $title = null) {
        access_denied_check('export_pdf');

        $model = new ExportPdfForm;

        $model->varData = $htmlVarData;
        $model->varPreview = $htmlVarPreview;

        if (!not_empty_string($model->title)) {
            if (is_null($title))
                $title = t('no_title');

            $model->title = $title;
        }

        if (!file_exists(Yii::app()->params['exportPdfCertificate']))
            Yii::app()->user->setFlash('notice', Yii::t('app', 'WARNING: The system cannot sign the PDF: certificate not found!'));

        if (isset($_POST['ExportPdfForm'])) {
            $model->attributes = $_POST['ExportPdfForm'];

            $info = $_POST['ExportPdfForm'];


            $doPdf = true;
            $adminPwdRequired = false;
            $viewPwdRequired = false;

            switch (Yii::app()->params['pdfPassword']) {
                case 'all':
                default:
                    $adminPwdRequired = true;
                    $viewPwdRequired = true;
                    break;
                case 'admin':
                    $adminPwdRequired = false;
                    break;
                case 'view':
                    $viewPwdRequired = false;
                    break;
                case 'none':
                    //do nothing
                    break;
            }


            if ($viewPwdRequired && $info['viewer_password'] == '') {
                $model->addError('viewer_password', Yii::t('app', 'Password cannot be empty!'));
                $doPdf = false;
            } else {
                $model->viewer_password = $info['viewer_password'];
            }
            if (!$adminPwdRequired && $info['admin_password'] != '') {
                $model->addError('admin_password', Yii::t('app', 'Password cannot be empty!'));
                $doPdf = false;
            } else {
                $model->admin_password = $info['admin_password'];
            }

            if ($doPdf) {
                $this->layout = '//layouts/pdf';
                $html = TempDataBuffer::instance()->getValue($model->varData);

                $this->exportPdf($html, $info['viewer_password'], $info['admin_password'], $info['title']);
            }
        }

        $this->render('exportpdf', array('model' => $model, 'modelfocus' => 'viewer_password'));
    }

    public function actionPreview($html) {

        $html = TempDataBuffer::instance()->getValue($html);

        echo "<div class= 'export-preview-content'>";
        echo $html;
        echo "</div>";

        Yii::app()->end();
    }

    private function exportPdf($html, $viewrPwd, $adminPwd, $title) {
        $certificate = Yii::app()->params['exportPdfCertificate'];
        $certificateFound = file_exists($certificate);
        $certificatewarning = $certificateFound ? "" : Yii::t('app', 'NOT SIGNED');

        $pdf = new PDFTools();

        $pdf->html = $html;


        switch (Yii::app()->params['pdfPassword']) {
            case 'all':
            default:
                $pdf->viewerPassword = $viewrPwd;
                $pdf->adminPassword = $adminPwd;
                $pdf->encryptionStrength = PDFTools::ENCRYPTION_STRENGTH_AES256; // l'encryption incide sulla portabilità del documento
                break;
            case 'admin':
                $pdf->adminPassword = $adminPwd;
                $pdf->encryptionStrength = PDFTools::ENCRYPTION_STRENGTH_AES256; // l'encryption incide sulla portabilità del documento
                break;
            case 'view':
                $pdf->viewerPassword = $viewrPwd;
                $pdf->encryptionStrength = PDFTools::ENCRYPTION_STRENGTH_AES256; // l'encryption incide sulla portabilità del documento
                break;
            case 'none':
                //do nothing
                break;
        }

        $pdf->author = ('Kria Event Server');
        $pdf->creator = ('Kria Event Server');
        //$pdf->subject = ('COMUNE DI TORINO - STAMPA TRANSITO');
        //$pdf->title = ("$eventDate - $eventTime - $event->Plate - $event->GateDescription".($certificateFound ? "" : Yii::t('app', 'NOT SIGNED')));

        $pdf->certificateExtraInfo_Name = 'EXPORT';
        $pdf->certificateExtraInfo_Location = 'Kria Event Server';
        $pdf->certificateExtraInfo_Reason = 'Export Report';
        $pdf->certificateExtraInfo_ContactInfo = 'http://www.kria.biz';

        $pdf->certificateFile = $certificate;
        $pdf->certificatePassword = paramdeep('exportPdfCertificatePassword');

        $userRepository = $this->getUserRepositoryPath();

        $pdf->outputFilename = $userRepository . DateHelper::formatFileDateTime() . '_' . $title . '.pdf';
        $pdf->createPdfFromHtml(PDFTools::CREATION_MODE_DOWNLOAD_SAVE);

        //$pdf->outputFilename = $title.'.pdf';
        //$pdf->createPdfFromHtml();
    }

}
