<?php

namespace KirilKirkov\WpInvoices;

use KirilKirkov\WpInvoices\Invoices;
use KirilKirkov\WpInvoices\SendInvoice;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class WpInvoicesPdf
{
    const WP_UPLOADS_DIRECTORY_NAME = 'public_kkinv_preview';

    /**
     * Used to generate pdf file into wp uploads directory.
     * used mostly for ShortCodes and Stripe payment page.
     * 
     * Those generated files should be deleted by cron job.
     * WP Invoices is scheduled to clean these files hourly using cron.
     * 
     * Throws exception if error.
     */
    public static function generate_tmp_pdf($invoice)
    {
        // Create uploads directory if not exists
        $wp_upload_dir = wp_upload_dir();
        $wp_uploads_dir_url = rtrim($wp_upload_dir['baseurl'], '/');
        $preview_upload_dir_name = trailingslashit( $wp_upload_dir['basedir'] ) . self::WP_UPLOADS_DIRECTORY_NAME;
        if(!is_dir($preview_upload_dir_name)) {
            wp_mkdir_p( $preview_upload_dir_name );
        }

        $id = $invoice['id'];

        // Check if file already exists, if not generate it
        $file_already_in_dir = false;
        $list_files = glob("{$preview_upload_dir_name}/*.pdf");
        if(count($list_files)) {
            foreach($list_files as $list_file) {
                // !! "invoice_{$id}" SHOULD BE SAME LIKE IN SENDINVOICE.php :: generate_pdf_file() !!
                if(strpos($list_file, "invoice_{$id}") !== false) {
                    $file_already_in_dir = true;
                    
                    $pathInfo = pathinfo($list_file);
                    $basename = $pathInfo['basename']; // filename.pdf
        
                    $new_file_name = $basename;
                    break;
                }
            }
        }

        if($file_already_in_dir === false) {
            try {
                // Generate in server tmp
                $output_file = self::generate_pdf_file($invoice);
            } catch(\Exception $e) {
                throw new \Exception(esc_html($e->getMessage()));
            }

            if(!is_file($output_file)) {
                throw new \Exception('Error generating pdf file.');
            }

            $pathInfo = pathinfo($output_file);
            $basename = $pathInfo['basename']; // filename.pdf

            if(!is_dir($preview_upload_dir_name)) {
                throw new \Exception('Error creating directory.');
            }

            // Upload to wp uploads dir and clear tmp
            $new_file_name = $basename;
            $upload_new_path = $wp_upload_dir['basedir'].DIRECTORY_SEPARATOR.self::WP_UPLOADS_DIRECTORY_NAME.DIRECTORY_SEPARATOR . $new_file_name;

            global $wp_filesystem;
            if ( empty( $wp_filesystem ) ) {
                require_once ABSPATH . 'wp-admin/includes/file.php';
                WP_Filesystem();
            }

            $success = $wp_filesystem->move( $output_file, $upload_new_path, true );
            if ( !$success ) {
                throw new \Exception('Error moving file.');
            }
            wp_delete_file($output_file);
            
            if(!is_file($upload_new_path)) {
                throw new \Exception('Error moving file.');
            }
        }

        $pdf_url = $wp_uploads_dir_url . '/' . self::WP_UPLOADS_DIRECTORY_NAME . '/' . $new_file_name;
        return $pdf_url;
    }

    /**
     * Generate pdf file of invoice and return filepath
     */
    public static function generate_pdf_file($invoice)
    {
        $tmp = get_temp_dir();
        $tmp = DIRECTORY_SEPARATOR . trim($tmp, '/\\') . DIRECTORY_SEPARATOR; // make sure that has slash (bacause different OS systems)

        $inv_dwn_types = Config::get_inv_dwn_types();
        $inv_dwn_type = isset($inv_dwn_types[$invoice['invoice_type']]) ? $inv_dwn_types[$invoice['invoice_type']] : $inv_dwn_types['original'];
        $Config = Config::class;
        
        ob_start();
        require_once plugin_dir_path( __FILE__ ) . '..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'Admin'.DIRECTORY_SEPARATOR.'Views'.DIRECTORY_SEPARATOR.'Invoices'.DIRECTORY_SEPARATOR.'Templates'.DIRECTORY_SEPARATOR.'download_invoice.php';
        $html = ob_get_clean();

        if(!class_exists('\Dompdf\Dompdf')) {
            require_once plugin_dir_path( __FILE__ ) . '../../../vendor/autoload.php';
        }
        $dompdf = new \Dompdf\Dompdf();

        $dompdf->loadHtml($html);

        // (Optional) Setup the paper size and orientation
        // [0, 0, 867.00, 1008.00]
        $dompdf->setPaper('A4', 'portrait');

        // Render the HTML as PDF
        $dompdf->render();
        
        // Output the generated PDF to variable
        $output = $dompdf->output();
        
        // !! 'invoice_' . $invoice['id'] SHOULD BE SAME LIKE IN SHORTCODES.php !!
        $output_file = $tmp . 'invoice_' . $invoice['id'] . '_' . time() . '_' . '.pdf';
        file_put_contents($output_file, $output);

        return $output_file;
    }
}