<?php

namespace KirilKirkov\WpInvoices;

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

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

class ShortCodes
{
    // shortcodes
    const SHORTCODE_PREVIEW_INV = 'kkwi-invoice-preview';

    public function init()
    {
        add_action('wp_enqueue_scripts', function() {
            global $post;

            if ( isset($post->post_content) && is_singular(array( 'post','page' ) ) && has_shortcode( $post->post_content, ShortCodes::SHORTCODE_PREVIEW_INV ) ) {
                wp_enqueue_style(Config::SCRIPTS_PREFIX.'wp-invoices-preview-shortcode-styles', esc_url(plugins_url('../Assets/Css/select-list-invoices.css', __FILE__ )), array(), '1.0.0', 'all');
                wp_enqueue_script(Config::SCRIPTS_PREFIX.'wp-invoices-preview-shortcode-scripts', esc_url(plugins_url('../Assets/Js/select-list-invoices.js', __FILE__ )), array(), '1.0.0', true);
            }
        });

        add_shortcode(self::SHORTCODE_PREVIEW_INV, array($this, 'load_preview_invoice'));

        $this->add_cronjob();
    }

    /**
     * Add cronjob
     */
    private function add_cronjob()
    {
        add_action( 'kirilkirkovwipdf_clear_pdf_invoices_cron', function () {
            
            $wp_upload_dir = wp_upload_dir();
            // public_kkinv_preview === WpInvoicesPdf::WP_UPLOADS_DIRECTORY_NAME
            $preview_upload_dir_name = trailingslashit( $wp_upload_dir['basedir'] ) . WpInvoicesPdf::WP_UPLOADS_DIRECTORY_NAME;

            if(is_dir($preview_upload_dir_name)) {
                $list_files = glob("{$preview_upload_dir_name}/*.pdf");
                if(count($list_files)) {
                    foreach($list_files as $list_file) {

                        $pathInfo = pathinfo($list_file);
                        $basename = $pathInfo['basename']; // filename.pdf
                        $parts = explode('_', $basename);

                        if(!isset($parts[2]) || !is_numeric(($parts[2]))) {
                            continue;
                        }

                        $diff = time() - $parts[2];
                        // 3600 seconds === 1 hour
                        if($diff > 3600) {
                            wp_delete_file($list_file);
                        }
                    }
                }
            }

        });

        add_action('init', function () {
            if ( ! wp_next_scheduled('kirilkirkovwipdf_clear_pdf_invoices_cron') ) {
                wp_schedule_event( time(), 'hourly', 'kirilkirkovwipdf_clear_pdf_invoices_cron' );
            }
        });
    }

    /**
     * Remove cron when plugin deactivated
     */
    public function remove_cron()
    {
        $timestamp = wp_next_scheduled( 'kirilkirkovwipdf_clear_pdf_invoices_cron' );
        if ( $timestamp ) {
            wp_unschedule_event( $timestamp, 'kirilkirkovwipdf_clear_pdf_invoices_cron' );
        }
    }

    private function return404()
    {
        global $wp;
        $wp->parse_request();
        $current_url = home_url($wp->request);

        ob_start();
        require plugin_dir_path( __FILE__ ) . '../../Public/Views/Invoice/404.php';
        return ob_get_clean();
    }

    private function undefinedError()
    {
        global $wp;
        $wp->parse_request();
        $current_url = home_url($wp->request);

        ob_start();
        require plugin_dir_path( __FILE__ ) . '../../Public/Views/Invoice/UndefinedError.php';
        return ob_get_clean();
    }

    /**
     * Public invoice preview Shortcode
     */
    public function load_preview_invoice()
    {
        // CHECK IS ENABLED
        if(!$this->is_enabled()) {
            return '';
        }

        $current_user_id = get_current_user_id();
        $pdf_url = null;
        
        // No nonce verification needed here – just reading if is valid shortcode param. There is no write/modify operation.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if(isset($_GET['kkwi-wp-invoice']) && $current_user_id > 0) {
            // No nonce verification needed here – just reading if is valid shortcode param. There is no write/modify operation.
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $invoice = sanitize_text_field(wp_unslash($_GET['kkwi-wp-invoice']));
            $invoice = explode('-', $invoice);

            if(!is_array($invoice) || count($invoice) !== 2) {
                return $this->return404();
            }

            $id = (int)$invoice[0];
            $timestamp = $invoice[1];

            if($id < 1 || !is_numeric($timestamp) || (int)$timestamp < 1) {
                return $this->return404();
            }

            $invoice = Invoices::get_invoice($id, false, true, true);
            if($invoice === false || (int)$invoice['customer_user_id'] !== $current_user_id) {
                return $this->return404();
            }

            if(strtotime($invoice['created_at']) !== (int)$timestamp) {
                return $this->return404();
            }

            try {
                $pdf_url = WpInvoicesPdf::generate_tmp_pdf($invoice);
            } catch(\Exception $e) {
                return $this->undefinedError();
            }
        }

        $list_invoices = $this->get_list_invoices($current_user_id);

        ob_start();
        require plugin_dir_path( __FILE__ ) . '../../Public/Views/Invoice/Preview.php';
        return ob_get_clean();
    }

    /**
     * Get User List Invoices
     */
    private function get_list_invoices($current_user_id)
    {
        $list_invoices = [];
        if($current_user_id > 0) {
            $list_invoices = Invoices::get_customer_invoices($current_user_id);
        }

        return $list_invoices;
    }

    /**
     * Check is shortcode enabled
     */
    private function is_enabled()
    {
        $enable_shortcode_prev_inv = get_option(Config::INPUTS_PREFIX.'enable_shortcode_prev_inv');
        if(!$enable_shortcode_prev_inv || (int)$enable_shortcode_prev_inv < 1) {
            return false;
        }

        return true;
    }
}