<?php

class pdfreports_model extends Cf_Model
{
    public function convertCSVtoPDF(
        $fileName,
        $baseCsvFile,
        $reportID,
        $reportTitle,
        $reportDescription,
        $outputFileName = '',
        $outputPath = '',
    ) {
        session_write_close();
        $phpBinPath = get_php_bin_path();

        // prepare variables for shell
        $reportID = escapeshellarg($reportID);
        $baseCsvFile = escapeshellarg($baseCsvFile);
        $reportTitle = escapeshellarg($reportTitle);
        $reportDescription = escapeshellarg($reportDescription);
        $outputFileName = escapeshellarg($outputFileName);

        log_message(
            'info',
            "convertCSVtoPDF(): converting to pdf. Filename: $fileName, baseCsvFile: $baseCsvFile, reportID: $reportID, reportTitle: $reportTitle, reportDescription: $reportDescription, outputFileName: $outputFileName, outputPath: $outputPath",
        );

        if ($outputFileName == '') {
            $outputFileName = $fileName . '_' . time();
            log_message('info', 'convertCSVtoPDF(): outputFileName is empty. Use new name:' . $outputFileName);
        }

        if ($outputPath == '') {
            $outputPath = get_tmpdir();
            log_message('info', 'convertCSVtoPDF(): outputPath is empty. Use default:' . $outputPath);
        }

        $logFile = $outputPath . $fileName . '.pdf.log';
        $pidfile = $outputPath . $fileName . '.pdf.pid';

        log_message('info', "convertCSVtoPDF(): logFile: $logFile, pidfile: $pidfile");

        $cmd = sprintf(
            '%s %spublic/index.php csv2pdf convert %s %s %s %s %s %s',
            $phpBinPath,
            FCPATH,
            $baseCsvFile,
            $reportID,
            base64_encode($reportTitle),
            base64_encode($reportDescription),
            $outputFileName,
            $outputPath,
        );

        log_message('info', 'convertCSVtoPDF(): Command to execute: ' . $cmd);
        log_message(
            'info',
            'convertCSVtoPDF(): Full shell command: ' .
                sprintf('%s > %s 2>&1 & echo $! >> %s', $cmd, $logFile, $pidfile),
        );

        exec(sprintf('%s > %s 2>&1 & echo $! >> %s', $cmd, $logFile, $pidfile));
        log_message('info', 'convertCSVtoPDF(): Convertion complete ');
    }

    public function checkFileSize($fileName)
    {
        try {
            $pathInfo = pathinfo($fileName);
            $localFile = get_tmpdir() . $fileName;

            if ($pathInfo['extension'] == 'pdf') {
                //waiting for status file
                sleep(1);
                if (file_exists($localFile . '.status')) {
                    $i = 0;
                    //generating of pdf files take some time and we have to wait when status will be 100
                    while ($i < 90) {
                        if (file_get_contents($localFile . '.status') != '100') {
                            sleep(1);
                            continue;
                        } else {
                            break;
                        }
                    }
                }
            }

            if (file_exists($localFile)) {
                $sizeMB = filesize($localFile) / pow(1024, 2);
                return [
                    'filePath' => $localFile,
                    'fileSize' => $sizeMB,
                ];
            }
        } catch (Exception $e) {
            log_message('debug', 'checkFileSize(): Command executed with error: ' . $e->getMessage());
        }

        return false;
    }

    public function getRowsCount($file)
    {
        $fp = file($file);
        // return count without header row
        return count($fp) - 1;
    }
}
