403Webshell
Server IP : 121.121.20.254  /  Your IP : 216.73.216.202
Web Server : Microsoft-IIS/10.0
System : Windows NT WEB-SERVER 10.0 build 20348 (Windows Server 2022) AMD64
User : IUSR ( 0)
PHP Version : 8.3.28
Disable Function : NONE
MySQL : ON  |  cURL : ON  |  WGET : OFF  |  Perl : OFF  |  Python : OFF  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /Program Files/MariaDB 10.6/data/invoice/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /Program Files/MariaDB 10.6/data/invoice/wp_snippets.ibd
�������������@��������������������������&&�������������������������0�L/��������Q.$�Q.$2���������������������������������������������i������������������������������������������������������������������������������������������������������������������������������������������������������i�
	�����������������������������������������������������������������������������������������������������i������������������������������������������������������������������������������������������������������������������������������������������������������i���������������������������������������������������������������������������������������������������������������������������������������������������������i������������������������������������������������������������������������������������������������������������������������������������������������������i�����������������������������������������������������������������������������������������������������������������������������������zU��������m�9�E�����H���2infimumsupremum��!�
	)���pcm�9�k�d��������m���E��B�4�I�r��Zinfimumsupremum+global�	��front-end� )global�(��content�0global�8global�@global�Hglobal�Pglobal�	Xglobal�
`global�hglobal�p.global�
x��site-head-js��0global����site-footer-js��global��global��global��global��global����global�p�^�cm���a����������m���E������J���2�infimumsupremum���� ��(T��0ā�8��@��H*��P8��X�䀀`*��	h*�p*��xb��
�F������X����X���*��������ր�
��́�p�3�cm����������Yh�E��>��8�H!infimumsupremum
4��&��Make upload filenames lowercaseMakes sure that image and file uploads have lowercase filenames.

This is a sample snippet. Feel free to use it, edit it, or remove it.add_filter( 'sanitize_file_name', 'mb_strtolower' );sample, mediaglobal��
���0w�	s��c��Disable admin barTurns off the WordPress admin bar for everyone except administrators.

This is a sample snippet. Feel free to use it, edit it, or remove it.add_action( 'wp', function () {
	if ( ! current_user_can( 'manage_options' ) ) {
		show_admin_bar( false );
	}
} );sample, admin-barfront-end��
���0w���r
 ��Allow smiliesAllows smiley conversion in obscure places.

This is a sample snippet. Feel free to use it, edit it, or remove it.add_filter( 'widget_text', 'convert_smilies' );
add_filter( 'the_title', 'convert_smilies' );
add_filter( 'wp_title', 'convert_smilies' );
add_filter( 'get_bloginfo', 'convert_smilies' );sampleglobal��
���0w�
��(���Current yearShortcode for inserting the current year into a post or page..

This is a sample snippet. Feel free to use it, edit it, or remove it.<?php echo date( 'Y' ); ?>sample, datescontent��
���0w��0=��Frontend PDF Upload Shortcodefunction frontend_pdf_uploader_kaya_qr() {

    if (!is_user_logged_in()) {
        return "<p>Please login to upload PDF.</p>";
    }

    ob_start();

    if (isset($_POST['submit_pdf']) && !empty($_FILES['pdf_file']['name'])) {

        $uploadedfile = $_FILES['pdf_file'];
        $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/INVOICE/FILES/';

        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0755, true);
        }

        if (!is_writable($target_dir)) {
            echo "<p style='color:red;'>Folder not writable: ".$target_dir."</p>";
            return ob_get_clean();
        }

        $original_filename = sanitize_file_name($uploadedfile['name']);
        $filename = $original_filename;
        $counter = 1;
        while (file_exists($target_dir . $filename)) {
            $file_parts = pathinfo($original_filename);
            $filename = $file_parts['filename'] . '-' . $counter . '.' . $file_parts['extension'];
            $counter++;
        }

        $target_path = $target_dir . $filename;

        if (move_uploaded_file($uploadedfile['tmp_name'], $target_path)) {

            // ✅ PDF URL CORRECT
            $pdf_url = home_url('/FILES/' . $filename);

            $title = sanitize_text_field($_POST['post_title']);
            $category = intval($_POST['post_category']);

            // ✅ QR Code TO PDF URL
            $qr_shortcode = '[kaya_qrcode content="'.$pdf_url.'" dynamic_content="0" download_button="1"]';

            $content = '
            <div style="display:flex; flex-wrap:wrap; gap:20px; align-items:flex-start;">
                <div style="flex:2; min-width:300px;">
                    [qepw_pdf_viewer file="'.$pdf_url.'"]
                </div>
                <div style="flex:1; min-width:200px; text-align:center;">
                    '.$qr_shortcode.'
                    <p style="font-weight:bold; margin-top:10px;">Scan to Download PDF</p>
                    <p style="font-size:12px; word-break:break-all;">'.$pdf_url.'</p>
                </div>
            </div>
            ';

            $post_id = wp_insert_post(array(
                'post_title'   => $title,
                'post_content' => $content,
                'post_status'  => 'publish',
                'post_type' => 'post',
                'post_category'=> array($category),
                'post_author'  => get_current_user_id()
            ));

            echo "<h3 style='color:green;'>Upload Successful!</h3>";
            echo "<p><a href='".get_permalink($post_id)."' target='_blank'>View Page</a></p>";

        } else {
            echo "<p style='color:red;'>Upload failed. Check folder permissions: ".$target_dir."</p>";
        }
    }

    ?>
    <form method="post" enctype="multipart/form-data" style="max-width:600px; margin:20px 0;">
        <p>
            <label>Title:</label><br>
            <input type="text" name="post_title" required style="width:100%; padding:8px;">
        </p>

        <p>
            <label>Select Category:</label><br>
            <select name="post_category" required style="width:100%; padding:8px;">
                <?php
                $categories = get_terms(array(
                    'taxonomy' => 'category',
                    'hide_empty' => false
                ));
                foreach ($categories as $cat) {
                    echo '<option value="'.$cat->term_id.'">'.$cat->name.'</option>';
                }
                ?>
            </select>
        </p>

        <p>
            <label>Upload PDF:</label><br>
            <input type="file" name="pdf_file" accept="application/pdf" required>
        </p>

        <input type="submit" name="submit_pdf" value="Submit" style="
            padding:10px 20px;
            background-color:#0073aa;
            color:#fff;
            border:none;
            border-radius:5px;
            font-weight:bold;
            cursor:pointer;
        ">
    </form>
    <?php

    return ob_get_clean();
}
add_shortcode('pdf_frontend_upload', 'frontend_pdf_uploader_kaya_qr');global��
���6�E�8���Allow iframe in Postsfunction allow_iframe_in_post($allowed_tags) {
    $allowed_tags['iframe'] = array(
        'src' => true,
        'width' => true,
        'height' => true,
        'frameborder' => true,
        'allowfullscreen' => true,
    );
    return $allowed_tags;
}
add_filter('wp_kses_allowed_html', 'allow_iframe_in_post', 10, 2);global��
���0y����@��Create Downloads Post Typefunction create_downloads_cpt() {
    $labels = array(
        'name' => 'Downloads',
        'singular_name' => 'Download',
        'add_new' => 'Add New',
        'add_new_item' => 'Add New Download',
        'edit_item' => 'Edit Download',
        'new_item' => 'New Download',
        'view_item' => 'View Download',
        'search_items' => 'Search Downloads',
        'not_found' => 'No downloads found',
        'not_found_in_trash' => 'No downloads found in Trash',
        'all_items' => 'All Downloads',
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'has_archive' => true,
        'show_in_rest' => true,
        'supports' => array('title', 'author', 'editor', 'custom-fields'),
        'menu_position' => 5,
        'menu_icon' => 'dashicons-media-document',
    );
    register_post_type('downloads', $args);
}
add_action('init', 'create_downloads_cpt');global��
���0~V�t�H€�homepage designfunction homepage_latest_pdf_qr() {

    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => 1,
        'category_name'  => 'invoice' // 你的分类 slug
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) :
        ob_start();
        while ($query->have_posts()) : $query->the_post();

            $content = get_the_content();

            preg_match('/https?:\/\/[^\s"]+\.pdf/', $content, $matches);

            if (!empty($matches[0])) {

                $pdf_url = $matches[0];
                $qr = 'https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=' . urlencode($pdf_url);
                ?>

                <div class="invoice-card">
                    <h3><?php the_title(); ?></h3>

                    <div class="invoice-flex">
                        <div class="invoice-view">
                            <iframe src="<?php echo $pdf_url; ?>"></iframe>
                        </div>

                        <div class="invoice-qr">
                            <img src="<?php echo $qr; ?>">
                            <p>Scan to Download</p>
                        </div>
                    </div>
                </div>

                <?php
            }

        endwhile;
        wp_reset_postdata();
        return ob_get_clean();
    endif;
}
add_shortcode('latest_invoice_qr', 'homepage_latest_pdf_qr');global��
���6"���3P�	�Frontend PDF Upload Shortcode For Categories Folder/**
 * Full replacement — Frontend PDF uploader (Category folder) + QR + PDF Viewer
 * - Uploads into: wp-content/uploads/invoice/<CATEGORY_SLUG>/
 * - Uses WordPress upload handling (safe + portable)
 * - Adds nonce + permission checks + PDF-only validation
 * - Creates a WP Post with embedded [qepw_pdf_viewer] + [kaya_qrcode]
 */

function frontend_pdf_uploader_kaya_qr() {

    if (!is_user_logged_in()) {
        return "<p>Please login to upload PDF.</p>";
    }

    // Optional: require upload capability
    if (!current_user_can('upload_files')) {
        return "<p style='color:red;'>You do not have permission to upload files.</p>";
    }

    $flash = '';

    // Handle POST
    if (
        isset($_POST['submit_pdf']) &&
        isset($_POST['kaya_pdf_upload_nonce']) &&
        wp_verify_nonce($_POST['kaya_pdf_upload_nonce'], 'kaya_pdf_upload_action')
    ) {

        if (empty($_FILES['pdf_file']['name'])) {
            $flash = "<p style='color:red;'>Please choose a PDF file.</p>";
        } else {

            $title       = isset($_POST['post_title']) ? sanitize_text_field(wp_unslash($_POST['post_title'])) : '';
            $category_id = isset($_POST['post_category']) ? absint($_POST['post_category']) : 0;

            // Validate category
            $category = get_term($category_id, 'category');
            if (!$category || is_wp_error($category)) {
                $flash = "<p style='color:red;'>Invalid category.</p>";
            } else {

                // Folder name from category slug (safe)
                $slug = sanitize_title($category->slug);          // e.g. "crm"
                $folder_name = strtoupper($slug);                // e.g. "CRM" (for display only)

                // Build target path inside wp uploads
                $upload_dir = wp_upload_dir();
                if (!empty($upload_dir['error'])) {
                    $flash = "<p style='color:red;'>Upload directory error: " . esc_html($upload_dir['error']) . "</p>";
                } else {

                    $target_dir = trailingslashit($upload_dir['basedir']) . 'invoice/' . $slug . '/';
                    $target_url = trailingslashit($upload_dir['baseurl']) . 'invoice/' . $slug . '/';

                    // Make sure folder exists
                    if (!file_exists($target_dir)) {
                        wp_mkdir_p($target_dir);
                    }

                    if (!is_dir($target_dir) || !is_writable($target_dir)) {
                        $flash = "<p style='color:red;'>Folder not writable: " . esc_html($target_dir) . "</p>";
                    } else {

                        // PDF-only check (mime + extension)
                        $file = $_FILES['pdf_file'];
                        $check = wp_check_filetype_and_ext($file['tmp_name'], $file['name']);

                        $is_pdf = (
                            !empty($check['ext']) &&
                            strtolower($check['ext']) === 'pdf' &&
                            !empty($check['type']) &&
                            $check['type'] === 'application/pdf'
                        );

                        if (!$is_pdf) {
                            $flash = "<p style='color:red;'>Only PDF files are allowed.</p>";
                        } else {

                            // Prepare filename (unique)
                            $original_filename = sanitize_file_name($file['name']);
                            $unique_filename   = wp_unique_filename($target_dir, $original_filename);
                            $target_path       = $target_dir . $unique_filename;

                            // Move uploaded file
                            if (!@move_uploaded_file($file['tmp_name'], $target_path)) {
                                $flash = "<p style='color:red;'>Upload failed while moving the file.</p>";
                            } else {

                                // Final URL to the PDF
                                $pdf_url = $target_url . $unique_filename;

                                // Build post content with your shortcodes
                                $qr_shortcode = '[kaya_qrcode content="' . esc_url($pdf_url) . '" dynamic_content="0"]';

                                $content = '
<div class="pdf-wrapper">
  <div class="pdf-view">
    [qepw_pdf_viewer file="' . esc_url($pdf_url) . '"]
  </div>
  <div class="pdf-qr">
    ' . $qr_shortcode . '
    <p class="pdf-link"><a href="' . esc_url($pdf_url) . '" target="_blank" rel="noopener">Open PDF</a></p>
    <p class="pdf-link-raw" style="word-break:break-all;">' . esc_html($pdf_url) . '</p>
    <p class="pdf-folder" style="opacity:.7;">Folder: ' . esc_html($folder_name) . '</p>
  </div>
</div>
';

                                // Create WP post
                                $post_id = wp_insert_post(array(
                                    'post_title'    => $title !== '' ? $title : $unique_filename,
                                    'post_content'  => $content,
                                    'post_status'   => 'publish',
                                    'post_type'     => 'post',
                                    'post_category' => array($category_id),
                                    'post_author'   => get_current_user_id(),
                                ), true);

                                if (is_wp_error($post_id)) {
                                    $flash = "<p style='color:red;'>Post creation failed: " . esc_html($post_id->get_error_message()) . "</p>";
                                } else {
                                    $flash = "<div style='padding:10px;border:1px solid #86efac;background:#f0fdf4;border-radius:10px;'>
                                      <b>Upload Successful!</b><br>
                                      <a href='" . esc_url(get_permalink($post_id)) . "' target='_blank' rel='noopener'>View Page</a>
                                    </div>";
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // Render form
    ob_start();

    echo $flash;

    $categories = get_terms(array(
        'taxonomy'   => 'category',
        'hide_empty' => false,
    ));
    ?>
    <form method="post" enctype="multipart/form-data" class="pdf-upload-form" style="display:grid;gap:10px;max-width:520px;">
        <?php wp_nonce_field('kaya_pdf_upload_action', 'kaya_pdf_upload_nonce'); ?>

        <input type="text" name="post_title" placeholder="Title" required>

        <select name="post_category" required>
            <?php
            if (!is_wp_error($categories) && !empty($categories)) {
                foreach ($categories as $cat) {
                    echo '<option value="' . esc_attr($cat->term_id) . '">' . esc_html($cat->name) . '</option>';
                }
            } else {
                echo '<option value="">No categories found</option>';
            }
            ?>
        </select>

        <input type="file" name="pdf_file" accept="application/pdf" required>

        <button type="submit" name="submit_pdf">Upload PDF</button>
    </form>
    <?php

    return ob_get_clean();
}
add_shortcode('pdf_frontend_upload', 'frontend_pdf_uploader_kaya_qr');global��
���6-[�p�cYh��ge�	Y�E��*��H!infimumsupremum�=��Frontend PDF Upload Shortcodefunction frontend_pdf_uploader_kaya_qr() {

    if (!is_user_logged_in()) {
        return "<p>Please login to upload PDF.</p>";
    }

    ob_start();

    if (isset($_POST['submit_pdf']) && !empty($_FILES['pdf_file']['name'])) {

        $uploadedfile = $_FILES['pdf_file'];
        $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/INVOICE/FILES/';

        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0755, true);
        }

        if (!is_writable($target_dir)) {
            echo "<p style='color:red;'>Folder not writable: ".$target_dir."</p>";
            return ob_get_clean();
        }

        $original_filename = sanitize_file_name($uploadedfile['name']);
        $filename = $original_filename;
        $counter = 1;
        while (file_exists($target_dir . $filename)) {
            $file_parts = pathinfo($original_filename);
            $filename = $file_parts['filename'] . '-' . $counter . '.' . $file_parts['extension'];
            $counter++;
        }

        $target_path = $target_dir . $filename;

        if (move_uploaded_file($uploadedfile['tmp_name'], $target_path)) {

            // ✅ PDF URL CORRECT
            $pdf_url = home_url('/FILES/' . $filename);

            $title = sanitize_text_field($_POST['post_title']);
            $category = intval($_POST['post_category']);

            // ✅ QR Code TO PDF URL
            $qr_shortcode = '[kaya_qrcode content="'.$pdf_url.'" dynamic_content="0" download_button="1"]';

            $content = '
            <div style="display:flex; flex-wrap:wrap; gap:20px; align-items:flex-start;">
                <div style="flex:2; min-width:300px;">
                    [qepw_pdf_viewer file="'.$pdf_url.'"]
                </div>
                <div style="flex:1; min-width:200px; text-align:center;">
                    '.$qr_shortcode.'
                    <p style="font-weight:bold; margin-top:10px;">Scan to Download PDF</p>
                    <p style="font-size:12px; word-break:break-all;">'.$pdf_url.'</p>
                </div>
            </div>
            ';

            $post_id = wp_insert_post(array(
                'post_title'   => $title,
                'post_content' => $content,
                'post_status'  => 'publish',
                'post_type' => 'post',
                'post_category'=> array($category),
                'post_author'  => get_current_user_id()
            ));

            echo "<h3 style='color:green;'>Upload Successful!</h3>";
            echo "<p><a href='".get_permalink($post_id)."' target='_blank'>View Page</a></p>";

        } else {
            echo "<p style='color:red;'>Upload failed. Check folder permissions: ".$target_dir."</p>";
        }
    }

    ?>
    <form method="post" enctype="multipart/form-data" style="max-width:600px; margin:20px 0;">
        <p>
            <label>Title:</label><br>
            <input type="text" name="post_title" required style="width:100%; padding:8px;">
        </p>

        <p>
            <label>Select Category:</label><br>
            <select name="post_category" required style="width:100%; padding:8px;">
                <?php
                $categories = get_terms(array(
                    'taxonomy' => 'category',
                    'hide_empty' => false
                ));
                foreach ($categories as $cat) {
                    echo '<option value="'.$cat->term_id.'">'.$cat->name.'</option>';
                }
                ?>
            </select>
        </p>

        <p>
            <label>Upload PDF:</label><br>
            <input type="file" name="pdf_file" accept="application/pdf" required>
        </p>

        <input type="submit" name="submit_pdf" value="Submit" style="
            padding:10px 20px;
            background-color:#0073aa;
            color:#fff;
            border:none;
            border-radius:5px;
            font-weight:bold;
            cursor:pointer;
        ">
    </form>
    <?php

    return ob_get_clean();
}
add_shortcode('pdf_frontend_upload', 'frontend_pdf_uploader_kaya_qr');global��
���6�E����Allow iframe in Postsfunction allow_iframe_in_post($allowed_tags) {
    $allowed_tags['iframe'] = array(
        'src' => true,
        'width' => true,
        'height' => true,
        'frameborder' => true,
        'allowfullscreen' => true,
    );
    return $allowed_tags;
}
add_filter('wp_kses_allowed_html', 'allow_iframe_in_post', 10, 2);global��
���0y���� ��Create Downloads Post Typefunction create_downloads_cpt() {
    $labels = array(
        'name' => 'Downloads',
        'singular_name' => 'Download',
        'add_new' => 'Add New',
        'add_new_item' => 'Add New Download',
        'edit_item' => 'Edit Download',
        'new_item' => 'New Download',
        'view_item' => 'View Download',
        'search_items' => 'Search Downloads',
        'not_found' => 'No downloads found',
        'not_found_in_trash' => 'No downloads found in Trash',
        'all_items' => 'All Downloads',
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'has_archive' => true,
        'show_in_rest' => true,
        'supports' => array('title', 'author', 'editor', 'custom-fields'),
        'menu_position' => 5,
        'menu_icon' => 'dashicons-media-document',
    );
    register_post_type('downloads', $args);
}
add_action('init', 'create_downloads_cpt');global��
���0~V�t�(€�homepage designfunction homepage_latest_pdf_qr() {

    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => 1,
        'category_name'  => 'invoice' // 你的分类 slug
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) :
        ob_start();
        while ($query->have_posts()) : $query->the_post();

            $content = get_the_content();

            preg_match('/https?:\/\/[^\s"]+\.pdf/', $content, $matches);

            if (!empty($matches[0])) {

                $pdf_url = $matches[0];
                $qr = 'https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=' . urlencode($pdf_url);
                ?>

                <div class="invoice-card">
                    <h3><?php the_title(); ?></h3>

                    <div class="invoice-flex">
                        <div class="invoice-view">
                            <iframe src="<?php echo $pdf_url; ?>"></iframe>
                        </div>

                        <div class="invoice-qr">
                            <img src="<?php echo $qr; ?>">
                            <p>Scan to Download</p>
                        </div>
                    </div>
                </div>

                <?php
            }

        endwhile;
        wp_reset_postdata();
        return ob_get_clean();
    endif;
}
add_shortcode('latest_invoice_qr', 'homepage_latest_pdf_qr');global��
���6"�Q�30�l�	�Frontend PDF Upload Shortcode For Categories Folderfunction frontend_pdf_uploader_kaya_qr() {

    if (!is_user_logged_in()) {
        return "<p>Please login to upload PDF.</p>";
    }

    ob_start();

    if (isset($_POST['submit_pdf']) && !empty($_FILES['pdf_file']['name'])) {

        $uploadedfile = $_FILES['pdf_file'];
        $category_id  = intval($_POST['post_category']);

        // GET CATEGORIES INFORMATION
        $category = get_term($category_id, 'category');

        if (!$category) {
            echo "<p style='color:red;'>Invalid category.</p>";
            return ob_get_clean();
        }

        // USE CATEGORY slug AS folder NAME
        $folder_name = strtoupper($category->slug);

        // TARGET MENU
        $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/INVOICE/' . $folder_name . '/';

        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0755, true);
        }

        if (!is_writable($target_dir)) {
            echo "<p style='color:red;'>Folder not writable: " . $target_dir . "</p>";
            return ob_get_clean();
        }

        // KEEP ORIGINAL FOLDER NAME
        $original_filename = sanitize_file_name($uploadedfile['name']);
        $filename = $original_filename;
        $counter  = 1;

        while (file_exists($target_dir . $filename)) {
            $file_parts = pathinfo($original_filename);
            $filename   = $file_parts['filename'] . '-' . $counter . '.' . $file_parts['extension'];
            $counter++;
        }

        $target_path = $target_dir . $filename;

        if (move_uploaded_file($uploadedfile['tmp_name'], $target_path)) {

            // CORRECT URL
            $pdf_url = home_url('/' . $folder_name . '/' . $filename);

            $title = sanitize_text_field($_POST['post_title']);

            $qr_shortcode = '[kaya_qrcode content="' . $pdf_url . '" dynamic_content="0"]';

            $content = '
            <div class="pdf-wrapper">
                <div class="pdf-view">
                    [qepw_pdf_viewer file="' . $pdf_url . '"]
                </div>
                <div class="pdf-qr">
                    ' . $qr_shortcode . '
                    <p class="pdf-link">' . $pdf_url . '</p>
                </div>
            </div>
            ';

            $post_id = wp_insert_post(array(
                'post_title'    => $title,
                'post_content'  => $content,
                'post_status'   => 'publish',
                'post_type'     => 'post',
                'post_category' => array($category_id),
                'post_author'   => get_current_user_id()
            ));

            echo "<h3 style='color:green;'>Upload Successful!</h3>";
            echo "<p><a href='" . get_permalink($post_id) . "' target='_blank'>View Page</a></p>";

        } else {
            echo "<p style='color:red;'>Upload failed.</p>";
        }
    }
    ?>

    <form method="post" enctype="multipart/form-data" class="pdf-upload-form">
        <input type="text" name="post_title" placeholder="Title" required>

        <select name="post_category" required>
            <?php
            $categories = get_terms(array(
                'taxonomy'   => 'category',
                'hide_empty' => false
            ));

            foreach ($categories as $cat) {
                echo '<option value="' . $cat->term_id . '">' . $cat->name . '</option>';
            }
            ?>
        </select>

        <input type="file" name="pdf_file" accept="application/pdf" required>

        <button type="submit" name="submit_pdf">Upload PDF</button>
    </form>

    <?php
    return ob_get_clean();
}

add_shortcode('pdf_frontend_upload', 'frontend_pdf_uploader_kaya_qr');global��
���61΀pcY��1����������g��
�
&����aDrop');
      const fileInput = document.getElementById('kayaFileInput');
      const pickBtn = document.getElementById('kayaPickBtn');
      const hint = document.getElementById('kayaFileHint');
      const nameEl = document.getElementById('kayaFileName');

      if (drop && fileInput) {
        function showFileName(){
          const f = fileInput.files && fileInput.files[0];
          if (!f) {
            if (hint) hint.style.display = 'none';
            return;
          }
          if (hint) hint.style.display = 'block';
          if (nameEl) nameEl.textContent = f.name;
        }

        if (pickBtn){
          pickBtn.addEventListener('click', function(e){
            e.preventDefault();
            fileInput.click();
          });
        }

        fileInput.addEventListener('change', showFileName);

        ['dragenter','dragover'].forEach(function(evt){
          drop.addEventListener(evt, function(e){
            e.preventDefault();
            e.stopPropagation();
            drop.classList.add('is-drag');
          });
        });

        ['dragleave','drop'].forEach(function(evt){
          drop.addEventListener(evt, function(e){
            e.preventDefault();
            e.stopPropagation();
            drop.classList.remove('is-drag');
          });
        });

        drop.addEventListener('drop', function(e){
          if (!e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files.length) return;
          fileInput.files = e.dataTransfer.files;
          showFileName();
        });
      }

      document.addEventListener('click', function(e){
        const btn = e.target.closest('.kaya-download-qr-btn');
        if (!btn) return;

        const targetId = btn.getAttribute('data-target');
        const filename = btn.getAttribute('data-filename') || 'qr-image.png';
        const box = document.getElementById(targetId);

        if (!box || typeof html2canvas === 'undefined') {
          alert('QR image downloader is not ready.');
          return;
        }

        html2canvas(box, {
          backgroundColor: '#ffffff',
          scale: 2,
          useCORS: true
        }).then(function(canvas){
          const link = document.createElement('a');
          link.download = filename;
          link.href = canvas.toDataURL('image/png');
          link.click();
        }).catch(function(err){
          console.error(err);
          alert('Failed to download QR image.');
        });
      });
    })();
  </script>
  <?php

  return ob_get_clean();
}

add_shortcode('pdf_frontend_upload', 'frontend_pdf_uploader_kaya_qr');g��zܟ	hm}�E��,B�H!infimumsupremum�;��
�Frontend PDF Upload Shortcode For Categories Folder [CLONE]�
&Brglobal��
���89�)�C���Frontend PDF Upload Shortcode For Categories Folder [CLONE] [CLONE]function frontend_pdf_uploader_kaya_qr() {

    if (!is_user_logged_in()) {
        return "<p>Please login to upload PDF.</p>";
    }

    if (!current_user_can('upload_files')) {
        return "<p style='color:red;'>No permission to upload.</p>";
    }

    $flash = '';

    // Existing base folder (as per your File Manager screenshot)
    $BASE_REL = 'FILES';

    if (
        isset($_POST['submit_pdf'], $_POST['kaya_pdf_upload_nonce']) &&
        wp_verify_nonce($_POST['kaya_pdf_upload_nonce'], 'kaya_pdf_upload_action')
    ) {

        if (empty($_FILES['pdf_file']['name'])) {
            $flash = "<p style='color:red;'>Please select a file.</p>";
        } else {

            $title       = sanitize_text_field(wp_unslash($_POST['post_title'] ?? ''));
            $category_id = absint($_POST['post_category'] ?? 0);
            $category    = get_term($category_id, 'category');

            if (!$category || is_wp_error($category)) {
                $flash = "<p style='color:red;'>Invalid category.</p>";
            } else {

                // slug like: crm2, invoice2
                $slug = sanitize_title($category->slug);
                if ($slug === '') {
                    $flash = "<p style='color:red;'>Category slug is empty.</p>";
                } else {

                    // Folder name is your existing folder: CRM2 / INVOICE2
                    // (matches your screenshot)
                    $folder_name = strtoupper($slug);

                    // Target folder on disk: C:\inetpub\wwwroot\INVOICE\FILES\CRM2\
                    $target_dir = rtrim(ABSPATH, '/\\') . DIRECTORY_SEPARATOR
                                . trim($BASE_REL, '/\\') . DIRECTORY_SEPARATOR
                                . $folder_name . DIRECTORY_SEPARATOR;

                    // Public URL: https://website.../INVOICE/FILES/CRM2/<file>
                    $base_url = home_url('/' . trim($BASE_REL, '/\\') . '/' . $folder_name . '/');

                    // Do not create folder. Must already exist.
                    if (!is_dir($target_dir)) {
                        $flash = "<p style='color:red;'><b>Folder does not exist</b>: " . esc_html($target_dir) . "</p>";
                    } elseif (!is_writable($target_dir)) {
                        $flash = "<p style='color:red;'><b>Folder not writable</b>: " . esc_html($target_dir) . "</p>";
                    } else {

                        $file  = $_FILES['pdf_file'];
                        $check = wp_check_filetype_and_ext($file['tmp_name'], $file['name']);
                        $ext   = strtolower((string)($check['ext'] ?? ''));

                        if ($ext !== 'pdf') {
                            $flash = "<p style='color:red;'>Only PDF allowed.</p>";
                        } else {

                            $filename    = sanitize_file_name($file['name']);
                            $filename    = wp_unique_filename($target_dir, $filename);
                            $target_path = $target_dir . $filename;

                            if (!@move_uploaded_file($file['tmp_name'], $target_path)) {
                                $err = error_get_last();
                                $flash  = "<p style='color:red;'><b>Upload failed while moving file</b>.</p>";
                                $flash .= "<p>Target: " . esc_html($target_path) . "</p>";
                                $flash .= "<pre style='white-space:pre-wrap;background:#f8fafc;border:1px solid #e5e7eb;padding:10px;border-radius:10px;'>" .
                                          esc_html(print_r($err, true)) . "</pre>";
                            } else {

                                $pdf_url = $base_url . rawurlencode($filename);

                                $content = '
<div class="pdf-wrapper">
  <div class="pdf-view">
    [qepw_pdf_viewer file="' . esc_url($pdf_url) . '"]
  </div>
  <div class="pdf-qr">
    [kaya_qrcode content="' . esc_url($pdf_url) . '" dynamic_content="0"]
    <p style="word-break:break-all;">' . esc_html($pdf_url) . '</p>
  </div>
</div>';

                                $post_id = wp_insert_post(array(
                                    'post_title'    => $title !== '' ? $title : $filename,
                                    'post_content'  => $content,
                                    'post_status'   => 'publish',
                                    'post_type'     => 'post',
                                    'post_category' => array($category_id),
                                    'post_author'   => get_current_user_id()
                                ), true);

                                if (is_wp_error($post_id)) {
                                    $flash = "<p style='color:red;'>Post creation failed: " . esc_html($post_id->get_error_message()) . "</p>";
                                } else {
                                    $flash = "<div style='padding:10px;border:1px solid #86efac;background:#f0fdf4;border-radius:10px;'>
                                      <b>Upload Successful!</b><br>
                                      <a href='" . esc_url(get_permalink($post_id)) . "' target='_blank' rel='noopener'>View Page</a>
                                    </div>";
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    ob_start();
    echo $flash;
    ?>
    <form method="post" enctype="multipart/form-data" style="display:grid;gap:10px;max-width:520px;">
        <?php wp_nonce_field('kaya_pdf_upload_action', 'kaya_pdf_upload_nonce'); ?>

        <input type="text" name="post_title" placeholder="Title" required>

        <select name="post_category" required>
            <?php
            $categories = get_terms(array('taxonomy' => 'category', 'hide_empty' => false));
            if (!is_wp_error($categories) && $categories) {
                foreach ($categories as $cat) {
                    echo '<option value="' . esc_attr($cat->term_id) . '">' . esc_html($cat->name) . '</option>';
                }
            }
            ?>
        </select>

        <input type="file" name="pdf_file" accept="application/pdf" required>

        <button type="submit" name="submit_pdf">Upload PDF</button>
    </form>
    <?php

    return ob_get_clean();
}
add_shortcode('pdf_frontend_upload', 'frontend_pdf_uploader_kaya_qr');global��
��6<D�� D��Disable Dashboard/**
 * Hide Dashboard for non-admin users
 */
add_action('admin_init', function () {

    // Allow AJAX
    if (defined('DOING_AJAX') && DOING_AJAX) {
        return;
    }

    // If not administrator, redirect
    if (!current_user_can('administrator')) {
        wp_redirect(home_url());
        exit;
    }
});

/**
 * Hide Admin Bar on frontend for non-admin
 */
add_action('after_setup_theme', function () {
    if (!current_user_can('administrator')) {
        show_admin_bar(false);
    }
});global��
���6S��H(��
�Frontend PDF Upload Shortcode For Categories Folder [Secret Folder Name]�&I�global��
���Z���Z�0�Ԁ�Postcode City State(function () {
  var DATA_URL = 'https://invoice.webstation.my/FILES/Postcode/all.json';

  var SEL_POSTCODE = 'input[name="form_fields[my_postcode]"]';
  var SEL_CITY     = 'input[name="form_fields[my_city]"]';
  var SEL_STATE    = 'input[name="form_fields[my_state]"]';

  var postcodeMap = null;
  var loading = false;
  var waiters = [];

  function setVal(selector, value) {
    var el = document.querySelector(selector);
    if (!el) return;

    el.value = value || '';

    // trigger Elementor listeners
    try {
      el.dispatchEvent(new Event('input', { bubbles: true }));
      el.dispatchEvent(new Event('change', { bubbles: true }));
    } catch (e) {
      var evt = document.createEvent('Event');
      evt.initEvent('change', true, true);
      el.dispatchEvent(evt);
    }
  }

  function normalizePostcode(v) {
    v = (v || '').toString();
    v = v.replace(/\D/g, '');
    if (v.length > 5) v = v.substring(0, 5);
    return v;
  }

  function buildMap(json) {
    var map = {};
    var states = json || [];

    for (var i = 0; i < states.length; i++) {
      var stateObj = states[i] || {};
      var stateName = (stateObj.state || stateObj.name || '') + '';
      var cities = stateObj.city || [];

      for (var j = 0; j < cities.length; j++) {
        var cityObj = cities[j] || {};
        var cityName = (cityObj.name || cityObj.city || '') + '';
        var pcs = cityObj.postcode || [];

        for (var k = 0; k < pcs.length; k++) {
          var key = String(pcs[k] || '').trim();
          if (key) map[key] = { state: stateName, city: cityName };
        }
      }
    }
    return map;
  }

  function loadPostcodes(cb) {
    if (postcodeMap) return cb(null, postcodeMap);

    waiters.push(cb);
    if (loading) return;

    loading = true;

    var xhr = new XMLHttpRequest();
    xhr.open('GET', DATA_URL, true);
    xhr.onreadystatechange = function () {
      if (xhr.readyState !== 4) return;

      loading = false;

      if (xhr.status < 200 || xhr.status >= 300) {
        flushWaiters(new Error('Failed to load postcode data (' + xhr.status + ')'), null);
        return;
      }

      try {
        var json = JSON.parse(xhr.responseText);
        postcodeMap = buildMap(json);
        flushWaiters(null, postcodeMap);
      } catch (e) {
        flushWaiters(e, null);
      }
    };

    xhr.send(null);
  }

  function flushWaiters(err, map) {
    var list = waiters.slice(0);
    waiters = [];
    for (var i = 0; i < list.length; i++) {
      try { list[i](err, map); } catch (e) {}
    }
  }

  function bind() {
    var pcEl = document.querySelector(SEL_POSTCODE);
    if (!pcEl) return false;

    if (pcEl.getAttribute('data-ac-postcode-bound') === '1') return true;
    pcEl.setAttribute('data-ac-postcode-bound', '1');

    pcEl.addEventListener('input', function () {
      var pc = normalizePostcode(pcEl.value);
      if (pcEl.value !== pc) pcEl.value = pc;

      if (pc.length < 5) {
        setVal(SEL_CITY, '');
        setVal(SEL_STATE, '');
        return;
      }

      loadPostcodes(function (err, map) {
        if (err || !map) return;

        var hit = map[pc];
        if (hit) {
          setVal(SEL_CITY, hit.city);
          setVal(SEL_STATE, hit.state);
        } else {
          setVal(SEL_CITY, '');
          setVal(SEL_STATE, '');
        }
      });
    });

    return true;
  }

  function boot() {
    var tries = 0;
    var t = setInterval(function () {
      tries++;
      if (bind() || tries >= 30) clearInterval(t);
    }, 500);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }
})();
</script>site-head-js��
��Fu��pchm}���l�
��������Z^*�
�?�/**
 * FULL REPLACEMENT — Frontend PDF Upload -> Create Post with PDF Viewer (left) + QR (right)
 * Shortcode: [pdf_frontend_upload]
 *
 * Changes:
 * - Kaya QR: enable download button via shortcode params:
 *   download_button="1" download_align="aligncenter"
 * - No custom QR download button
 * - Toggle: show/hide File URL block stays
 */

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

/** =========================
 * SETTINGS (change later)
 * ========================= */
if (!defined('KAYA_INV_SHOW_FILE_URL')) {
  define('KAYA_INV_SHOW_FILE_URL', true); // set false to hide File URL section
}
if (!defined('KAYA_INV_QR_FILENAME_PREFIX')) {
  define('KAYA_INV_QR_FILENAME_PREFIX', 'QR-'); // kept for future use
}

/** Add a CSS class to generated invoice posts (easy global styling) */
add_filter('post_class', function($classes, $class, $post_id){
  if (get_post_meta($post_id, '_kaya_invoice_post', true)) {
    $classes[] = 'kaya-invoice-post';
    $classes[] = 'kaya-invoice-post--v5';
  }
  return $classes;
}, 10, 3);

/** Output CSS once */
add_action('wp_head', function () {
  ?>
  <style id="kaya-invoice-css">
    /* ===== Invoice Post Layout ===== */
    .kaya-inv-page{
      display: grid;
      grid-template-columns: minmax(0, 1fr) 320px;
      gap: 18px;
      align-items: start;
      margin: 18px 0;
    }
    @media (max-width: 900px){
      .kaya-inv-page{ grid-template-columns: 1fr; }
    }

    .kaya-inv-viewer{
      border: 1px solid rgba(226,232,240,1);
      border-radius: 16px;
      background: #fff;
      padding: 12px;
      overflow: hidden;
      min-width: 0;
    }

    .kaya-inv-qr{
      border: 1px solid rgba(226,232,240,1);
      border-radius: 16px;
      background: #fff;
      padding: 14px;
    }

    .kaya-inv-qrbox{
      display:flex;
      justify-content:center;
      align-items:center;
      padding: 12px;
      border-radius: 14px;
      background: #f8fafc;
      border: 1px dashed rgba(226,232,240,1);
      flex-direction: column;
      gap: 10px;
    }

    .kaya-inv-qrbox img{
      width: 100%;
      max-width: 240px;
      height: auto;
    }

    /* If Kaya QR plugin prints a download button/link, align it nicely */
    .kaya-inv-qrbox .aligncenter{
      display: flex;
      justify-content: center;
    }

    /* File URL meta */
    .kaya-inv-meta{ margin-top: 12px; }
    .kaya-inv-label{
      font-size: 12px;
      color: #64748b;
      font-weight: 800;
      margin: 0 0 6px;
    }
    .kaya-inv-url{
      font-size: 13px;
      word-break: break-all;
      color: #0f172a;
    }

    /* Make QEPW canvas responsive */
    .kaya-invoice-post canvas.pdf-canvas{
      width: 100% !important;
      height: auto !important;
      display: block !important;
    }
    .kaya-invoice-post .pdf-viewer{
      width: 100% !important;
      max-width: 100% !important;
    }

    /* ===== Uploader UI (scoped) ===== */
    .kaya-up{ --pri:#0082ff; --txt:#0f172a; --mut:#6b7280; --bd:#dbe3f0; --bg:#f5f8ff; }
    .kaya-up *{ box-sizing:border-box; }

    .kaya-up-shell{ max-width: 740px; margin: 0 auto; }
    .kaya-up-card{ background:#fff; border-radius: 18px; box-shadow: 0 20px 60px rgba(2, 6, 23, .10); padding: 22px; }

    .kaya-up-top{
      display:grid;
      grid-template-columns: 1fr 1fr;
      gap: 12px;
      margin-bottom: 14px;
    }
    @media(max-width: 767px){
      .kaya-up-shell{ padding: 0 14px; }
      .kaya-up-top{ grid-template-columns: 1fr; }
      .kaya-up-btn--primary{ min-width: 100% !important; }
      .kaya-up-or:before, .kaya-up-or:after{ width: 60px; }
    }

    .kaya-up-field label{
      display:block;
      font-size: 12px;
      color: var(--mut);
      font-weight: 800;
      margin: 0 0 6px;
    }
    .kaya-up-field input[type="text"],
    .kaya-up-field select{
      width:100%;
      border:1px solid rgba(226,232,240,1);
      border-radius: 12px;
      padding: 12px 12px;
      font-size: 14px;
      outline:none;
      background:#fff;
    }
    .kaya-up-field input[type="text"]:focus,
    .kaya-up-field select:focus{
      border-color: rgba(0,130,255,.55);
      box-shadow: 0 0 0 4px rgba(0,130,255,.12);
    }

    .kaya-up-drop{
      position: relative;
      border: 2px dashed rgba(0,130,255,.35);
      border-radius: 16px;
      padding: 26px 18px;
      background: linear-gradient(180deg, rgba(245,248,255,.9), #fff);
      text-align: center;
      transition: box-shadow .15s ease, border-color .15s ease, transform .08s ease;
    }
    .kaya-up-drop.is-drag{
      border-color: rgba(0,130,255,.75);
      box-shadow: 0 0 0 6px rgba(0,130,255,.10);
    }

    .kaya-up-illu{
      width: 86px; height: 86px; margin: 0 auto 12px;
      border-radius: 18px; background: rgba(0,130,255,.10);
      display:flex; align-items:center; justify-content:center;
    }
    .kaya-up-illu svg{ width: 44px; height: 44px; stroke: var(--pri); }

    .kaya-up-title{ font-size: 18px; font-weight: 800; color: var(--txt); margin: 6px 0 8px; }

    .kaya-up-or{
      display:flex; align-items:center; gap: 10px; justify-content:center;
      margin: 10px 0 14px; color: var(--mut); font-size: 13px;
    }
    .kaya-up-or:before, .kaya-up-or:after{ content:""; height:1px; width: 90px; background: rgba(100,116,139,.25); }

    .kaya-up-btn{
      display:inline-flex; align-items:center; justify-content:center;
      height: 52px; padding: 0 26px; border-radius: 12px;
      font-weight: 900; font-size: 15px;
      border: 1px solid transparent; cursor: pointer; text-decoration:none;
      transition: transform .08s ease, box-shadow .15s ease, background .15s ease;
    }
    .kaya-up-btn:active{ transform: translateY(1px); }
    .kaya-up-btn--primary{
      background: var(--pri); color: #fff; min-width: 320px;
      box-shadow: 0 14px 30px rgba(0,130,255,.22);
    }
    .kaya-up-btn--primary:hover{ background:#0a6fe0; }

    .kaya-up-note{ font-size: 12px; color: var(--mut); margin-top: 10px; }
    .kaya-up-filehint{
      font-size: 13px; color: var(--txt); margin-top: 10px;
      font-weight: 700; word-break: break-word;
    }
    .kaya-up-filehint span{ font-weight: 600; color: var(--mut); }
    .kaya-up input[type="file"]{ position:absolute; inset:0; opacity:0; cursor:pointer; }

    .kaya-up-alert{
      border-radius:14px; padding:12px 14px;
      border:1px solid rgba(226,232,240,1);
      background: #fff; color: var(--txt); margin: 0 0 12px;
    }
    .kaya-up-alert--ok{ border-color: rgba(34,197,94,.35); background:#f0fdf4; }
    .kaya-up-alert--err{ border-color: rgba(239,68,68,.35); background:#fff1f2; }
    .kaya-up-alert--warn{ border-color: rgba(245,158,11,.35); background:#fffbeb; }

    .kaya-up-actions{ display:flex; gap:10px; flex-wrap:wrap; margin-top:10px; }
    .kaya-up-small{ font-size:12px; color:#64748b; margin-top:6px; word-break:break-all; }

    .kaya-up-debug{
      margin-top:10px; padding:10px; border-radius:12px;
      border:1px dashed rgba(226,232,240,1);
      background: #f8fafc; font-size:12px; color: var(--txt);
    }
    .kaya-up-debug pre{ margin:8px 0 0; white-space:pre-wrap; }
  </style>
  <?php
});

/** Shortcode */
function frontend_pdf_uploader_kaya_qr() {

  if (!is_user_logged_in()) {
    return '<div class="kaya-up-alert kaya-up-alert--warn">Please login to upload PDF.</div>';
  }
  if (!current_user_can('upload_files')) {
    return '<div class="kaya-up-alert kaya-up-alert--err">No permission to upload.</div>';
  }

  $flash = '';
  $BASE_REL = 'FILES';
  $max_mb_text = '100 MB';

  if (
    isset($_POST['submit_pdf'], $_POST['kaya_pdf_upload_nonce']) &&
    wp_verify_nonce($_POST['kaya_pdf_upload_nonce'], 'kaya_pdf_upload_action')
  ) {

    if (empty($_FILES['pdf_file']['name'])) {
      $flash = '<div class="kaya-up-alert kaya-up-alert--err">Please select a PDF file.</div>';
    } else {

      $title       = sanitize_text_field(wp_unslash($_POST['post_title'] ?? ''));
      $category_id = absint($_POST['post_category'] ?? 0);
      $category    = get_term($category_id, 'category');

      if (!$category || is_wp_error($category)) {
        $flash = '<div class="kaya-up-alert kaya-up-alert--err">Invalid category.</div>';
      } else {

        $slug = sanitize_title($category->slug);
        if ($slug === '') {
          $flash = '<div class="kaya-up-alert kaya-up-alert--err">Category slug is empty.</div>';
        } else {

          $folder_name = strtoupper($slug);

          $target_dir = rtrim(ABSPATH, '/\\') . DIRECTORY_SEPARATOR
                      . trim($BASE_REL, '/\\') . DIRECTORY_SEPARATOR
                      . $folder_name . DIRECTORY_SEPARATOR;

          $base_url = home_url('/' . trim($BASE_REL, '/\\') . '/' . $folder_name . '/');

          if (!is_dir($target_dir)) {
            $flash = '<div class="kaya-up-alert kaya-up-alert--err"><b>Folder does not exist</b><div class="kaya-up-small">'
                   . esc_html($target_dir) . '</div></div>';
          } elseif (!is_writable($target_dir)) {
            $flash = '<div class="kaya-up-alert kaya-up-alert--err"><b>Folder not writable</b><div class="kaya-up-small">'
                   . esc_html($target_dir) . '</div></div>';
          } else {

            $file  = $_FILES['pdf_file'];
            $check = wp_check_filetype_and_ext($file['tmp_name'], $file['name']);
            $ext   = strtolower((string)($check['ext'] ?? ''));

            if ($ext !== 'pdf') {
              $flash = '<div class="kaya-up-alert kaya-up-alert--err">Only PDF allowed.</div>';
            } else {

              $filename    = sanitize_file_name($file['name']);
              $filename    = wp_unique_filename($target_dir, $filename);
              $target_path = $target_dir . $filename;

              if (!@move_uploaded_file($file['tmp_name'], $target_path)) {
                $err = error_get_last();
                $flash  = '<div class="kaya-up-alert kaya-up-alert--err"><b>Upload failed while moving file</b>.</div>';
                $flash .= '<div class="kaya-up-debug"><b>Target:</b> ' . esc_html($target_path) . '<br><pre>'
                        . esc_html(print_r($err, true)) . '</pre></div>';
              } else {

                $pdf_url = $base_url . rawurlencode($filename);

                // QEPW viewer (NO download button here)
                $qepw = '[qepw_pdf_viewer file="' . esc_url($pdf_url) . '"]';

                // Kaya QR with built-in download button here
                $kaya_qr = '[kaya_qrcode content="' . esc_url($pdf_url) . '" dynamic_content="0" download_button="1" download_align="aligncenter"]';

                $content = '<div class="kaya-inv-page kaya-inv-page--v5">' .
                    '<div class="kaya-inv-viewer kaya-inv-viewer--qepw">' .
                      $qepw .
                    '</div>' .
                    '<div class="kaya-inv-qr kaya-inv-qr--kaya">' .
                      '<div class="kaya-inv-qrbox">' .
                        $kaya_qr .
                      '</div>';

                // File URL (optional)
                if (KAYA_INV_SHOW_FILE_URL) {
                  $content .= '<div class="kaya-inv-meta kaya-inv-urlwrap">' .
                                '<div class="kaya-inv-label">File URL</div>' .
                                '<div class="kaya-inv-url">' . esc_html($pdf_url) . '</div>' .
                              '</div>';
                }

                $content .= '</div></div>';

                $post_id = wp_insert_post(array(
                  'post_title'    => ($title !== '' ? $title : $filename),
                  'post_content'  => $content,
                  'post_status'   => 'publish',
                  'post_type'     => 'post',
                  'post_category' => array($category_id),
                  'post_author'   => get_current_user_id()
                ), true);

                if (is_wp_error($post_id)) {
                  $flash = '<div class="kaya-up-alert kaya-up-alert--err">Post creation failed: '
                         . esc_html($post_id->get_error_message()) . '</div>';
                } else {
                  update_post_meta($post_id, '_kaya_invoice_post', 1);
                  update_post_meta($post_id, '_kaya_invoice_pdf_url', esc_url_raw($pdf_url));

                  $flash = '<div class="kaya-up-alert kaya-up-alert--ok">
                    <b>Upload Successful!</b>
                    <div class="kaya-up-actions">
                      <a class="kaya-up-btn kaya-up-btn--primary" href="' . esc_url(get_permalink($post_id)) . '" target="_blank" rel="noopener">View Page</a>
                      <a class="kaya-up-btn kaya-up-btn--ghost" href="' . esc_url($pdf_url) . '" target="_blank" rel="noopener">Open PDF</a>
                    </div>
                  </div>';
                }
              }
            }
          }
        }
      }
    }
  }

  ob_start();
  ?>
  <div class="kaya-up">
    <div class="kaya-up-shell">
      <?php echo $flash; ?>

      <div class="kaya-up-card">
        <form method="post" enctype="multipart/form-data">
          <?php wp_nonce_field('kaya_pdf_upload_action', 'kaya_pdf_upload_nonce'); ?>

          <div class="kaya-up-top">
            <div class="kaya-up-field">
              <label>Title</label>
              <input type="text" name="post_title" placeholder="e.g. INV-000123" required>
            </div>

            <div class="kaya-up-field">
              <label>Category</label>
              <select name="post_category" required>
                <?php
                $categories = get_terms(array('taxonomy' => 'category', 'hide_empty' => false));
                if (!is_wp_error($categories) && $categories) {
                  foreach ($categories as $cat) {
                    echo '<option value="' . esc_attr($cat->term_id) . '">' . esc_html($cat->name) . '</option>';
                  }
                }
                ?>
              </select>
            </div>
          </div>

          <div class="kaya-up-drop" id="kayaDrop">
            <div class="kaya-up-illu" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                <path d="M14 2v6h6"/>
                <path d="M12 18v-6"/>
                <path d="M9.5 14.5 12 12l2.5 2.5"/>
              </svg>
            </div>

            <div class="kaya-up-title">Drag &amp; drop your file</div>
            <div class="kaya-up-or">or</div>

            <button type="button" class="kaya-up-btn kaya-up-btn--primary" id="kayaPickBtn">
              Upload PDF
            </button>

            <div class="kaya-up-note">PDF up to <?php echo esc_html($max_mb_text); ?></div>

            <div class="kaya-up-filehint" id="kayaFileHint" style="display:none;">
              <span>Selected:</span> <b id="kayaFileName"></b>
            </div>

            <input type="file" name="pdf_file" accept="application/pdf" required id="kayaFileInput">
          </div>

          <div style="margin-top:14px; display:flex; justify-content:center;">
            <button type="submit" name="submit_pdf" class="kaya-up-btn kaya-up-btn--primary" style="min-width:320px;">
              Submit Upload
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script>
    (function(){
      const drop = document.getElementById('kayaDrop');
      const fileInput = document.getElementById('kayaFileInput');
      const pickBtn = document.getElementById('kayaPickBtn');
      const hint = document.getElementById('kayaFileHint');
      const nameEl = document.getElementById('kayaFileName');

      if (!drop || !fileInput) return;

      function showFileName(){
        const f = fileInput.files && fileInput.files[0];
        if (!f) { if (hint) hint.style.display = 'none'; return; }
        if (hint) hint.style.display = 'block';
        if (nameEl) nameEl.textContent = f.name;
      }

      if (pickBtn){
        pickBtn.addEventListener('click', function(e){
          e.preventDefault();
          fileInput.click();
        });
      }

      fileInput.addEventListener('change', showFileName);

      ['dragenter','dragover'].forEach(evt => {
        drop.addEventListener(evt, function(e)Z^*�p�s���������~��
�h����/script>

  <?php if (!empty($popup)) : ?>
  <script>
  document.addEventListener('DOMContentLoaded', function () {
    Swal.fire({
      icon: <?php echo wp_json_encode($popup['icon']); ?>,
      title: <?php echo wp_json_encode($popup['title']); ?>,
      html: <?php echo wp_json_encode($popup['html'] ?? ''); ?>,
      confirmButtonText: 'OK'
    });
  });
  </script>
  <?php endif; ?>

  <?php if (!empty($success_popup)) : ?>
  <script>
  document.addEventListener('DOMContentLoaded', function () {
    Swal.fire({
      icon: 'success',
      title: <?php echo wp_json_encode($success_popup['title']); ?>,
      html: `
        <div style="margin-bottom:14px;">
          <?php echo esc_js($success_popup['text']); ?>
        </div>
        <div style="display:flex; gap:10px; justify-content:center; flex-wrap:wrap;">
          <button type="button" id="swal-view-page-btn" class="swal2-styled" style="margin:0;">
            View Page
          </button>
          <button type="button" id="swal-open-pdf-btn" class="swal2-styled" style="margin:0; background:#6b7280;">
            Open PDF
          </button>
        </div>
      `,
      confirmButtonText: 'Close',
      allowOutsideClick: false,
      allowEscapeKey: false,
      allowEnterKey: false,
      showCloseButton: false,
      didOpen: function () {
        var viewBtn = document.getElementById('swal-view-page-btn');
        var pdfBtn  = document.getElementById('swal-open-pdf-btn');

        if (viewBtn) {
          viewBtn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            window.open(<?php echo wp_json_encode($success_popup['view_url']); ?>, '_blank');
          });
        }

        if (pdfBtn) {
          pdfBtn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            window.open(<?php echo wp_json_encode($success_popup['pdf_url']); ?>, '_blank');
          });
        }
      }
    });
  });
  </script>
  <?php endif; ?>

  <?php
  return ob_get_clean();
}

add_shortcode('pdf_frontend_upload', 'frontend_pdf_uploader_kaya_qr');�~��������������Z^*�
������{
          e.preventDefault(); e.stopPropagation();
          drop.classList.add('is-drag');
        });
      });
      ['dragleave','drop'].forEach(evt => {
        drop.addEventListener(evt, function(e){
          e.preventDefault(); e.stopPropagation();
          drop.classList.remove('is-drag');
        });
      });

      drop.addEventListener('drop', function(e){
        if (!e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files.length) return;
        fileInput.files = e.dataTransfer.files;
        showFileName();
      });
    })();
  </script>
  <?php

  return ob_get_clean();
}

add_shortcode('pdf_frontend_upload', 'frontend_pdf_uploader_kaya_qr');Z^*��w��
��������Z_D^
������   e.preventDefault(); e.stopPropagation();
          drop.classList.add('is-drag');
        });
      });
      ['dragleave','drop'].forEach(evt => {
        drop.addEventListener(evt, function(e){
          e.preventDefault(); e.stopPropagation();
          drop.classList.remove('is-drag');
        });
      });

      drop.addEventListener('drop', function(e){
        if (!e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files.length) return;
        fileInput.files = e.dataTransfer.files;
        showFileName();
      });
    })();
  </script>
  <?php

  return ob_get_clean();
}

add_shortcode('pdf_frontend_upload', 'frontend_pdf_uploader_kaya_qr');Z_D^g��	������E��9ˀ
j�H!infimumsupremumr����Certificateif (!defined('ABSPATH')) exit;

/**
 * Elementor Form -> Certificate Page
 * Fields expected:
 * name, email, my_addr_line1, my_addr_line2, my_postcode, my_city, my_state
 */

/** 1) Register hidden CPT to store certificates */
add_action('init', function () {
  register_post_type('ac_certificate', [
    'label' => 'Certificates',
    'public' => false,
    'show_ui' => true,
    'supports' => ['title'],
  ]);
});

/** 2) Capture Elementor submission and redirect to certificate page */
add_action('elementor_pro/forms/new_record', function ($record, $handler) {

  $form_name = (string) $record->get_form_settings('form_name');
  if ($form_name !== 'Address Certificate') return; // <-- change if needed

  $raw_fields = $record->get('fields');
  $fields = [];

  foreach ($raw_fields as $id => $field) {
    $val = isset($field['value']) ? wp_unslash($field['value']) : '';
    if (is_array($val)) $val = implode(', ', $val);
    $fields[$id] = sanitize_text_field($val);
  }

  // Generate secure access key for viewing
  $key = wp_generate_password(24, false, false);

  $title = 'CERT ' . (!empty($fields['name']) ? $fields['name'] : current_time('Y-m-d H:i'));

  $post_id = wp_insert_post([
    'post_type'   => 'ac_certificate',
    'post_status' => 'publish',
    'post_title'  => $title,
  ]);

  if (is_wp_error($post_id) || !$post_id) return;

  update_post_meta($post_id, '_ac_cert_key', $key);
  update_post_meta($post_id, '_ac_cert_fields', $fields);

  // Certificate page URL (must contain [ac_certificate_view])
  $cert_page_url = site_url('/certificate/'); // <-- change if your page slug differs

  $url = add_query_arg([
    'cid' => $post_id,
    'k'   => $key,
  ], $cert_page_url);

  // Redirect user after submission
  $handler->add_response_data('redirect_url', $url);

}, 10, 2);

/** 3) Shortcode renders the certificate */
add_shortcode('ac_certificate_view', function () {

  $cid = isset($_GET['cid']) ? absint($_GET['cid']) : 0;
  $k   = isset($_GET['k']) ? sanitize_text_field(wp_unslash($_GET['k'])) : '';

  if (!$cid || !$k) {
    return '<div style="padding:16px;border:1px solid #eee;border-radius:12px;">Missing certificate parameters.</div>';
  }

  if (get_post_type($cid) !== 'ac_certificate') {
    return '<div style="padding:16px;border:1px solid #fee2e2;border-radius:12px;color:#991b1b;">Invalid certificate.</div>';
  }

  $saved_key = (string) get_post_meta($cid, '_ac_cert_key', true);
  if (!$saved_key || !hash_equals($saved_key, $k)) {
    return '<div style="padding:16px;border:1px solid #fee2e2;border-radius:12px;color:#991b1b;">Access denied.</div>';
  }

  $f = (array) get_post_meta($cid, '_ac_cert_fields', true);
  $get = function($id) use ($f) {
    return isset($f[$id]) ? esc_html($f[$id]) : '';
  };

  // Build full address
  $addr1 = $get('my_addr_line1');
  $addr2 = $get('my_addr_line2');
  $pc    = $get('my_postcode');
  $city  = $get('my_city');
  $state = $get('my_state');

  $lineA = trim($addr1);
  $lineB = trim($addr2);
  $lineC = trim(($pc ? $pc . ' ' : '') . $city);
  $lineD = trim($state);

  ob_start();
  ?>
  <style>
    .ac-cert-wrap{ max-width:820px; margin:24px auto; padding:18px; background:#fff; }
    .ac-cert{
      border:3px double #bfc5d2; border-radius:10px;
      padding:34px 36px;
      font-family: Arial, sans-serif;
      color:#111827;
    }
    .ac-top{
      text-align:center;
      margin-bottom: 14px;
    }
    .ac-badge{
      display:inline-block;
      padding:8px 16px;
      border:2px solid #dc2626;
      color:#dc2626;
      font-weight:800;
      letter-spacing:2px;
      border-radius:6px;
      font-size:18px;
    }
    .ac-title{
      text-align:center;
      font-size:26px;
      font-weight:800;
      margin:14px 0 10px;
      letter-spacing: .8px;
    }
    .ac-sub{
      text-align:center;
      font-size:13px;
      color:#374151;
      margin-bottom: 22px;
    }
    .ac-row{ display:flex; gap:12px; margin:8px 0; }
    .ac-label{ width:170px; font-weight:700; }
    .ac-value{ flex:1; }
    .ac-box{
      margin-top: 18px;
      border:1px solid #e5e7eb;
      border-radius:10px;
      padding:14px 16px;
      background:#f9fafb;
    }
    .ac-address div{ margin:2px 0; }
    .no-print{ display:flex; justify-content:flex-end; margin-bottom:10px; }
    .btn{
      padding:10px 14px;
      border-radius:10px;
      border:1px solid #e5e7eb;
      background:#111827;
      color:#fff;
      cursor:pointer;
      font-weight:700;
    }
    .ac-foot{
      margin-top: 22px;
      display:flex;
      justify-content: space-between;
      font-size:12px;
      color:#6b7280;
      gap: 10px;
    }
    @media print{
      .no-print{ display:none !important; }
      .ac-cert-wrap{ margin:0; padding:0; }
    }
  </style>

  <div class="ac-cert-wrap">
    <div class="no-print">
      <button class="btn" onclick="window.print()">Print / Save as PDF</button>
    </div>

    <div class="ac-cert">
      <div class="ac-top">
        <div class="ac-badge">CERT</div>
      </div>

      <div class="ac-title">CERTIFICATE OF CONFIRMATION</div>
      <div class="ac-sub">This document confirms the details submitted via our form.</div>

      <div class="ac-row">
        <div class="ac-label">Name:</div>
        <div class="ac-value"><b><?php echo $get('name'); ?></b></div>
      </div>

      <div class="ac-row">
        <div class="ac-label">Email:</div>
        <div class="ac-value"><?php echo $get('email'); ?></div>
      </div>

      <div class="ac-box">
        <div class="ac-row" style="margin-top:0;">
          <div class="ac-label">Address:</div>
          <div class="ac-value ac-address">
            <?php if ($lineA) : ?><div><?php echo $lineA; ?></div><?php endif; ?>
            <?php if ($lineB) : ?><div><?php echo $lineB; ?></div><?php endif; ?>
            <?php if ($lineC) : ?><div><?php echo $lineC; ?></div><?php endif; ?>
            <?php if ($lineD) : ?><div><?php echo $lineD; ?></div><?php endif; ?>
          </div>
        </div>
      </div>

      <div class="ac-foot">
        <div>Generated: <?php echo esc_html(current_time('Y-m-d H:i')); ?></div>
        <div><?php echo esc_html(home_url()); ?></div>
      </div>
    </div>
  </div>
  <?php
  return ob_get_clean();
});global��
���Fy�������DOWNLOAD QR<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

<script>
document.addEventListener('click', function(e){

  const btn = e.target.closest('.kaya-download-qr-btn');
  if(!btn) return;

  const targetId = btn.getAttribute('data-target');
  const filename = btn.getAttribute('data-filename') || 'qr-image.png';

  const box = document.getElementById(targetId);

  if(!box) return;

  html2canvas(box,{
    backgroundColor:'#ffffff',
    scale:2
  }).then(function(canvas){

    const link = document.createElement('a');
    link.download = filename;
    link.href = canvas.toDataURL("image/png");
    link.click();

  });

});
</script>site-footer-js��
���Zs,�� 9��LOAD HTML2CANVASfunction kaya_enqueue_qr_assets() {
  wp_enqueue_script(
    'html2canvas',
    'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js',
    array(),
    '1.4.1',
    true
  );
}
add_action('wp_enqueue_scripts', 'kaya_enqueue_qr_assets');global��
���Z|t��(�ހ�PDF Edit�&f�global��
����P�x�
0�Table Creator/**
 * KAYA WEBSTATION CERTIFICATES TABLE SETUP
 * Run only when version changes
 */

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

if (!defined('KAYA_WEBSTATION_CERT_TABLE_VERSION')) {
  define('KAYA_WEBSTATION_CERT_TABLE_VERSION', '1.0.0');
}

/**
 * Create Webstation certificates table
 */
function kaya_create_webstation_certificates_table() {
  global $wpdb;

  $table_name = $wpdb->prefix . 'kaya_certificates';
  $charset_collate = $wpdb->get_charset_collate();

  require_once ABSPATH . 'wp-admin/includes/upgrade.php';

  $sql = "CREATE TABLE {$table_name} (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    post_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
    cust_name VARCHAR(255) NOT NULL DEFAULT '',
    title VARCHAR(255) NOT NULL DEFAULT '',
    category_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
    category_slug VARCHAR(200) NOT NULL DEFAULT '',
    pdf_url TEXT NOT NULL,
    today_date DATE DEFAULT NULL,
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    is_active CHAR(1) NOT NULL DEFAULT 'T',
    PRIMARY KEY (id),
    KEY post_id (post_id),
    KEY cust_name (cust_name),
    KEY title (title),
    KEY category_id (category_id),
    KEY category_slug (category_slug),
    KEY today_date (today_date),
    KEY created_by (created_by),
    KEY is_active (is_active)
  ) {$charset_collate};";

  dbDelta($sql);
}

/**
 * Run only when version changes
 */
function kaya_maybe_upgrade_webstation_certificates_table() {
  $saved_version = get_option('kaya_webstation_cert_table_version', '');

  if ($saved_version === KAYA_WEBSTATION_CERT_TABLE_VERSION) {
    return;
  }

  kaya_create_webstation_certificates_table();
  update_option('kaya_webstation_cert_table_version', KAYA_WEBSTATION_CERT_TABLE_VERSION);
}

add_action('init', 'kaya_maybe_upgrade_webstation_certificates_table');global��
��\=��
8���PDF Upload�&��global��
����4�ه
@�߀�Table Creator/**
 * KAYA WEBSTATION CERTIFICATES TABLE SETUP
 * Run only when version changes
 */

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

if (!defined('KAYA_WEBSTATION_CERT_TABLE_VERSION')) {
  define('KAYA_WEBSTATION_CERT_TABLE_VERSION', '1.0.1');
}

/**
 * Create Webstation certificates table
 */
function kaya_create_webstation_certificates_table() {
  global $wpdb;

  $table_name = $wpdb->prefix . 'kaya_certificates';
  $charset_collate = $wpdb->get_charset_collate();

  require_once ABSPATH . 'wp-admin/includes/upgrade.php';

  $sql = "CREATE TABLE {$table_name} (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    post_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
    document_number VARCHAR(100) NOT NULL DEFAULT '',
    cust_name VARCHAR(255) NOT NULL DEFAULT '',
    title VARCHAR(255) NOT NULL DEFAULT '',
    category_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
    category_slug VARCHAR(200) NOT NULL DEFAULT '',
    pdf_url TEXT NOT NULL,
    today_date DATE DEFAULT NULL,
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    is_active CHAR(1) NOT NULL DEFAULT 'T',
    PRIMARY KEY (id),
    KEY post_id (post_id),
    KEY document_number (document_number),
    KEY cust_name (cust_name),
    KEY title (title),
    KEY category_id (category_id),
    KEY category_slug (category_slug),
    KEY today_date (today_date),
    KEY created_by (created_by),
    KEY is_active (is_active)
  ) {$charset_collate};";

  dbDelta($sql);
}

/**
 * Run only when version changes
 */
function kaya_maybe_upgrade_webstation_certificates_table() {
  $saved_version = get_option('kaya_webstation_cert_table_version', '');

  if ($saved_version === KAYA_WEBSTATION_CERT_TABLE_VERSION) {
    return;
  }

  kaya_create_webstation_certificates_table();
  update_option('kaya_webstation_cert_table_version', KAYA_WEBSTATION_CERT_TABLE_VERSION);
}

add_action('init', 'kaya_maybe_upgrade_webstation_certificates_table');global��
���\C7���H��Useradd_filter('wp_nav_menu_items', 'my_wppb_login_logout_menu_item', 10, 2);
function my_wppb_login_logout_menu_item($items, $args) {

    if ($args->theme_location !== 'primary') {
        return $items;
    }

    $login_page_url  = 'https://invoice.webstation.my/index.php/login-page/';
    $logout_redirect = home_url('/');
    $logout_url      = wp_logout_url($logout_redirect);

    if (is_user_logged_in()) {
        $current_user = wp_get_current_user();
        $name = $current_user->display_name ? $current_user->display_name : $current_user->user_login;

        $items .= '<li class="menu-item menu-item-user-name">
            <a href="#">Hi, ' . esc_html($name) . '</a>
        </li>';

        $items .= '<li class="menu-item menu-item-logout">
            <a href="' . esc_url($logout_url) . '">Logout</a>
        </li>';
    } else {
        $items .= '<li class="menu-item menu-item-login">
            <a href="' . esc_url($login_page_url) . '">Login</a>
        </li>';
    }

    return $items;
}global��
���`��p-xc��M-M���������g��
�?�/**
 * FRONTEND PDF UPLOAD -> Create Post with PDF Viewer + QR + Store Record In Custom Table
 * Shortcode: [pdf_frontend_upload]
 *
 * NEW WEBSITE VERSION
 * - New table only, no ALTER logic
 * - Form asks: Customer Name, Title, Category
 * - QR block shows Webstation info + customer name
 * - Soft delete support with is_active
 */

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

/** =========================
 * SETTINGS
 * ========================= */
if (!defined('KAYA_INV_SHOW_FILE_URL')) {
  define('KAYA_INV_SHOW_FILE_URL', true);
}
if (!defined('KAYA_INV_QR_FILENAME_PREFIX')) {
  define('KAYA_INV_QR_FILENAME_PREFIX', 'QR-');
}

/** =========================
 * CREATE TABLE
 * ========================= */
function kaya_create_certificates_table() {
  global $wpdb;

  $table_name = $wpdb->prefix . 'kaya_certificates';
  $charset_collate = $wpdb->get_charset_collate();

  require_once ABSPATH . 'wp-admin/includes/upgrade.php';

  $sql = "CREATE TABLE {$table_name} (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    post_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
    cust_name VARCHAR(255) NOT NULL DEFAULT '',
    title VARCHAR(255) NOT NULL DEFAULT '',
    category_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
    category_slug VARCHAR(200) NOT NULL DEFAULT '',
    pdf_url TEXT NOT NULL,
    today_date DATE DEFAULT NULL,
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    is_active CHAR(1) NOT NULL DEFAULT 'T',
    PRIMARY KEY (id),
    KEY post_id (post_id),
    KEY cust_name (cust_name),
    KEY title (title),
    KEY category_id (category_id),
    KEY category_slug (category_slug),
    KEY today_date (today_date),
    KEY created_by (created_by),
    KEY is_active (is_active)
  ) {$charset_collate};";

  dbDelta($sql);
}

/** Add CSS class to generated posts */
add_filter('post_class', function($classes, $class, $post_id){
  if (get_post_meta($post_id, '_kaya_invoice_post', true)) {
    $classes[] = 'kaya-invoice-post';
    $classes[] = 'kaya-invoice-post--webstation';
  }
  return $classes;
}, 10, 3);

/** Shortcode */
function frontend_pdf_uploader_kaya_qr() {

  kaya_create_certificates_table();

  if (!is_user_logged_in()) {
    return '<div class="kaya-up-alert kaya-up-alert--warn">Please login to upload PDF.</div>';
  }

  $current_user = wp_get_current_user();

  if (!array_intersect(['administrator','editor'], (array) $current_user->roles)) {
    return '<div class="kaya-up-alert kaya-up-alert--err">Only administrators or editors can upload documents.</div>';
  }

  $flash = '';
  $BASE_REL = 'FILES';
  $max_mb_text = '100 MB';

  if (
    isset($_POST['submit_pdf'], $_POST['kaya_pdf_upload_nonce']) &&
    wp_verify_nonce($_POST['kaya_pdf_upload_nonce'], 'kaya_pdf_upload_action')
  ) {
    if (empty($_FILES['pdf_file']['name'])) {
      $flash = '<div class="kaya-up-alert kaya-up-alert--err">Please select a PDF file.</div>';
    } else {
      $cust_name   = sanitize_text_field(wp_unslash($_POST['cust_name'] ?? ''));
      $title       = sanitize_text_field(wp_unslash($_POST['title'] ?? ''));
      $category_id = absint($_POST['post_category'] ?? 0);
      $today_date  = current_time('Y-m-d');
      $category    = get_term($category_id, 'category');

      if ($cust_name === '') {
        $flash = '<div class="kaya-up-alert kaya-up-alert--err">Please fill in Customer Name.</div>';
      } elseif ($title === '') {
        $flash = '<div class="kaya-up-alert kaya-up-alert--err">Please fill in Title.</div>';
      } elseif (!$category || is_wp_error($category)) {
        $flash = '<div class="kaya-up-alert kaya-up-alert--err">Invalid category.</div>';
      } else {
        $slug = sanitize_title($category->slug);

        if ($slug === '') {
          $flash = '<div class="kaya-up-alert kaya-up-alert--err">Category slug is empty.</div>';
        } else {
          $folder_name = strtoupper($slug);

          $target_dir = rtrim(ABSPATH, '/\\') . DIRECTORY_SEPARATOR
                      . trim($BASE_REL, '/\\') . DIRECTORY_SEPARATOR
                      . $folder_name . DIRECTORY_SEPARATOR;

          $base_url = home_url('/' . trim($BASE_REL, '/\\') . '/' . $folder_name . '/');

          if (!is_dir($target_dir)) {
            $flash = '<div class="kaya-up-alert kaya-up-alert--err"><b>Folder does not exist</b><div class="kaya-up-small">'
                   . esc_html($target_dir) . '</div></div>';
          } elseif (!is_writable($target_dir)) {
            $flash = '<div class="kaya-up-alert kaya-up-alert--err"><b>Folder not writable</b><div class="kaya-up-small">'
                   . esc_html($target_dir) . '</div></div>';
          } else {
            $file  = $_FILES['pdf_file'];
            $check = wp_check_filetype_and_ext($file['tmp_name'], $file['name']);
            $ext   = strtolower((string)($check['ext'] ?? ''));

            if ($ext !== 'pdf') {
              $flash = '<div class="kaya-up-alert kaya-up-alert--err">Only PDF allowed.</div>';
            } else {
              $random      = wp_generate_password(20, false, false);
              $filename    = strtolower($random) . '.pdf';
              $target_path = $target_dir . $filename;

              if (!@move_uploaded_file($file['tmp_name'], $target_path)) {
                $err = error_get_last();
                $flash  = '<div class="kaya-up-alert kaya-up-alert--err"><b>Upload failed while moving file</b>.</div>';
                $flash .= '<div class="kaya-up-debug"><b>Target:</b> ' . esc_html($target_path) . '<br><pre>'
                        . esc_html(print_r($err, true)) . '</pre></div>';
              } else {
                $pdf_url   = $base_url . rawurlencode($filename);
                $row_title = $title;

                $qepw = '[qepw_pdf_viewer file="' . esc_url($pdf_url) . '"]';

                // New QR block with separate view and print templates
                $qr_view_id     = 'kaya-qr-view-' . wp_generate_password(8, false, false);
                $qr_print_id    = 'kaya-qr-print-' . wp_generate_password(8, false, false);

                $kaya_qr = '
                  <div class="kaya-qr-download-wrap kaya-webstation-qr" id="' . esc_attr($qr_view_id) . '">
                    <div class="kaya-webstation-company">WEBSTATION COMPUTER CENTRE</div>
                    <div class="kaya-webstation-phone-main">1700 822 922</div>
                    <div class="kaya-webstation-contact">TEL: 05-2822919 FAX: 05-2811919 H/Phone: 016-550 8505</div>
                    <div class="kaya-webstation-contact">E-mail: sales@webstation.my</div>

                    <div class="kaya-webstation-customer">' . esc_html($title) . '</div>

                    <div class="kaya-qr-download-inner">
                      [kaya_qrcode content="' . esc_url($pdf_url) . '" dynamic_content="0" download_button="0" download_align="aligncenter"]
                    </div>
                  </div>

					<div class="kaya-qr-print-template" aria-hidden="true">
					  <div class="kaya-webstation-print" id="' . esc_attr($qr_print_id) . '">
						<div class="kaya-webstation-print-company">WEBSTATION COMPUTER CENTRE</div>
						<div class="kaya-webstation-print-phone">1700 822 922</div>
						<div class="kaya-webstation-print-contact">TEL: 05-2822919 FAX: 05-2811919 H/Phone: 016-550 8505</div>
						<div class="kaya-webstation-print-contact">E-mail: sales@webstation.my</div>

						<div class="kaya-webstation-print-customer">' . esc_html($title) . '</div>

						<div class="kaya-qr-download-inner">
						  [kaya_qrcode content="' . esc_url($pdf_url) . '" dynamic_content="0" download_button="0" download_align="aligncenter"]
						</div>
					  </div>
					</div>

                  <div class="kaya-qr-download-actions">
                    <button type="button"
                            class="kaya-up-btn kaya-up-btn--primary kaya-download-qr-btn"
                            data-target="' . esc_attr($qr_print_id) . '"
                            data-filename="' . esc_attr(sanitize_file_name($title . '-' . $title)) . '-qr.png">
                      Download QR Image
                    </button>
                  </div>
                ';

                $content = '<div class="kaya-inv-page kaya-inv-page--webstation">' .
                  '<div class="kaya-inv-viewer kaya-inv-viewer--qepw">' .
                    $qepw .
                  '</div>' .
                  '<div class="kaya-inv-qr kaya-inv-qr--kaya">' .
                    '<div class="kaya-inv-qrbox">' .
                      $kaya_qr .
                    '</div>';

                $content .= '<div class="kaya-inv-meta">' .
                              '<div class="kaya-inv-label">Customer Name</div>' .
                              '<div class="kaya-inv-text">' . esc_html($cust_name) . '</div>' .
                            '</div>';

                $content .= '<div class="kaya-inv-meta">' .
                              '<div class="kaya-inv-label">Title</div>' .
                              '<div class="kaya-inv-text">' . esc_html($title) . '</div>' .
                            '</div>';

                if (KAYA_INV_SHOW_FILE_URL) {
                  $content .= '<div class="kaya-inv-meta">' .
                                '<div class="kaya-inv-label">File URL</div>' .
                                '<div class="kaya-inv-url">' . esc_html($pdf_url) . '</div>' .
                              '</div>';
                }

                $content .= '<div class="kaya-inv-meta">' .
                              '<div class="kaya-inv-label">Created Date</div>' .
                              '<div class="kaya-inv-text">' . esc_html($today_date) . '</div>' .
                            '</div>';

                $content .= '</div></div>';

                $post_id = wp_insert_post(array(
                  'post_title'    => $row_title,
                  'post_content'  => $content,
                  'post_status'   => 'publish',
                  'post_type'     => 'post',
                  'post_category' => array($category_id),
                  'post_author'   => get_current_user_id()
                ), true);

                if (is_wp_error($post_id)) {
                  $flash = '<div class="kaya-up-alert kaya-up-alert--err">Post creation failed: '
                         . esc_html($post_id->get_error_message()) . '</div>';
                } else {
                  update_post_meta($post_id, '_kaya_invoice_post', 1);
                  update_post_meta($post_id, '_kaya_invoice_pdf_url', esc_url_raw($pdf_url));
                  update_post_meta($post_id, '_kaya_cust_name', $cust_name);
                  update_post_meta($post_id, '_kaya_title', $title);
                  update_post_meta($post_id, '_kaya_today_date', $today_date);

                  global $wpdb;
                  $table_name = $wpdb->prefix . 'kaya_certificates';

                  $inserted = $wpdb->insert(
                    $table_name,
                    array(
                      'post_id'       => $post_id,
                      'cust_name'     => $cust_name,
                      'title'         => $title,
                      'category_id'   => $category_id,
                      'category_slug' => $slug,
                      'pdf_url'       => esc_url_raw($pdf_url),
                      'today_date'    => $today_date,
                      'created_by'    => get_current_user_id(),
                      'is_active'     => 'T',
                    ),
                    array(
                      '%d',
                      '%s',
                      '%s',
                      '%d',
                      '%s',
                      '%s',
                      '%s',
                      '%d',
                      '%s',
                    )
                  );

                  if ($inserted === false) {
                    $flash = '<div class="kaya-up-alert kaya-up-alert--err"><b>Upload succeeded but DB insert failed.</b><div class="kaya-up-small">'
                           . esc_html($wpdb->last_error) . '</div>'
                           . '<div class="kaya-up-actions">'
                           . '<a class="kaya-up-btn kaya-up-btn--primary" href="' . esc_url(get_permalink($post_id)) . '" target="_blank" rel="noopener">View Page</a>'
                           . '<a class="kaya-up-btn kaya-up-btn--ghost" href="' . esc_url($pdf_url) . '" target="_blank" rel="noopener">Open PDF</a>'
                           . '</div></div>';
                  } else {
                    $flash = '<div class="kaya-up-alert kaya-up-alert--ok">
                      <b>Upload Successful!</b>
                      <div class="kaya-up-actions">
                        <a class="kaya-up-btn kaya-up-btn--primary" href="' . esc_url(get_permalink($post_id)) . '" target="_blank" rel="noopener">View Page</a>
                        <a class="kaya-up-btn kaya-up-btn--ghost" href="' . esc_url($pdf_url) . '" target="_blank" rel="noopener">Open PDF</a>
                      </div>
                    </div>';
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  ob_start();
  ?>
  <div class="kaya-up">
    <div class="kaya-up-shell">
      <?php echo $flash; ?>

      <div class="kaya-up-card">
        <form method="post" enctype="multipart/form-data">
          <?php wp_nonce_field('kaya_pdf_upload_action', 'kaya_pdf_upload_nonce'); ?>

          <div class="kaya-up-top">
            <div class="kaya-up-field">
              <label>Customer Name</label>
              <input type="text" name="cust_name" placeholder="Enter customer name" required>
            </div>

            <div class="kaya-up-field">
              <label>Title</label>
              <input type="text" name="title" placeholder="Enter document title" required>
            </div>
          </div>

          <div class="kaya-up-top">
            <div class="kaya-up-field" style="max-width:100%;">
              <label>Category</label>
              <select name="post_category" required>
                <?php
                $categories = get_terms(array(
                  'taxonomy'   => 'category',
                  'hide_empty' => false
                ));
                if (!is_wp_error($categories) && $categories) {
                  foreach ($categories as $cat) {
                    echo '<option value="' . esc_attr($cat->term_id) . '">' . esc_html($cat->name) . '</option>';
                  }
                }
                ?>
              </select>
            </div>
          </div>

          <div class="kaya-up-drop" id="kayaDrop">
            <div class="kaya-up-illu" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                <path d="M14 2v6h6"/>
                <path d="M12 18v-6"/>
                <path d="M9.5 14.5 12 12l2.5 2.5"/>
              </svg>
            </div>

            <div class="kaya-up-title">Drag &amp; drop your file</div>
            <div class="kaya-up-or">or</div>

            <button type="button" class="kaya-up-btn kaya-up-btn--primary" id="kayaPickBtn">
              Upload PDF
            </button>

            <div class="kaya-up-note">PDF up to <?php echo esc_html($max_mb_text); ?></div>

            <div class="kaya-up-filehint" id="kayaFileHint" style="display:none;">
              <span>Selected:</span> <b id="kayaFileName"></b>
            </div>

            <input type="file" name="pdf_file" accept="application/pdf" required id="kayaFileInput">
          </div>

          <div style="margin-top:14px; display:flex; justify-content:center;">
            <button type="submit" name="submit_pdf" class="kaya-up-btn kaya-up-btn--primary" style="min-width:320px;">
              Submit Upload
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

  <script>
    (function(){
      const drop = document.getElementById('kayg��9��}��������m�]/
�?�/**
 * FRONTEND PDF EDIT SHORTCODE FOR INVOICE PAGE
 * Shortcode: [pdf_frontend_edit]
 *
 * - Edits an existing invoice/document row using ?edit_id=ID
 * - Updates wp_kaya_certificates and related WP post
 * - PDF upload is optional; if not selected, old PDF is kept
 * - If new PDF is uploaded, existing filename is reused so URL stays unchanged
 * - Success popup contains custom "View Page" and "Open PDF" buttons
 * - Today Date field removed from edit form; existing created date is preserved
 */

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

/** =========================
 * SETTINGS
 * ========================= */
if (!defined('KAYA_INV_SHOW_FILE_URL')) {
  define('KAYA_INV_SHOW_FILE_URL', true);
}
if (!defined('KAYA_INV_QR_FILENAME_PREFIX')) {
  define('KAYA_INV_QR_FILENAME_PREFIX', 'QR-');
}

/** =========================
 * HELPERS
 * ========================= */
if (!function_exists('kaya_webstation_certificates_table_exists')) {
  function kaya_webstation_certificates_table_exists() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'kaya_certificates';

    $found = $wpdb->get_var($wpdb->prepare(
      "SHOW TABLES LIKE %s",
      $table_name
    ));

    return ($found === $table_name);
  }
}

if (!function_exists('kaya_cert_get_existing_pdf_filename')) {
  function kaya_cert_get_existing_pdf_filename($pdf_url) {
    $path = wp_parse_url($pdf_url, PHP_URL_PATH);
    if (!$path) return '';
    return basename($path);
  }
}

/** =========================
 * SHORTCODE
 * ========================= */
function frontend_pdf_editor_kaya_qr_invoice() {

  if (!is_user_logged_in()) {
    return '<div class="kaya-up-alert kaya-up-alert--warn">Please login to edit document.</div>';
  }

  $current_user = wp_get_current_user();

  if (!array_intersect(['administrator','editor'], (array) $current_user->roles)) {
    return '<div class="kaya-up-alert kaya-up-alert--err">Only administrators or editors can edit documents.</div>';
  }

  if (!kaya_webstation_certificates_table_exists()) {
    return '<div class="kaya-up-alert kaya-up-alert--err">Certificate table is missing. Please enable the table setup snippet first.</div>';
  }

  global $wpdb;
  $table_name = $wpdb->prefix . 'kaya_certificates';

  $flash = '';
  $success_popup = null;

  $BASE_REL = 'FILES';
  $max_mb_text = '100 MB';

  $edit_id = absint($_GET['edit_id'] ?? 0);
  if ($edit_id <= 0) {
    return '<div class="kaya-up-alert kaya-up-alert--err">Missing or invalid edit_id.</div>';
  }

  $existing = $wpdb->get_row(
    $wpdb->prepare("SELECT * FROM {$table_name} WHERE id = %d LIMIT 1", $edit_id),
    ARRAY_A
  );

  if (!$existing) {
    return '<div class="kaya-up-alert kaya-up-alert--err">Document record not found.</div>';
  }

  $post_id_existing = isset($existing['post_id']) ? absint($existing['post_id']) : 0;
  $post_existing = $post_id_existing ? get_post($post_id_existing) : null;

  if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['kaya_pdf_edit_nonce']) &&
    wp_verify_nonce($_POST['kaya_pdf_edit_nonce'], 'kaya_pdf_edit_action')
  ) {
    $cust_name       = sanitize_text_field(wp_unslash($_POST['cust_name'] ?? ''));
    $document_number = sanitize_text_field(wp_unslash($_POST['document_number'] ?? ''));
    $title           = sanitize_text_field(wp_unslash($_POST['title'] ?? ''));
    $category_id     = absint($_POST['post_category'] ?? 0);
    $category        = get_term($category_id, 'category');

    if ($cust_name === '') {
      $flash = '<div class="kaya-up-alert kaya-up-alert--err">Please fill in Customer Name.</div>';
    } elseif ($document_number === '') {
      $flash = '<div class="kaya-up-alert kaya-up-alert--err">Please fill in Document Number.</div>';
    } elseif ($title === '') {
      $flash = '<div class="kaya-up-alert kaya-up-alert--err">Please fill in Title.</div>';
    } elseif (!$category || is_wp_error($category)) {
      $flash = '<div class="kaya-up-alert kaya-up-alert--err">Invalid category.</div>';
    } else {
      $slug = sanitize_title($category->slug);

      if ($slug === '') {
        $flash = '<div class="kaya-up-alert kaya-up-alert--err">Category slug is empty.</div>';
      } else {
        $folder_name = strtoupper($slug);

        $target_dir = rtrim(ABSPATH, '/\\') . DIRECTORY_SEPARATOR
                    . trim($BASE_REL, '/\\') . DIRECTORY_SEPARATOR
                    . $folder_name . DIRECTORY_SEPARATOR;

        $base_url = home_url('/' . trim($BASE_REL, '/\\') . '/' . $folder_name . '/');

        if (!is_dir($target_dir)) {
          $flash = '<div class="kaya-up-alert kaya-up-alert--err"><b>Folder does not exist</b><div class="kaya-up-small">'
                 . esc_html($target_dir) . '</div></div>';
        } elseif (!is_writable($target_dir)) {
          $flash = '<div class="kaya-up-alert kaya-up-alert--err"><b>Folder not writable</b><div class="kaya-up-small">'
                 . esc_html($target_dir) . '</div></div>';
        } else {
          $pdf_url = isset($existing['pdf_url']) ? (string) $existing['pdf_url'] : '';
          $new_file_uploaded = !empty($_FILES['pdf_file']['name']);
          $created_date = !empty($existing['today_date']) ? (string) $existing['today_date'] : '';

          if ($new_file_uploaded) {
            $file  = $_FILES['pdf_file'];
            $check = wp_check_filetype_and_ext($file['tmp_name'], $file['name']);
            $ext   = strtolower((string)($check['ext'] ?? ''));

            if ($ext !== 'pdf') {
              $flash = '<div class="kaya-up-alert kaya-up-alert--err">Only PDF allowed.</div>';
            } else {
              $old_pdf_url  = isset($existing['pdf_url']) ? (string) $existing['pdf_url'] : '';
              $old_filename = kaya_cert_get_existing_pdf_filename($old_pdf_url);

              if ($old_filename === '') {
                $flash = '<div class="kaya-up-alert kaya-up-alert--err">Existing PDF filename could not be detected.</div>';
              } else {
                $target_path = $target_dir . $old_filename;

                if (is_file($target_path)) {
                  @unlink($target_path);
                }

                if (!@move_uploaded_file($file['tmp_name'], $target_path)) {
                  $err = error_get_last();
                  $flash  = '<div class="kaya-up-alert kaya-up-alert--err"><b>Upload failed while replacing file</b>.</div>';
                  $flash .= '<div class="kaya-up-debug"><b>Target:</b> ' . esc_html($target_path) . '<br><pre>'
                          . esc_html(print_r($err, true)) . '</pre></div>';
                } else {
                  $pdf_url = $old_pdf_url;
                }
              }
            }
          }

          if ($flash === '') {
            $row_title = $title;

            $qr_view_id  = 'kaya-qr-view-' . wp_generate_password(8, false, false);
            $qr_print_id = 'kaya-qr-print-' . wp_generate_password(8, false, false);

            $qepw = '[qepw_pdf_viewer file="' . esc_url($pdf_url) . '"]';

            $kaya_qr = '
              <div class="kaya-qr-download-wrap kaya-webstation-qr" id="' . esc_attr($qr_view_id) . '">
                <div class="kaya-webstation-company">WEBSTATION COMPUTER CENTRE</div>
                <div class="kaya-webstation-phone-main">1700 822 922</div>
                <div class="kaya-webstation-contact">TEL: 05-2822919 FAX: 05-2811919 H/Phone: 016-550 8505</div>
                <div class="kaya-webstation-contact">E-mail: sales@webstation.my</div>

                <div class="kaya-webstation-customer">' . esc_html($cust_name) . '</div>
                <div class="kaya-webstation-docno">' . esc_html($document_number) . '</div>

                <div class="kaya-qr-download-inner">
                  [kaya_qrcode content="' . esc_url($pdf_url) . '" dynamic_content="0" download_button="0" download_align="aligncenter"]
                </div>
              </div>

              <div class="kaya-qr-print-template" aria-hidden="true">
                <div class="kaya-webstation-print" id="' . esc_attr($qr_print_id) . '">

                  <div class="kaya-webstation-print-top">
                    <div class="kaya-webstation-print-left">
                      <div class="kaya-webstation-print-company">WEBSTATION</div>
                      <div class="kaya-webstation-print-branch">COMPUTER CENTRE</div>
                      <div class="kaya-webstation-print-phone">1700 822 922</div>

                      <div class="kaya-webstation-print-customer">' . esc_html($cust_name) . '</div>
                      <div class="kaya-webstation-print-docno">' . esc_html($document_number) . '</div>

                      <div class="kaya-webstation-print-contact">TEL: 05-2822919</div>
                      <div class="kaya-webstation-print-contact">FAX: 05-2811919</div>
                      <div class="kaya-webstation-print-contact">H/P: 016-550 8505</div>
                    </div>

                    <div class="kaya-webstation-print-right">
                      <div class="kaya-qr-download-inner">
                        [kaya_qrcode content="' . esc_url($pdf_url) . '" dynamic_content="0" size="440" download_button="0" download_align="aligncenter"]
                      </div>
                    </div>
                  </div>

                  <div class="kaya-webstation-print-email">
                    E-mail: sales@webstation.my
                  </div>

                </div>
              </div>

              <div class="kaya-qr-download-actions">
                <button type="button"
                        class="kaya-up-btn kaya-up-btn--primary kaya-download-qr-btn"
                        data-target="' . esc_attr($qr_print_id) . '"
                        data-filename="' . esc_attr(sanitize_file_name($document_number . '-' . $title)) . '-qr.png">
                  Download QR Image
                </button>
              </div>
            ';

            $content = '<div class="kaya-inv-page kaya-inv-page--webstation">' .
              '<div class="kaya-inv-viewer kaya-inv-viewer--qepw">' .
                $qepw .
              '</div>' .
              '<div class="kaya-inv-qr kaya-inv-qr--kaya">' .
                '<div class="kaya-inv-qrbox">' .
                  $kaya_qr .
                '</div>';

            $content .= '<div class="kaya-inv-meta">' .
                          '<div class="kaya-inv-label">Customer Name</div>' .
                          '<div class="kaya-inv-text">' . esc_html($cust_name) . '</div>' .
                        '</div>';

            $content .= '<div class="kaya-inv-meta">' .
                          '<div class="kaya-inv-label">Document Number</div>' .
                          '<div class="kaya-inv-text">' . esc_html($document_number) . '</div>' .
                        '</div>';

            $content .= '<div class="kaya-inv-meta">' .
                          '<div class="kaya-inv-label">Title</div>' .
                          '<div class="kaya-inv-text">' . esc_html($title) . '</div>' .
                        '</div>';

            if (KAYA_INV_SHOW_FILE_URL) {
              $content .= '<div class="kaya-inv-meta">' .
                            '<div class="kaya-inv-label">File URL</div>' .
                            '<div class="kaya-inv-url">' . esc_html($pdf_url) . '</div>' .
                          '</div>';
            }

            if ($created_date !== '') {
              $content .= '<div class="kaya-inv-meta">' .
                            '<div class="kaya-inv-label">Created Date</div>' .
                            '<div class="kaya-inv-text">' . esc_html($created_date) . '</div>' .
                          '</div>';
            }

            $content .= '</div></div>';

            $post_result = false;

            if ($post_existing) {
              $post_result = wp_update_post([
                'ID'            => $post_id_existing,
                'post_title'    => $row_title,
                'post_content'  => $content,
                'post_category' => [$category_id],
              ], true);
            } else {
              $post_result = wp_insert_post([
                'post_title'    => $row_title,
                'post_content'  => $content,
                'post_status'   => 'publish',
                'post_type'     => 'post',
                'post_category' => [$category_id],
                'post_author'   => get_current_user_id()
              ], true);

              if (!is_wp_error($post_result)) {
                $post_id_existing = (int) $post_result;
              }
            }

            if (is_wp_error($post_result)) {
              $flash = '<div class="kaya-up-alert kaya-up-alert--err">Post update failed: '
                     . esc_html($post_result->get_error_message()) . '</div>';
            } else {
              $updated = $wpdb->update(
                $table_name,
                [
                  'post_id'         => $post_id_existing,
                  'document_number' => $document_number,
                  'cust_name'       => $cust_name,
                  'title'           => $title,
                  'category_id'     => $category_id,
                  'category_slug'   => $slug,
                  'pdf_url'         => esc_url_raw($pdf_url),
                ],
                ['id' => $edit_id],
                ['%d','%s','%s','%s','%d','%s','%s'],
                ['%d']
              );

              if ($updated === false) {
                $flash = '<div class="kaya-up-alert kaya-up-alert--err"><b>Post updated but DB update failed.</b><div class="kaya-up-small">'
                       . esc_html($wpdb->last_error) . '</div></div>';
              } else {
                update_post_meta($post_id_existing, '_kaya_invoice_post', 1);
                update_post_meta($post_id_existing, '_kaya_invoice_pdf_url', esc_url_raw($pdf_url));
                update_post_meta($post_id_existing, '_kaya_cust_name', $cust_name);
                update_post_meta($post_id_existing, '_kaya_document_number', $document_number);
                update_post_meta($post_id_existing, '_kaya_title', $title);
                update_post_meta($post_id_existing, '_kaya_cert_row_id', $edit_id);

                $success_popup = [
                  'title'    => 'Update Successful!',
                  'text'     => 'Document has been updated successfully.',
                  'view_url' => get_permalink($post_id_existing),
                  'pdf_url'  => $pdf_url,
                ];

                $existing = $wpdb->get_row(
                  $wpdb->prepare("SELECT * FROM {$table_name} WHERE id = %d LIMIT 1", $edit_id),
                  ARRAY_A
                );
              }
            }
          }
        }
      }
    }
  }

  $default_cust_name       = isset($existing['cust_name']) ? (string) $existing['cust_name'] : '';
  $default_title           = isset($existing['title']) ? (string) $existing['title'] : '';
  $default_document_number = isset($existing['document_number']) ? (string) $existing['document_number'] : '';
  $default_category_id     = isset($existing['category_id']) ? absint($existing['category_id']) : 0;
  $current_pdf_url         = isset($existing['pdf_url']) ? (string) $existing['pdf_url'] : '';
  $view_post_url           = !empty($existing['post_id']) ? get_permalink((int)$existing['post_id']) : '';

  ob_start();
  ?>
  <div class="kaya-up">
    <div class="kaya-up-shell">
      <?php echo $flash; ?>

      <div class="kaya-up-card">
        <form method="post" enctype="multipart/form-data" id="kayaPdfEditForm">
          <?php wp_nonce_field('kaya_pdf_edit_action', 'kaya_pdf_edit_nonce'); ?>
          <input type="hidden" name="edit_id" value="<?php echo esc_attr($edit_id); ?>">

          <div class="kaya-up-top">
            <div class="kaya-up-field">
              <label>Customer Name</label>
              <input type="text" name="cust_name" value="<?php echo esc_attr($default_cust_name); ?>" placeholder="Enter customer name" required>
            </div>

            <div class="kaya-up-field">
              <label>Title</label>
              <input type="text" name="title" value="<?php echo esc_attr($default_title); ?>" placeholder="Enter document title" required>
            </div>
          </divm�]/K]b,����������r
�?�/**
 * FRONTEND PDF EDIT SHORTCODE FOR INVOICE PAGE
 * Shortcode: [pdf_frontend_edit]
 *
 * - Edits an existing invoice/document row using ?edit_id=ID
 * - Updates wp_kaya_certificates and related WP post
 * - PDF upload is optional; if not selected, old PDF is kept
 * - If new PDF is uploaded, existing filename is reused so URL stays unchanged
 * - Success popup contains custom "View Page" and "Open PDF" buttons
 * - Today Date field removed from edit form; existing created date is preserved
 * - FIELDS LOCKED: Customer Name, Title, Category, Document Number (only PDF can be replaced)
 */

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

/** =========================
 * SETTINGS
 * ========================= */
if (!defined('KAYA_INV_SHOW_FILE_URL')) {
  define('KAYA_INV_SHOW_FILE_URL', true);
}
if (!defined('KAYA_INV_QR_FILENAME_PREFIX')) {
  define('KAYA_INV_QR_FILENAME_PREFIX', 'QR-');
}

/** =========================
 * HELPERS
 * ========================= */
if (!function_exists('kaya_webstation_certificates_table_exists')) {
  function kaya_webstation_certificates_table_exists() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'kaya_certificates';

    $found = $wpdb->get_var($wpdb->prepare(
      "SHOW TABLES LIKE %s",
      $table_name
    ));

    return ($found === $table_name);
  }
}

if (!function_exists('kaya_cert_get_existing_pdf_filename')) {
  function kaya_cert_get_existing_pdf_filename($pdf_url) {
    $path = wp_parse_url($pdf_url, PHP_URL_PATH);
    if (!$path) return '';
    return basename($path);
  }
}

/** =========================
 * SHORTCODE
 * ========================= */
function frontend_pdf_editor_kaya_qr_invoice() {

  if (!is_user_logged_in()) {
    return '<div class="kaya-up-alert kaya-up-alert--warn">Please login to edit document.</div>';
  }

  $current_user = wp_get_current_user();

  if (!array_intersect(['administrator','editor'], (array) $current_user->roles)) {
    return '<div class="kaya-up-alert kaya-up-alert--err">Only administrators or editors can edit documents.</div>';
  }

  if (!kaya_webstation_certificates_table_exists()) {
    return '<div class="kaya-up-alert kaya-up-alert--err">Certificate table is missing. Please enable the table setup snippet first.</div>';
  }

  global $wpdb;
  $table_name = $wpdb->prefix . 'kaya_certificates';

  $flash = '';
  $success_popup = null;

  $BASE_REL = 'FILES';
  $max_mb_text = '100 MB';

  $edit_id = absint($_GET['edit_id'] ?? 0);
  if ($edit_id <= 0) {
    return '<div class="kaya-up-alert kaya-up-alert--err">Missing or invalid edit_id.</div>';
  }

  $existing = $wpdb->get_row(
    $wpdb->prepare("SELECT * FROM {$table_name} WHERE id = %d LIMIT 1", $edit_id),
    ARRAY_A
  );

  if (!$existing) {
    return '<div class="kaya-up-alert kaya-up-alert--err">Document record not found.</div>';
  }

  $post_id_existing = isset($existing['post_id']) ? absint($existing['post_id']) : 0;
  $post_existing = $post_id_existing ? get_post($post_id_existing) : null;

  // ------------------------------------------------------------------------
  // LOCKED FIELDS: always use existing DB values, ignore POST
  // ------------------------------------------------------------------------
  if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['kaya_pdf_edit_nonce']) &&
    wp_verify_nonce($_POST['kaya_pdf_edit_nonce'], 'kaya_pdf_edit_action')
  ) {
    // Force existing values
    $cust_name       = isset($existing['cust_name']) ? sanitize_text_field($existing['cust_name']) : '';
    $document_number = isset($existing['document_number']) ? sanitize_text_field($existing['document_number']) : '';
    $title           = isset($existing['title']) ? sanitize_text_field($existing['title']) : '';
    $category_id     = isset($existing['category_id']) ? absint($existing['category_id']) : 0;
    $category        = get_term($category_id, 'category');

    if ($cust_name === '') {
      $flash = '<div class="kaya-up-alert kaya-up-alert--err">Customer Name is missing on existing record.</div>';
    } elseif ($document_number === '') {
      $flash = '<div class="kaya-up-alert kaya-up-alert--err">Document Number is missing on existing record.</div>';
    } elseif ($title === '') {
      $flash = '<div class="kaya-up-alert kaya-up-alert--err">Title is missing on existing record.</div>';
    } elseif (!$category || is_wp_error($category)) {
      $flash = '<div class="kaya-up-alert kaya-up-alert--err">Invalid existing category.</div>';
    } else {
      $slug = sanitize_title($category->slug);

      if ($slug === '') {
        $flash = '<div class="kaya-up-alert kaya-up-alert--err">Category slug is empty.</div>';
      } else {
        $folder_name = strtoupper($slug);

        $target_dir = rtrim(ABSPATH, '/\\') . DIRECTORY_SEPARATOR
                    . trim($BASE_REL, '/\\') . DIRECTORY_SEPARATOR
                    . $folder_name . DIRECTORY_SEPARATOR;

        $base_url = home_url('/' . trim($BASE_REL, '/\\') . '/' . $folder_name . '/');

        if (!is_dir($target_dir)) {
          $flash = '<div class="kaya-up-alert kaya-up-alert--err"><b>Folder does not exist</b><div class="kaya-up-small">'
                 . esc_html($target_dir) . '</div></div>';
        } elseif (!is_writable($target_dir)) {
          $flash = '<div class="kaya-up-alert kaya-up-alert--err"><b>Folder not writable</b><div class="kaya-up-small">'
                 . esc_html($target_dir) . '</div></div>';
        } else {
          $pdf_url = isset($existing['pdf_url']) ? (string) $existing['pdf_url'] : '';
          $new_file_uploaded = !empty($_FILES['pdf_file']['name']);
          $created_date = !empty($existing['today_date']) ? (string) $existing['today_date'] : '';

          if ($new_file_uploaded) {
            $file  = $_FILES['pdf_file'];
            $check = wp_check_filetype_and_ext($file['tmp_name'], $file['name']);
            $ext   = strtolower((string)($check['ext'] ?? ''));

            if ($ext !== 'pdf') {
              $flash = '<div class="kaya-up-alert kaya-up-alert--err">Only PDF allowed.</div>';
            } else {
              $old_pdf_url  = isset($existing['pdf_url']) ? (string) $existing['pdf_url'] : '';
              $old_filename = kaya_cert_get_existing_pdf_filename($old_pdf_url);

              if ($old_filename === '') {
                $flash = '<div class="kaya-up-alert kaya-up-alert--err">Existing PDF filename could not be detected.</div>';
              } else {
                $target_path = $target_dir . $old_filename;

                if (is_file($target_path)) {
                  @unlink($target_path);
                }

                if (!@move_uploaded_file($file['tmp_name'], $target_path)) {
                  $err = error_get_last();
                  $flash  = '<div class="kaya-up-alert kaya-up-alert--err"><b>Upload failed while replacing file</b>.</div>';
                  $flash .= '<div class="kaya-up-debug"><b>Target:</b> ' . esc_html($target_path) . '<br><pre>'
                          . esc_html(print_r($err, true)) . '</pre></div>';
                } else {
                  $pdf_url = $old_pdf_url;
                }
              }
            }
          }

          if ($flash === '') {
            $row_title = $title;

            $qr_view_id  = 'kaya-qr-view-' . wp_generate_password(8, false, false);
            $qr_print_id = 'kaya-qr-print-' . wp_generate_password(8, false, false);

            $qepw = '[qepw_pdf_viewer file="' . esc_url($pdf_url) . '"]';

            $kaya_qr = '
              <div class="kaya-qr-download-wrap kaya-webstation-qr" id="' . esc_attr($qr_view_id) . '">
                <div class="kaya-webstation-company">WEBSTATION COMPUTER CENTRE</div>
                <div class="kaya-webstation-phone-main">1700 822 922</div>
                <div class="kaya-webstation-contact">TEL: 05-2822919 FAX: 05-2811919 H/Phone: 016-550 8505</div>
                <div class="kaya-webstation-contact">E-mail: sales@webstation.my</div>

                <div class="kaya-webstation-customer">' . esc_html($cust_name) . '</div>
                <div class="kaya-webstation-docno">' . esc_html($document_number) . '</div>

                <div class="kaya-qr-download-inner">
                  [kaya_qrcode content="' . esc_url($pdf_url) . '" dynamic_content="0" download_button="0" download_align="aligncenter"]
                </div>
              </div>

              <div class="kaya-qr-print-template" aria-hidden="true">
                <div class="kaya-webstation-print" id="' . esc_attr($qr_print_id) . '">

                  <div class="kaya-webstation-print-top">
                    <div class="kaya-webstation-print-left">
                      <div class="kaya-webstation-print-company">WEBSTATION</div>
                      <div class="kaya-webstation-print-branch">COMPUTER CENTRE</div>
                      <div class="kaya-webstation-print-phone">1700 822 922</div>

                      <div class="kaya-webstation-print-customer">' . esc_html($cust_name) . '</div>
                      <div class="kaya-webstation-print-docno">' . esc_html($document_number) . '</div>

                      <div class="kaya-webstation-print-contact">TEL: 05-2822919</div>
                      <div class="kaya-webstation-print-contact">FAX: 05-2811919</div>
                      <div class="kaya-webstation-print-contact">H/P: 016-550 8505</div>
                    </div>

                    <div class="kaya-webstation-print-right">
                      <div class="kaya-qr-download-inner">
                        [kaya_qrcode content="' . esc_url($pdf_url) . '" dynamic_content="0" size="440" download_button="0" download_align="aligncenter"]
                      </div>
                    </div>
                  </div>

                  <div class="kaya-webstation-print-email">
                    E-mail: sales@webstation.my
                  </div>

                </div>
              </div>

              <div class="kaya-qr-download-actions">
                <button type="button"
                        class="kaya-up-btn kaya-up-btn--primary kaya-download-qr-btn"
                        data-target="' . esc_attr($qr_print_id) . '"
                        data-filename="' . esc_attr(sanitize_file_name($document_number . '-' . $title)) . '-qr.png">
                  Download QR Image
                </button>
              </div>
            ';

            $content = '<div class="kaya-inv-page kaya-inv-page--webstation">' .
              '<div class="kaya-inv-viewer kaya-inv-viewer--qepw">' .
                $qepw .
              '</div>' .
              '<div class="kaya-inv-qr kaya-inv-qr--kaya">' .
                '<div class="kaya-inv-qrbox">' .
                  $kaya_qr .
                '</div>';

            $content .= '<div class="kaya-inv-meta">' .
                          '<div class="kaya-inv-label">Customer Name</div>' .
                          '<div class="kaya-inv-text">' . esc_html($cust_name) . '</div>' .
                        '</div>';

            $content .= '<div class="kaya-inv-meta">' .
                          '<div class="kaya-inv-label">Document Number</div>' .
                          '<div class="kaya-inv-text">' . esc_html($document_number) . '</div>' .
                        '</div>';

            $content .= '<div class="kaya-inv-meta">' .
                          '<div class="kaya-inv-label">Title</div>' .
                          '<div class="kaya-inv-text">' . esc_html($title) . '</div>' .
                        '</div>';

            if (KAYA_INV_SHOW_FILE_URL) {
              $content .= '<div class="kaya-inv-meta">' .
                            '<div class="kaya-inv-label">File URL</div>' .
                            '<div class="kaya-inv-url">' . esc_html($pdf_url) . '</div>' .
                          '</div>';
            }

            if ($created_date !== '') {
              $content .= '<div class="kaya-inv-meta">' .
                            '<div class="kaya-inv-label">Created Date</div>' .
                            '<div class="kaya-inv-text">' . esc_html($created_date) . '</div>' .
                          '</div>';
            }

            $content .= '</div></div>';

            $post_result = false;

            if ($post_existing) {
              $post_result = wp_update_post([
                'ID'            => $post_id_existing,
                'post_title'    => $row_title,
                'post_content'  => $content,
                'post_category' => [$category_id],
              ], true);
            } else {
              $post_result = wp_insert_post([
                'post_title'    => $row_title,
                'post_content'  => $content,
                'post_status'   => 'publish',
                'post_type'     => 'post',
                'post_category' => [$category_id],
                'post_author'   => get_current_user_id()
              ], true);

              if (!is_wp_error($post_result)) {
                $post_id_existing = (int) $post_result;
              }
            }

            if (is_wp_error($post_result)) {
              $flash = '<div class="kaya-up-alert kaya-up-alert--err">Post update failed: '
                     . esc_html($post_result->get_error_message()) . '</div>';
            } else {
              $updated = $wpdb->update(
                $table_name,
                [
                  'post_id'         => $post_id_existing,
                  'document_number' => $document_number,
                  'cust_name'       => $cust_name,
                  'title'           => $title,
                  'category_id'     => $category_id,
                  'category_slug'   => $slug,
                  'pdf_url'         => esc_url_raw($pdf_url),
                ],
                ['id' => $edit_id],
                ['%d','%s','%s','%s','%d','%s','%s'],
                ['%d']
              );

              if ($updated === false) {
                $flash = '<div class="kaya-up-alert kaya-up-alert--err"><b>Post updated but DB update failed.</b><div class="kaya-up-small">'
                       . esc_html($wpdb->last_error) . '</div></div>';
              } else {
                update_post_meta($post_id_existing, '_kaya_invoice_post', 1);
                update_post_meta($post_id_existing, '_kaya_invoice_pdf_url', esc_url_raw($pdf_url));
                update_post_meta($post_id_existing, '_kaya_cust_name', $cust_name);
                update_post_meta($post_id_existing, '_kaya_document_number', $document_number);
                update_post_meta($post_id_existing, '_kaya_title', $title);
                update_post_meta($post_id_existing, '_kaya_cert_row_id', $edit_id);

                $success_popup = [
                  'title'    => 'Update Successful!',
                  'text'     => 'Document has been updated successfully.',
                  'view_url' => get_permalink($post_id_existing),
                  'pdf_url'  => $pdf_url,
                ];

                $existing = $wpdb->get_row(
                  $wpdb->prepare("SELECT * FROM {$table_name} WHERE id = %d LIMIT 1", $edit_id),
                  ARRAY_A
                );
              }
            }
          }
        }
      }
    }
  }

  $default_cust_name       = isset($existing['cust_name']) ? (string) $existing['cust_name'] : '';
  $default_title           = isset($existing['title']) ? (string) $existing['title'] : '';
  $default_document_number = isset($existing['document_number']) ? (string) $existing['document_number'] : '';
  $default_category_id     = isset($existing['category_id']) ? absint($existing['category_id']) : 0;
  $current_pdf_url         = isset($existing['pdf_url']) ? (string) $existing['pdf_url'] : '';
  $view_post_url           = !empty($existing['post_id']) ? get_permalink((int)$existing['post_id']) : '';

  ob_start();
  ?>
  <div class="kaya-up">
    <div class="kaya-up-shell">
      <?php echo $flash; ?>

      <div class="kaya-up-card">
        <form method="post" enctype="multipart/form-data" id="kayaPdfEditForm">
          <?php wp_nonce_field('kaya_pdf_edit_action', 'kaya_pdf_edit_nonce'); ?>
          <input type="hidden" name="edit_id" value="<?php echo esc_attr($edit_id); ?>">

          <!-- LOCKED FIELDS: read��r��m��������m�]/
�"f����>

          <div class="kaya-up-top">
            <div class="kaya-up-field">
              <label>Category</label>
              <select name="post_category" id="kayaPostCategory" required>
                <?php
                $categories = get_terms([
                  'taxonomy'   => 'category',
                  'hide_empty' => false
                ]);
                if (!is_wp_error($categories) && $categories) {
                  foreach ($categories as $cat) {
                    echo '<option value="' . esc_attr($cat->term_id) . '" data-cat-name="' . esc_attr($cat->name) . '" ' . selected($default_category_id, $cat->term_id, false) . '>' . esc_html($cat->name) . '</option>';
                  }
                }
                ?>
              </select>
            </div>

            <div class="kaya-up-field">
              <label id="kayaDocumentNumberLabel">Document Number</label>
              <input
                type="text"
                name="document_number"
                id="kayaDocumentNumberInput"
                value="<?php echo esc_attr($default_document_number); ?>"
                placeholder="Enter document number"
                required
              >
            </div>
          </div>

          <?php if ($current_pdf_url): ?>
          <div class="kaya-up-alert kaya-up-alert--warn" style="margin-bottom:14px;">
            Current PDF:
            <a href="<?php echo esc_url($current_pdf_url); ?>" target="_blank" rel="noopener">Open current PDF</a>
            <?php if ($view_post_url): ?>
              | <a href="<?php echo esc_url($view_post_url); ?>" target="_blank" rel="noopener">View current page</a>
            <?php endif; ?>
          </div>
          <?php endif; ?>

          <div class="kaya-up-drop" id="kayaDrop">
            <div class="kaya-up-illu" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                <path d="M14 2v6h6"/>
                <path d="M12 18v-6"/>
                <path d="M9.5 14.5 12 12l2.5 2.5"/>
              </svg>
            </div>

            <div class="kaya-up-title">Replace PDF (optional)</div>
            <div class="kaya-up-or">or keep current file</div>

            <button type="button" class="kaya-up-btn kaya-up-btn--primary" id="kayaPickBtn">
              Upload New PDF
            </button>

            <div class="kaya-up-note">PDF up to <?php echo esc_html($max_mb_text); ?></div>

            <div class="kaya-up-filehint" id="kayaFileHint" style="display:none;">
              <span>Selected:</span> <b id="kayaFileName"></b>
            </div>

            <input type="file" name="pdf_file" accept="application/pdf" id="kayaFileInput">
          </div>

          <div style="margin-top:14px; display:flex; justify-content:center;">
            <button type="submit" class="kaya-up-btn kaya-up-btn--primary" style="min-width:320px;">
              Save Changes
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

  <script>
  (function() {
    document.addEventListener('DOMContentLoaded', function() {
      const drop = document.getElementById('kayaDrop');
      const fileInput = document.getElementById('kayaFileInput');
      const pickBtn = document.getElementById('kayaPickBtn');
      const hint = document.getElementById('kayaFileHint');
      const nameEl = document.getElementById('kayaFileName');

      const categorySelect = document.getElementById('kayaPostCategory');
      const docLabel = document.getElementById('kayaDocumentNumberLabel');
      const docInput = document.getElementById('kayaDocumentNumberInput');

      function updateDocumentNumberLabel() {
        if (!categorySelect || !docLabel || !docInput) return;

        const selectedOption = categorySelect.options[categorySelect.selectedIndex];
        const catName = selectedOption ? (selectedOption.getAttribute('data-cat-name') || selectedOption.text || '') : '';
        const cleanName = String(catName).trim();

        if (cleanName) {
          docLabel.textContent = cleanName + ' Number';
          docInput.placeholder = 'Enter ' + cleanName.toLowerCase() + ' number';
        } else {
          docLabel.textContent = 'Document Number';
          docInput.placeholder = 'Enter document number';
        }
      }

      if (categorySelect) {
        categorySelect.addEventListener('change', updateDocumentNumberLabel);
        updateDocumentNumberLabel();
      }

      if (drop && fileInput) {
        function showFileName() {
          const f = fileInput.files && fileInput.files[0];
          if (!f) {
            if (hint) hint.style.display = 'none';
            return;
          }
          if (hint) hint.style.display = 'block';
          if (nameEl) nameEl.textContent = f.name;
        }

        if (pickBtn) {
          pickBtn.addEventListener('click', function(e) {
            e.preventDefault();
            fileInput.click();
          });
        }

        fileInput.addEventListener('change', showFileName);

        ['dragenter','dragover'].forEach(function(evt) {
          drop.addEventListener(evt, function(e) {
            e.preventDefault();
            e.stopPropagation();
            drop.classList.add('is-drag');
          });
        });

        ['dragleave','drop'].forEach(function(evt) {
          drop.addEventListener(evt, function(e) {
            e.preventDefault();
            e.stopPropagation();
            drop.classList.remove('is-drag');
          });
        });

        drop.addEventListener('drop', function(e) {
          if (!e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files.length) return;
          fileInput.files = e.dataTransfer.files;
          showFileName();
        });
      }

      document.addEventListener('click', function(e) {
        const btn = e.target.closest('.kaya-download-qr-btn');
        if (!btn) return;

        const targetId = btn.getAttribute('data-target');
        const filename = btn.getAttribute('data-filename') || 'qr-image.png';
        const box = document.getElementById(targetId);

        if (!box || typeof html2canvas === 'undefined') {
          alert('QR image downloader is not ready.');
          return;
        }

        html2canvas(box, {
          backgroundColor: '#ffffff',
          scale: 2,
          useCORS: true
        }).then(function(canvas) {
          const link = document.createElement('a');
          link.download = filename;
          link.href = canvas.toDataURL('image/png');
          link.click();
        }).catch(function(err) {
          console.error(err);
          alert('Failed to download QR image.');
        });
      });
    });
  })();
  </script>

  <?php if (!empty($success_popup)) : ?>
  <script>
  document.addEventListener('DOMContentLoaded', function () {
    Swal.fire({
      icon: 'success',
      title: <?php echo wp_json_encode($success_popup['title']); ?>,
      html: `
        <div style="margin-bottom:14px;">
          <?php echo esc_js($success_popup['text']); ?>
        </div>
        <div style="display:flex; gap:10px; justify-content:center; flex-wrap:wrap;">
          <button type="button" id="swal-view-page-btn" class="swal2-styled" style="margin:0;">
            View Page
          </button>
          <button type="button" id="swal-open-pdf-btn" class="swal2-styled" style="margin:0; background:#6b7280;">
            Open PDF
          </button>
        </div>
      `,
      confirmButtonText: 'Close',
      allowOutsideClick: false,
      allowEscapeKey: false,
      allowEnterKey: false,
      showCloseButton: false,
      didOpen: function () {
        var viewBtn = document.getElementById('swal-view-page-btn');
        var pdfBtn  = document.getElementById('swal-open-pdf-btn');

        if (viewBtn) {
          viewBtn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            window.open(<?php echo wp_json_encode($success_popup['view_url']); ?>, '_blank');
          });
        }

        if (pdfBtn) {
          pdfBtn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            window.open(<?php echo wp_json_encode($success_popup['pdf_url']); ?>, '_blank');
          });
        }
      }
    });
  });
  </script>
  <?php endif; ?>

  <?php
  return ob_get_clean();
}
add_shortcode('pdf_frontend_edit', 'frontend_pdf_editor_kaya_qr_invoice');m�]/�
r2����������r
�'&����only / disabled, but we keep the same name attributes for reference -->
          <div class="kaya-up-top">
            <div class="kaya-up-field">
              <label>Customer Name</label>
              <input
                type="text"
                name="cust_name"
                value="<?php echo esc_attr($default_cust_name); ?>"
                placeholder="Enter customer name"
                readonly
              >
            </div>

            <div class="kaya-up-field">
              <label>Title</label>
              <input
                type="text"
                name="title"
                value="<?php echo esc_attr($default_title); ?>"
                placeholder="Enter document title"
                readonly
              >
            </div>
          </div>

          <div class="kaya-up-top">
            <div class="kaya-up-field">
              <label>Category</label>
              <select name="post_category_display" id="kayaPostCategory" disabled>
                <?php
                $categories = get_terms([
                  'taxonomy'   => 'category',
                  'hide_empty' => false
                ]);
                if (!is_wp_error($categories) && $categories) {
                  foreach ($categories as $cat) {
                    echo '<option value="' . esc_attr($cat->term_id) . '" data-cat-name="' . esc_attr($cat->name) . '" ' . selected($default_category_id, $cat->term_id, false) . '>' . esc_html($cat->name) . '</option>';
                  }
                }
                ?>
              </select>
              <!-- Hidden field to pass actual category ID to backend (though backend ignores POST and uses existing) -->
              <input type="hidden" name="post_category" value="<?php echo esc_attr($default_category_id); ?>">
            </div>

            <div class="kaya-up-field">
              <label id="kayaDocumentNumberLabel">Document Number</label>
              <input
                type="text"
                name="document_number"
                id="kayaDocumentNumberInput"
                value="<?php echo esc_attr($default_document_number); ?>"
                placeholder="Enter document number"
                readonly
              >
            </div>
          </div>

          <?php if ($current_pdf_url): ?>
          <div class="kaya-up-alert kaya-up-alert--warn" style="margin-bottom:14px;">
            Current PDF:
            <a href="<?php echo esc_url($current_pdf_url); ?>" target="_blank" rel="noopener">Open current PDF</a>
            <?php if ($view_post_url): ?>
              | <a href="<?php echo esc_url($view_post_url); ?>" target="_blank" rel="noopener">View current page</a>
            <?php endif; ?>
          </div>
          <?php endif; ?>

          <div class="kaya-up-drop" id="kayaDrop">
            <div class="kaya-up-illu" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                <path d="M14 2v6h6"/>
                <path d="M12 18v-6"/>
                <path d="M9.5 14.5 12 12l2.5 2.5"/>
              </svg>
            </div>

            <div class="kaya-up-title">Replace PDF (optional)</div>
            <div class="kaya-up-or">or keep current file</div>

            <button type="button" class="kaya-up-btn kaya-up-btn--primary" id="kayaPickBtn">
              Upload New PDF
            </button>

            <div class="kaya-up-note">PDF up to <?php echo esc_html($max_mb_text); ?></div>

            <div class="kaya-up-filehint" id="kayaFileHint" style="display:none;">
              <span>Selected:</span> <b id="kayaFileName"></b>
            </div>

            <input type="file" name="pdf_file" accept="application/pdf" id="kayaFileInput">
          </div>

          <div style="margin-top:14px; display:flex; justify-content:center;">
            <button type="submit" class="kaya-up-btn kaya-up-btn--primary" style="min-width:320px;">
              Save Changes
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <style>
    .kaya-up input[readonly],
    .kaya-up select:disabled {
      background: #f5f5f5;
      color: #666;
      cursor: not-allowed;
      opacity: 1;
    }
  </style>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

  <script>
  (function() {
    document.addEventListener('DOMContentLoaded', function() {
      const drop = document.getElementById('kayaDrop');
      const fileInput = document.getElementById('kayaFileInput');
      const pickBtn = document.getElementById('kayaPickBtn');
      const hint = document.getElementById('kayaFileHint');
      const nameEl = document.getElementById('kayaFileName');

      const categorySelect = document.getElementById('kayaPostCategory');
      const docLabel = document.getElementById('kayaDocumentNumberLabel');
      const docInput = document.getElementById('kayaDocumentNumberInput');

      function updateDocumentNumberLabel() {
        if (!categorySelect || !docLabel || !docInput) return;

        const selectedOption = categorySelect.options[categorySelect.selectedIndex];
        const catName = selectedOption ? (selectedOption.getAttribute('data-cat-name') || selectedOption.text || '') : '';
        const cleanName = String(catName).trim();

        if (cleanName) {
          docLabel.textContent = cleanName + ' Number';
          docInput.placeholder = 'Enter ' + cleanName.toLowerCase() + ' number';
        } else {
          docLabel.textContent = 'Document Number';
          docInput.placeholder = 'Enter document number';
        }
      }

      if (categorySelect) {
        categorySelect.addEventListener('change', updateDocumentNumberLabel);
        updateDocumentNumberLabel();
      }

      if (drop && fileInput) {
        function showFileName() {
          const f = fileInput.files && fileInput.files[0];
          if (!f) {
            if (hint) hint.style.display = 'none';
            return;
          }
          if (hint) hint.style.display = 'block';
          if (nameEl) nameEl.textContent = f.name;
        }

        if (pickBtn) {
          pickBtn.addEventListener('click', function(e) {
            e.preventDefault();
            fileInput.click();
          });
        }

        fileInput.addEventListener('change', showFileName);

        ['dragenter','dragover'].forEach(function(evt) {
          drop.addEventListener(evt, function(e) {
            e.preventDefault();
            e.stopPropagation();
            drop.classList.add('is-drag');
          });
        });

        ['dragleave','drop'].forEach(function(evt) {
          drop.addEventListener(evt, function(e) {
            e.preventDefault();
            e.stopPropagation();
            drop.classList.remove('is-drag');
          });
        });

        drop.addEventListener('drop', function(e) {
          if (!e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files.length) return;
          fileInput.files = e.dataTransfer.files;
          showFileName();
        });
      }

      document.addEventListener('click', function(e) {
        const btn = e.target.closest('.kaya-download-qr-btn');
        if (!btn) return;

        const targetId = btn.getAttribute('data-target');
        const filename = btn.getAttribute('data-filename') || 'qr-image.png';
        const box = document.getElementById(targetId);

        if (!box || typeof html2canvas === 'undefined') {
          alert('QR image downloader is not ready.');
          return;
        }

        html2canvas(box, {
          backgroundColor: '#ffffff',
          scale: 2,
          useCORS: true
        }).then(function(canvas) {
          const link = document.createElement('a');
          link.download = filename;
          link.href = canvas.toDataURL('image/png');
          link.click();
        }).catch(function(err) {
          console.error(err);
          alert('Failed to download QR image.');
        });
      });
    });
  })();
  </script>

  <?php if (!empty($success_popup)) : ?>
  <script>
  document.addEventListener('DOMContentLoaded', function () {
    Swal.fire({
      icon: 'success',
      title: <?php echo wp_json_encode($success_popup['title']); ?>,
      html: `
        <div style="margin-bottom:14px;">
          <?php echo esc_js($success_popup['text']); ?>
        </div>
        <div style="display:flex; gap:10px; justify-content:center; flex-wrap:wrap;">
          <button type="button" id="swal-view-page-btn" class="swal2-styled" style="margin:0;">
            View Page
          </button>
          <button type="button" id="swal-open-pdf-btn" class="swal2-styled" style="margin:0; background:#6b7280;">
            Open PDF
          </button>
        </div>
      `,
      confirmButtonText: 'Close',
      allowOutsideClick: false,
      allowEscapeKey: false,
      allowEnterKey: false,
      showCloseButton: false,
      didOpen: function () {
        var viewBtn = document.getElementById('swal-view-page-btn');
        var pdfBtn  = document.getElementById('swal-open-pdf-btn');

        if (viewBtn) {
          viewBtn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            window.open(<?php echo wp_json_encode($success_popup['view_url']); ?>, '_blank');
          });
        }

        if (pdfBtn) {
          pdfBtn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            window.open(<?php echo wp_json_encode($success_popup['pdf_url']); ?>, '_blank');
          });
        }
      }
    });
  });
  </script>
  <?php endif; ?>

  <?php
  return ob_get_clean();
}
add_shortcode('pdf_frontend_edit', 'frontend_pdf_editor_kaya_qr_invoice');��r��
A���������~��
�?�
/**
 * FRONTEND PDF UPLOAD -> Create Post with PDF Viewer + QR + Store Record In Custom Table
 * Shortcode: [pdf_frontend_upload]
 *
 * NEW WEBSITE VERSION
 * - Runtime only
 * - No create-table logic inside shortcode
 * - Form asks: Customer Name, Title, Document Number, Category
 * - QR block shows Webstation info + customer name/title
 * - Soft delete support with is_active
 * - Success popup uses SweetAlert2 like Weldmaster
 */

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

/** =========================
 * SETTINGS
 * ========================= */
if (!defined('KAYA_INV_SHOW_FILE_URL')) {
  define('KAYA_INV_SHOW_FILE_URL', true);
}
if (!defined('KAYA_INV_QR_FILENAME_PREFIX')) {
  define('KAYA_INV_QR_FILENAME_PREFIX', 'QR-');
}

/** =========================
 * HELPERS
 * ========================= */
if (!function_exists('kaya_webstation_swal_notice')) {
  function kaya_webstation_swal_notice($icon, $title, $html = '') {
    ob_start(); ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
      document.addEventListener('DOMContentLoaded', function () {
        Swal.fire({
          icon: <?php echo wp_json_encode($icon); ?>,
          title: <?php echo wp_json_encode($title); ?>,
          html: <?php echo wp_json_encode($html); ?>,
          confirmButtonText: 'OK'
        });
      });
    </script>
    <?php
    return ob_get_clean();
  }
}

if (!function_exists('kaya_webstation_build_pdf_filename')) {
  function kaya_webstation_build_pdf_filename($cust_name, $document_number, $target_dir) {
    $customer_slug = sanitize_title($cust_name);
    $crm_slug      = sanitize_title($document_number);

    $base_filename = trim($customer_slug . '-' . $crm_slug, '-');

    if ($base_filename === '') {
      $base_filename = 'document';
    }

    // safer: if same filename already exists, WP will make -1, -2, etc.
    return wp_unique_filename($target_dir, $base_filename . '.pdf');
  }
}

/** =========================
 * OPTIONAL TABLE CHECK
 * ========================= */
if (!function_exists('kaya_webstation_certificates_table_exists')) {
  function kaya_webstation_certificates_table_exists() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'kaya_certificates';

    $found = $wpdb->get_var($wpdb->prepare(
      "SHOW TABLES LIKE %s",
      $table_name
    ));

    return ($found === $table_name);
  }
}

/** Add CSS class to generated posts */
add_filter('post_class', function($classes, $class, $post_id){
  if (get_post_meta($post_id, '_kaya_invoice_post', true)) {
    $classes[] = 'kaya-invoice-post';
    $classes[] = 'kaya-invoice-post--webstation';
  }
  return $classes;
}, 10, 3);

/** =========================
 * ASSETS FOR GENERATED POSTS (viewer page)
 * ========================= */
add_action('wp_enqueue_scripts', function () {
  if (is_admin() || !is_singular('post')) return;

  $post_id = get_queried_object_id();
  if (!$post_id || !get_post_meta($post_id, '_kaya_invoice_post', true)) return;

  wp_enqueue_script(
    'html2canvas',
    'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js',
    array(),
    '1.4.1',
    true
  );

  wp_enqueue_script(
    'sweetalert2',
    'https://cdn.jsdelivr.net/npm/sweetalert2@11',
    array(),
    '11',
    true
  );
});

add_action('wp_footer', function () {
  if (is_admin() || !is_singular('post')) return;

  $post_id = get_queried_object_id();
  if (!$post_id || !get_post_meta($post_id, '_kaya_invoice_post', true)) return;
  ?>
  <style>
    .kaya-doc-page{
      max-width:82rem;
      margin:0 auto;
      padding:1rem 0 0;
    }

    .kaya-doc-row{
      display:grid;
      grid-template-columns:minmax(0, 1.9fr) minmax(18rem, .9fr);
      gap:1.25rem;
      align-items:start;
      margin-bottom:1.25rem;
    }

    .kaya-doc-details-wrap{
      width:100%;
    }

    .kaya-doc-card{
      background:#fff;
      border:1px solid #e3eaf3;
      border-radius:1.25rem;
      box-shadow:0 .8rem 2rem rgba(15,23,42,.06);
      padding:1.15rem;
    }

    .kaya-doc-card--viewer{
      padding:.9rem;
    }

    .kaya-doc-card-title{
      margin:0 0 .9rem;
      color:#172033;
      font-size:1rem;
      font-weight:800;
    }

    .kaya-doc-viewer{
      border-radius:1rem;
      overflow:hidden;
      background:#f7f9fc;
    }

    .kaya-doc-viewer > *{
      width:100%;
    }

    .kaya-doc-qr-preview{
      display:grid;
      justify-items:center;
      gap:.75rem;
      text-align:center;
      padding:.25rem 0;
    }

    .kaya-doc-qr-brand{
      color:#172033;
      font-size:1.08rem;
      font-weight:800;
      line-height:1.2;
    }

    .kaya-doc-qr-customer{
      color:#172033;
      font-size:1rem;
      font-weight:700;
    }

    .kaya-doc-qr-docno{
      color:#1f5fae;
      font-size:1rem;
      font-weight:800;
    }

    .kaya-doc-qr-meta{
      color:#5b667a;
      font-size:.85rem;
      line-height:1.5;
    }

    .kaya-doc-qr-code img,
    .kaya-doc-qr-code canvas,
    .kaya-doc-qr-code svg{
      width:min(100%, 15rem) !important;
      height:auto !important;
      display:block;
      margin:0 auto;
    }

    .kaya-doc-qr-actions{
      margin-top:1rem;
      display:flex;
      justify-content:center;
    }

    .kaya-doc-btn{
      display:inline-flex;
      align-items:center;
      justify-content:center;
      min-height:2.8rem;
      padding:.8rem 1rem;
      border:none;
      border-radius:.9rem;
      font-size:.95rem;
      font-weight:700;
      text-decoration:none;
      cursor:pointer;
      transition:transform .18s ease, box-shadow .18s ease, background .18s ease;
    }

    .kaya-doc-btn:hover{
      transform:translateY(-.05rem);
    }

    .kaya-doc-btn--primary{
      background:#1f5fae;
      color:#fff;
      box-shadow:0 .6rem 1.2rem rgba(31,95,174,.16);
    }

    .kaya-doc-summary-grid{
      display:grid;
      grid-template-columns:repeat(2, minmax(0, 1fr));
      gap:1rem 1.25rem;
    }

    .kaya-doc-summary-item{
      padding:0 0 .95rem;
      border-bottom:1px solid #edf2f7;
    }

    .kaya-doc-summary-item--full{
      grid-column:1 / -1;
    }

    .kaya-doc-summary-label{
      margin-bottom:.28rem;
      color:#6a7486;
      font-size:.8rem;
      font-weight:700;
      text-transform:uppercase;
      letter-spacing:.03em;
    }

    .kaya-doc-summary-value{
      color:#172033;
      font-size:.98rem;
      line-height:1.5;
      word-break:break-word;
    }

    .kaya-doc-summary-value--url a{
      color:#1f5fae;
      text-decoration:none;
      word-break:break-word;
    }

    .kaya-doc-summary-value--url a:hover{
      text-decoration:underline;
    }

    .kaya-qr-print-template{
      position:fixed;
      left:-9999rem;
      top:0;
      pointer-events:none;
      z-index:-1;
    }

    @media (max-width: 64rem){
      .kaya-doc-row{
        grid-template-columns:1fr;
      }

      .kaya-doc-summary-grid{
        grid-template-columns:1fr;
      }

      .kaya-doc-summary-item--full{
        grid-column:auto;
      }
    }

    @media (max-width: 40rem){
      .kaya-doc-btn{
        width:100%;
      }
    }
  </style>

  <script>
    (function(){
      // Prevent this script from binding twice
      if (window.kayaQrDownloadScriptBound) return;
      window.kayaQrDownloadScriptBound = true;

      function showSwal(icon, title, text) {
        if (typeof Swal !== 'undefined') {
          Swal.fire({
            icon: icon,
            title: title,
            text: text || '',
            confirmButtonText: 'OK'
          });
          return;
        }
        alert(title + (text ? '\n' + text : ''));
      }

      function bindQrDownloadButtons() {
        var buttons = document.querySelectorAll('.kaya-download-qr-btn');

        buttons.forEach(function(qrBtn){
          if (qrBtn.dataset.bound === '1') return;
          qrBtn.dataset.bound = '1';

          qrBtn.addEventListener('click', function(e){
            e.preventDefault();
            e.stopPropagation();
            if (typeof e.stopImmediatePropagation === 'function') {
              e.stopImmediatePropagation();
            }

            if (qrBtn.dataset.busy === '1') return;
            qrBtn.dataset.busy = '1';
            qrBtn.disabled = true;

            var targetId = qrBtn.getAttribute('data-target');
            var filename = qrBtn.getAttribute('data-filename') || 'qr-image.png';
            var box = document.getElementById(targetId);

            if (!box || typeof html2canvas === 'undefined') {
              qrBtn.dataset.busy = '0';
              qrBtn.disabled = false;
              showSwal('error', 'QR image downloader is not ready.');
              return;
            }

            html2canvas(box, {
              backgroundColor: '#ffffff',
              scale: 2,
              useCORS: true
            }).then(function(canvas){
              var link = document.createElement('a');
              link.download = filename;
              link.href = canvas.toDataURL('image/png');
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);

              if (typeof Swal !== 'undefined') {
                Swal.fire({
                  icon: 'success',
                  title: 'QR image downloaded',
                  timer: 1400,
                  showConfirmButton: false
                });
              }
            }).catch(function(err){
              console.error(err);
              showSwal('error', 'Failed to download QR image.');
            }).finally(function(){
              setTimeout(function(){
                qrBtn.dataset.busy = '0';
                qrBtn.disabled = false;
              }, 800);
            });
          }, true);
        });
      }

      if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', bindQrDownloadButtons);
      } else {
        bindQrDownloadButtons();
      }
    })();
  </script>
  <?php
}, 99);

/** =========================
 * SHORTCODE: PDF Frontend Upload Form
 * ========================= */
function frontend_pdf_uploader_kaya_qr() {

  if (!is_user_logged_in()) {
    return kaya_webstation_swal_notice('warning', 'Please login to upload PDF.');
  }

  $current_user = wp_get_current_user();

  if (!array_intersect(['administrator','editor'], (array) $current_user->roles)) {
    return kaya_webstation_swal_notice('error', 'Only administrators or editors can upload documents.');
  }

  if (!kaya_webstation_certificates_table_exists()) {
    return kaya_webstation_swal_notice(
      'error',
      'Certificate table is missing.',
      'Please enable the table setup snippet first.'
    );
  }

  global $wpdb;
  $table_name = $wpdb->prefix . 'kaya_certificates';

  $popup = null;
  $success_popup = null;

  $BASE_REL = 'FILES';
  $max_mb_text = '100 MB';

  if (
    isset($_POST['submit_pdf'], $_POST['kaya_pdf_upload_nonce']) &&
    wp_verify_nonce($_POST['kaya_pdf_upload_nonce'], 'kaya_pdf_upload_action')
  ) {
    if (empty($_FILES['pdf_file']['name'])) {
      $popup = array(
        'icon'  => 'error',
        'title' => 'Please select a PDF file.',
        'html'  => ''
      );
    } else {
      $cust_name       = sanitize_text_field(wp_unslash($_POST['cust_name'] ?? ''));
      $document_number = sanitize_text_field(wp_unslash($_POST['document_number'] ?? ''));
      $title           = sanitize_text_field(wp_unslash($_POST['title'] ?? ''));
      $category_id     = absint($_POST['post_category'] ?? 0);
      $today_date      = current_time('Y-m-d');
      $category        = get_term($category_id, 'category');

      if ($cust_name === '') {
        $popup = array(
          'icon'  => 'error',
          'title' => 'Please fill in Customer Name.',
          'html'  => ''
        );
      } elseif ($document_number === '') {
        $popup = array(
          'icon'  => 'error',
          'title' => 'Please fill in Document Number.',
          'html'  => ''
        );
      } elseif ($title === '') {
        $popup = array(
          'icon'  => 'error',
          'title' => 'Please fill in Title.',
          'html'  => ''
        );
      } elseif (!$category || is_wp_error($category)) {
        $popup = array(
          'icon'  => 'error',
          'title' => 'Invalid category.',
          'html'  => ''
        );
      } else {
        $slug = sanitize_title($category->slug);

        if ($slug === '') {
          $popup = array(
            'icon'  => 'error',
            'title' => 'Category slug is empty.',
            'html'  => ''
          );
        } else {
          $folder_name = strtoupper($slug);

          $target_dir = rtrim(ABSPATH, '/\\') . DIRECTORY_SEPARATOR
                      . trim($BASE_REL, '/\\') . DIRECTORY_SEPARATOR
                      . $folder_name . DIRECTORY_SEPARATOR;

          $base_url = home_url('/' . trim($BASE_REL, '/\\') . '/' . $folder_name . '/');

          if (!is_dir($target_dir)) {
            $popup = array(
              'icon'  => 'error',
              'title' => 'Folder does not exist',
              'html'  => '<div class="kaya-up-small">' . esc_html($target_dir) . '</div>'
            );
          } elseif (!is_writable($target_dir)) {
            $popup = array(
              'icon'  => 'error',
              'title' => 'Folder not writable',
              'html'  => '<div class="kaya-up-small">' . esc_html($target_dir) . '</div>'
            );
          } else {
            $file  = $_FILES['pdf_file'];
            $check = wp_check_filetype_and_ext($file['tmp_name'], $file['name']);
            $ext   = strtolower((string)($check['ext'] ?? ''));

            if ($ext !== 'pdf') {
              $popup = array(
                'icon'  => 'error',
                'title' => 'Only PDF allowed.',
                'html'  => ''
              );
            } else {
              $filename    = kaya_webstation_build_pdf_filename($cust_name, $document_number, $target_dir);
              $target_path = $target_dir . $filename;

              if (!@move_uploaded_file($file['tmp_name'], $target_path)) {
                $err = error_get_last();
                $popup = array(
                  'icon'  => 'error',
                  'title' => 'Upload failed while moving file',
                  'html'  => '<div class="kaya-up-debug"><b>Target:</b> ' . esc_html($target_path) . '<br><pre>'
                           . esc_html(print_r($err, true)) . '</pre></div>'
                );
              } else {
                $pdf_url   = $base_url . rawurlencode($filename);
                $row_title = $title;

                $qepw = '[qepw_pdf_viewer file="' . esc_url($pdf_url) . '"]';

                // CONTENT BUILDER with compact preview + hidden print template
                $qr_view_id              = 'kaya-qr-view-' . wp_generate_password(8, false, false);
                $qr_print_id             = 'kaya-qr-print-' . wp_generate_password(8, false, false);
                $qr_download_filename    = sanitize_file_name($document_number . '-' . $title) . '-qr.png';
                $category_name           = !empty($category->name) ? $category->name : 'Document';
                $display_document_number = ltrim((string) $document_number, "# \t\n\r\0\x0B");

                ob_start();
                ?>
                <div class="kaya-doc-page">

                  <div class="kaya-doc-row">
                    <section class="kaya-doc-card kaya-doc-card--viewer">
                      <div class="kaya-doc-card-title">Document Preview</div>
                      <div class="kaya-doc-viewer">
                        <?php echo $qepw; ?>
                      </div>
                    </section>

                    <aside class="kaya-doc-card">
                      <div class="kaya-doc-card-title">Quick Access QR</div>

                      <div class="kaya-doc-qr-preview" id="<?php echo esc_attr($qr_view_id); ?>">
                        <div class="kaya-doc-qr-brand">WEBSTATION COMPUTER CENTRE</div>
                        <div class="kaya-doc-qr-customer"><?php echo esc_html($cust_name); ?></div>
                        <div class="kaya-doc-qr-docno">#<?php echo esc_html($display_document_number); ?></div>

                        <div class="kaya-doc-qr-me�~��Z������������~��
�?�ta">
                          TEL: 05-2822919<br>
                          FAX: 05-2811919<br>
                          H/P: 016-550 8505<br>
                          E-mail: sales@webstation.my
                        </div>

                        <div class="kaya-doc-qr-code">
                          <?php echo '[kaya_qrcode content="' . esc_url($pdf_url) . '" dynamic_content="0" size="260" download_button="0" download_align="aligncenter"]'; ?>
                        </div>
                      </div>

                      <div class="kaya-doc-qr-actions">
                        <button
                          type="button"
                          class="kaya-doc-btn kaya-doc-btn--primary kaya-download-qr-btn"
                          data-target="<?php echo esc_attr($qr_print_id); ?>"
                          data-filename="<?php echo esc_attr($qr_download_filename); ?>"
                        >
                          Download QR Image
                        </button>
                      </div>
                    </aside>
                  </div>

                  <div class="kaya-doc-details-wrap">
                    <section class="kaya-doc-card">
                      <div class="kaya-doc-card-title">Document Details</div>

                      <div class="kaya-doc-summary-grid">
                        <div class="kaya-doc-summary-item">
                          <div class="kaya-doc-summary-label">Customer Name</div>
                          <div class="kaya-doc-summary-value"><?php echo esc_html($cust_name); ?></div>
                        </div>

                        <div class="kaya-doc-summary-item">
                          <div class="kaya-doc-summary-label">Document Number</div>
                          <div class="kaya-doc-summary-value">#<?php echo esc_html($display_document_number); ?></div>
                        </div>

                        <div class="kaya-doc-summary-item">
                          <div class="kaya-doc-summary-label">Title</div>
                          <div class="kaya-doc-summary-value"><?php echo esc_html($title); ?></div>
                        </div>

                        <div class="kaya-doc-summary-item">
                          <div class="kaya-doc-summary-label">Category</div>
                          <div class="kaya-doc-summary-value"><?php echo esc_html($category_name); ?></div>
                        </div>

                        <?php if (KAYA_INV_SHOW_FILE_URL) : ?>
                          <div class="kaya-doc-summary-item kaya-doc-summary-item--full">
                            <div class="kaya-doc-summary-label">File URL</div>
                            <div class="kaya-doc-summary-value kaya-doc-summary-value--url">
                              <a href="<?php echo esc_url($pdf_url); ?>" target="_blank" rel="noopener noreferrer">
                                <?php echo esc_html($pdf_url); ?>
                              </a>
                            </div>
                          </div>
                        <?php endif; ?>

                        <div class="kaya-doc-summary-item">
                          <div class="kaya-doc-summary-label">Created Date</div>
                          <div class="kaya-doc-summary-value"><?php echo esc_html($today_date); ?></div>
                        </div>
                      </div>
                    </section>
                  </div>

                  <div class="kaya-qr-print-template" aria-hidden="true">
                    <div class="kaya-webstation-print" id="<?php echo esc_attr($qr_print_id); ?>">
                      <div class="kaya-webstation-print-top">
                        <div class="kaya-webstation-print-left">
                          <div class="kaya-webstation-print-company">WEBSTATION</div>
                          <div class="kaya-webstation-print-branch">COMPUTER CENTRE</div>
                          <div class="kaya-webstation-print-phone">1700 822 922</div>

                          <div class="kaya-webstation-print-customer"><?php echo esc_html($cust_name); ?></div>
                          <div class="kaya-webstation-print-docno">#<?php echo esc_html($display_document_number); ?></div>

                          <div class="kaya-webstation-print-contact">TEL: 05-2822919</div>
                          <div class="kaya-webstation-print-contact">FAX: 05-2811919</div>
                          <div class="kaya-webstation-print-contact">H/P: 016-550 8505</div>
                        </div>

                        <div class="kaya-webstation-print-right">
                          <div class="kaya-qr-download-inner">
                            <?php echo '[kaya_qrcode content="' . esc_url($pdf_url) . '" dynamic_content="0" size="440" download_button="0" download_align="aligncenter"]'; ?>
                          </div>
                        </div>
                      </div>

                      <div class="kaya-webstation-print-email">
                        E-mail: sales@webstation.my
                      </div>
                    </div>
                  </div>

                </div>
                <?php
                $content = ob_get_clean();

                $post_id = wp_insert_post(array(
                  'post_title'    => $row_title,
                  'post_content'  => $content,
                  'post_status'   => 'publish',
                  'post_type'     => 'post',
                  'post_category' => array($category_id),
                  'post_author'   => get_current_user_id()
                ), true);

                if (is_wp_error($post_id)) {
                  $popup = array(
                    'icon'  => 'error',
                    'title' => 'Post creation failed',
                    'html'  => esc_html($post_id->get_error_message())
                  );
                } else {
                  update_post_meta($post_id, '_kaya_invoice_post', 1);
                  update_post_meta($post_id, '_kaya_invoice_pdf_url', esc_url_raw($pdf_url));
                  update_post_meta($post_id, '_kaya_cust_name', $cust_name);
                  update_post_meta($post_id, '_kaya_document_number', $document_number);
                  update_post_meta($post_id, '_kaya_title', $title);
                  update_post_meta($post_id, '_kaya_today_date', $today_date);

                  $inserted = $wpdb->insert(
                    $table_name,
                    array(
                      'post_id'         => $post_id,
                      'document_number' => $document_number,
                      'cust_name'       => $cust_name,
                      'title'           => $title,
                      'category_id'     => $category_id,
                      'category_slug'   => $slug,
                      'pdf_url'         => esc_url_raw($pdf_url),
                      'today_date'      => $today_date,
                      'created_by'      => get_current_user_id(),
                      'is_active'       => 'T',
                    ),
                    array(
                      '%d',
                      '%s',
                      '%s',
                      '%s',
                      '%d',
                      '%s',
                      '%s',
                      '%s',
                      '%d',
                      '%s',
                    )
                  );

                  if ($inserted === false) {
                    $popup = array(
                      'icon'  => 'error',
                      'title' => 'Upload succeeded but DB insert failed.',
                      'html'  => '<div class="kaya-up-small">' . esc_html($wpdb->last_error) . '</div>'
                    );
                  } else {
                    $success_popup = array(
                      'title'    => 'Upload Successful!',
                      'text'     => 'Document has been created successfully.',
                      'view_url' => get_permalink($post_id),
                      'pdf_url'  => $pdf_url,
                    );
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  ob_start();
  ?>
  <div class="kaya-up">
    <div class="kaya-up-shell">
      <div class="kaya-up-card">
        <form method="post" enctype="multipart/form-data">
          <?php wp_nonce_field('kaya_pdf_upload_action', 'kaya_pdf_upload_nonce'); ?>

          <div class="kaya-up-top">
            <div class="kaya-up-field">
              <label>Customer Name</label>
              <input type="text" name="cust_name" placeholder="Enter customer name" required>
            </div>

            <div class="kaya-up-field">
              <label>Title</label>
              <input type="text" name="title" placeholder="Enter document title" required>
            </div>
          </div>

          <div class="kaya-up-top">
            <div class="kaya-up-field">
              <label>Category</label>
              <select name="post_category" id="kayaPostCategory" required>
                <?php
                $categories = get_terms(array(
                  'taxonomy'   => 'category',
                  'hide_empty' => false
                ));
                if (!is_wp_error($categories) && $categories) {
                  foreach ($categories as $cat) {
                    echo '<option value="' . esc_attr($cat->term_id) . '" data-cat-name="' . esc_attr($cat->name) . '">' . esc_html($cat->name) . '</option>';
                  }
                }
                ?>
              </select>
            </div>

            <div class="kaya-up-field">
              <label id="kayaDocumentNumberLabel">Document Number</label>
              <input
                type="text"
                name="document_number"
                id="kayaDocumentNumberInput"
                placeholder="Enter document number"
                required
              >
            </div>
          </div>

          <div class="kaya-up-drop" id="kayaDrop">
            <div class="kaya-up-illu" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                <path d="M14 2v6h6"/>
                <path d="M12 18v-6"/>
                <path d="M9.5 14.5 12 12l2.5 2.5"/>
              </svg>
            </div>

            <div class="kaya-up-title">Drag &amp; drop your file</div>
            <div class="kaya-up-or">or</div>

            <button type="button" class="kaya-up-btn kaya-up-btn--primary" id="kayaPickBtn">
              Upload PDF
            </button>

            <div class="kaya-up-note">PDF up to <?php echo esc_html($max_mb_text); ?></div>

            <div class="kaya-up-filehint" id="kayaFileHint" style="display:none;">
              <span>Selected:</span> <b id="kayaFileName"></b>
            </div>

            <input type="file" name="pdf_file" accept="application/pdf" required id="kayaFileInput">
          </div>

          <div style="margin-top:14px; display:flex; justify-content:center;">
            <button type="submit" name="submit_pdf" class="kaya-up-btn kaya-up-btn--primary" style="min-width:320px;">
              Submit Upload
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

  <script>
  (function(){
    const drop = document.getElementById('kayaDrop');
    const fileInput = document.getElementById('kayaFileInput');
    const pickBtn = document.getElementById('kayaPickBtn');
    const hint = document.getElementById('kayaFileHint');
    const nameEl = document.getElementById('kayaFileName');

    const categorySelect = document.getElementById('kayaPostCategory');
    const docLabel = document.getElementById('kayaDocumentNumberLabel');
    const docInput = document.getElementById('kayaDocumentNumberInput');

    const form = document.querySelector('.kaya-up-card form');
    const custInput = form ? form.querySelector('[name="cust_name"]') : null;
    const titleInput = form ? form.querySelector('[name="title"]') : null;

    function showSwal(icon, title, text = '') {
      if (typeof Swal === 'undefined') {
        alert(title + (text ? '\n' + text : ''));
        return;
      }

      Swal.fire({
        icon: icon,
        title: title,
        text: text,
        confirmButtonText: 'OK'
      });
    }

    function updateDocumentNumberLabel() {
      if (!categorySelect || !docLabel || !docInput) return;

      const selectedOption = categorySelect.options[categorySelect.selectedIndex];
      const catName = selectedOption ? (selectedOption.getAttribute('data-cat-name') || selectedOption.text || '') : '';
      const cleanName = String(catName).trim();

      if (cleanName) {
        docLabel.textContent = cleanName + ' Number';
        docInput.placeholder = 'Enter ' + cleanName.toLowerCase() + ' number';
      } else {
        docLabel.textContent = 'Document Number';
        docInput.placeholder = 'Enter document number';
      }
    }

    if (categorySelect) {
      categorySelect.addEventListener('change', updateDocumentNumberLabel);
      updateDocumentNumberLabel();
    }

    if (drop && fileInput) {
      function showFileName() {
        const f = fileInput.files && fileInput.files[0];
        if (!f) {
          if (hint) hint.style.display = 'none';
          return;
        }
        if (hint) hint.style.display = 'block';
        if (nameEl) nameEl.textContent = f.name;
      }

      if (pickBtn) {
        pickBtn.addEventListener('click', function(e){
          e.preventDefault();
          fileInput.click();
        });
      }

      fileInput.addEventListener('change', function () {
        const f = fileInput.files && fileInput.files[0];
        if (f && !/\.pdf$/i.test(f.name)) {
          fileInput.value = '';
          if (hint) hint.style.display = 'none';
          showSwal('error', 'Only PDF allowed.');
          return;
        }
        showFileName();
      });

      ['dragenter','dragover'].forEach(function(evt){
        drop.addEventListener(evt, function(e){
          e.preventDefault();
          e.stopPropagation();
          drop.classList.add('is-drag');
        });
      });

      ['dragleave','drop'].forEach(function(evt){
        drop.addEventListener(evt, function(e){
          e.preventDefault();
          e.stopPropagation();
          drop.classList.remove('is-drag');
        });
      });

      drop.addEventListener('drop', function(e){
        if (!e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files.length) return;

        const droppedFile = e.dataTransfer.files[0];
        if (!/\.pdf$/i.test(droppedFile.name)) {
          showSwal('error', 'Only PDF allowed.');
          return;
        }

        fileInput.files = e.dataTransfer.files;
        showFileName();
      });
    }

    if (form) {
      form.addEventListener('submit', function(e){
        const custName = custInput ? custInput.value.trim() : '';
        const titleVal = titleInput ? titleInput.value.trim() : '';
        const docNo = docInput ? docInput.value.trim() : '';
        const file = fileInput && fileInput.files ? fileInput.files[0] : null;

        if (!custName) {
          e.preventDefault();
          showSwal('error', 'Please fill in Customer Name.');
          return;
        }

        if (!titleVal) {
          e.preventDefault();
          showSwal('error', 'Please fill in Title.');
          return;
        }

        if (!docNo) {
          e.preventDefault();
          showSwal('error', 'Please fill in Document Number.');
          return;
        }

        if (!file) {
          e.preventDefault();
          showSwal('error', 'Please select a PDF file.');
          return;
        }

        if (!/\.pdf$/i.test(file.name)) {
          e.preventDefault();
          showSwal('error', 'Only PDF allowed.');
          return;
        }
      });
    }

    // QR download handler is only in wp_footer (no duplicate here)
  })();
  <�~��'B߱

Youez - 2016 - github.com/yon3zu
LinuXploit