<?php
namespace DS_Plugin;

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

class Print_Queue {
    protected static function find_designer_page_url() {
        $pages = get_posts([
            'post_type' => 'page',
            'post_status' => 'publish',
            'numberposts' => 200,
        ]);
        foreach ($pages as $p) {
            $content = (string) $p->post_content;
            if (strpos($content, '[design_studio') !== false) {
                $url = get_permalink($p->ID);
                if ($url) return $url;
            }
        }
        return '';
    }

    protected static function designer_url_for_design($design_post_id) {
        $design_post_id = (int) $design_post_id;
        if ($design_post_id <= 0) return '';
        $base = self::find_designer_page_url();
        if (!$base) return '';
        $args = [
            'ds_design' => $design_post_id,
            'ds_embed' => 1,
            '_dsr' => time(),
        ];
        $template_id = (int) get_post_meta($design_post_id, 'template_id', true);
        if ($template_id > 0) $args['ds_template'] = $template_id;
        return add_query_arg($args, $base);
    }

    protected static function zone_png_urls($post_id) {
        $zones_png = get_post_meta($post_id, 'zones_png_urls', true);
        if (!is_array($zones_png)) $zones_png = [];
        $out = [];
        foreach ($zones_png as $zid => $url) {
            $zone_id = sanitize_key((string) $zid);
            $zone_url = is_string($url) ? trim($url) : '';
            if ($zone_id === '' || $zone_url === '') continue;
            $out[$zone_id] = $zone_url;
        }
        return $out;
    }

    protected static function zone_layers_urls($post_id) {
        $zones_layers = get_post_meta($post_id, 'zones_layers_paths', true);
        if (!is_array($zones_layers)) $zones_layers = [];
        $out = [];
        foreach ($zones_layers as $zid => $url) {
            $zone_id = sanitize_key((string) $zid);
            $zone_url = is_string($url) ? trim($url) : '';
            if ($zone_id === '' || $zone_url === '') continue;
            $out[$zone_id] = $zone_url;
        }
        return $out;
    }

    protected static function active_zone_ids($post_id) {
        $zones_used = get_post_meta($post_id, 'zones_used', true);
        $ids = [];
        if (is_array($zones_used)) {
            foreach ($zones_used as $zid) {
                $k = sanitize_key((string) $zid);
                if ($k !== '') $ids[$k] = $k;
            }
        }
        if (!empty($ids)) return array_values($ids);
        $manifest = get_post_meta($post_id, 'zones_manifest', true);
        if (is_array($manifest)) {
            foreach ($manifest as $row) {
                if (!is_array($row) || empty($row['active'])) continue;
                $k = sanitize_key((string) ($row['id'] ?? ''));
                if ($k !== '') $ids[$k] = $k;
            }
        }
        return array_values($ids);
    }

    protected static function zone_meta_map($post_id) {
        $out = [];
        $attrs = get_post_meta($post_id, 'zones_attrs_snapshot', true);
        if (is_array($attrs)) {
            foreach ($attrs as $zid => $row) {
                $zone_id = sanitize_key((string) $zid);
                if ($zone_id === '' || !is_array($row)) continue;
                $out[$zone_id] = [
                    'label' => sanitize_text_field((string) ($row['label'] ?? $zone_id)),
                    'side' => sanitize_key((string) ($row['side'] ?? '')),
                ];
            }
        }
        return $out;
    }

    public static function init() {
        // Submenu under Design Studio
        add_action('admin_menu', [__CLASS__, 'add_submenu']);
        // Columns
        add_filter('manage_ds_design_posts_columns', [__CLASS__, 'columns']);
        add_action('manage_ds_design_posts_custom_column', [__CLASS__, 'render_column'], 10, 2);
        // Views filters
        add_filter('views_edit-ds_design', [__CLASS__, 'views']);
        add_action('pre_get_posts', [__CLASS__, 'filter_query_by_printed']);
        // Bulk actions
        add_filter('bulk_actions-edit-ds_design', [__CLASS__, 'bulk_actions']);
        add_filter('handle_bulk_actions-edit-ds_design', [__CLASS__, 'handle_bulk_actions'], 10, 3);
        add_action('admin_notices', [__CLASS__, 'export_notice']);
        // Row actions
        add_filter('post_row_actions', [__CLASS__, 'row_actions'], 10, 2);
        add_action('admin_action_ds_download_zip', [__CLASS__, 'action_download_zip']);
        add_action('admin_action_ds_mark_printed', [__CLASS__, 'action_mark_printed']);
        add_action('admin_action_ds_mark_unprinted', [__CLASS__, 'action_mark_unprinted']);
        // Metabox quick toggle
        add_action('add_meta_boxes_ds_design', [__CLASS__, 'add_metabox']);
        add_action('add_meta_boxes', [__CLASS__, 'add_design_editor_metabox_global'], 20, 2);
        add_filter('default_hidden_meta_boxes', [__CLASS__, 'unhide_design_editor_metabox'], 10, 2);
        add_action('save_post_ds_design', [__CLASS__, 'save_metabox']);
    }

    public static function add_submenu() {
        add_submenu_page(
            'edit.php?post_type=ds_template',
            __('Print Queue', 'ds'),
            __('Print Queue', 'ds'),
            'edit_posts',
            'edit.php?post_type=ds_design'
        );
    }

    public static function columns($cols) {
        $new = [];
        $new['cb'] = $cols['cb'] ?? '';
        $new['title'] = __('Design', 'ds');
        $new['template'] = __('Template', 'ds');
        $new['assets'] = __('Assets', 'ds');
        $new['order'] = __('Order', 'ds');
        $new['user'] = __('User', 'ds');
        $new['printed'] = __('Printed', 'ds');
        $new['date'] = $cols['date'] ?? __('Date');
        return $new;
    }

    public static function render_column($col, $post_id) {
        if ($col === 'template') {
            $tid = (int) get_post_meta($post_id, 'template_id', true);
            if ($tid) echo esc_html(get_the_title($tid));
        } elseif ($col === 'assets') {
            $png = get_post_meta($post_id, 'png_url', true);
            if ($png) echo '<a href="' . esc_url($png) . '" target="_blank">PNG</a> ';
            $zone_png = self::zone_png_urls($post_id);
            $zone_layers = self::zone_layers_urls($post_id);
            $active = self::active_zone_ids($post_id);
            $zone_meta = self::zone_meta_map($post_id);
            if (!empty($zone_png) || !empty($zone_layers)) {
                echo '<div style="margin-top:6px;font-size:12px;color:#4b5563;">';
                echo esc_html(sprintf(__('Set: %d PNG, %d JSON', 'ds'), count($zone_png), count($zone_layers)));
                if (!empty($active)) {
                    echo '<br><span>' . esc_html(__('Active zones:', 'ds')) . ' ' . esc_html(implode(', ', $active)) . '</span>';
                }
                echo '</div>';
                if (!empty($zone_png)) {
                    echo '<div style="margin-top:4px;max-width:360px;">';
                    foreach ($zone_png as $zid => $url) {
                        $label = isset($zone_meta[$zid]['label']) ? (string) $zone_meta[$zid]['label'] : $zid;
                        $side = isset($zone_meta[$zid]['side']) ? (string) $zone_meta[$zid]['side'] : '';
                        $tag = $side !== '' ? (' | ' . strtoupper($side)) : '';
                        echo '<div><a href="' . esc_url($url) . '" target="_blank">PNG [' . esc_html($label . ' / ' . $zid . $tag) . ']</a></div>';
                    }
                    echo '</div>';
                }
            }
        } elseif ($col === 'order') {
            $oid = (int) get_post_meta($post_id, 'order_id', true);
            if ($oid) {
                $url = admin_url('post.php?post=' . $oid . '&action=edit');
                echo '<a href="' . esc_url($url) . '">#' . intval($oid) . '</a>';
            }
        } elseif ($col === 'user') {
            $uid = (int) get_post_meta($post_id, 'user_id', true);
            if ($uid) {
                $u = get_user_by('id', $uid);
                echo $u ? esc_html($u->user_login) : (int) $uid;
            }
        } elseif ($col === 'printed') {
            $printed = (bool) get_post_meta($post_id, 'printed', true);
            $at = get_post_meta($post_id, 'printed_at', true);
            echo $printed ? '<span style="color:green;">' . __('Yes', 'ds') . '</span>' : '<span style="color:#777;">' . __('No', 'ds') . '</span>';
            if ($printed && $at) echo '<br/><span style="color:#777;">' . esc_html($at) . '</span>';
        }
    }

    public static function views($views) {
        $base = add_query_arg([]);
        $all_url = remove_query_arg('ds_printed', $base);
        $unprinted_url = add_query_arg('ds_printed', '0', $base);
        $printed_url = add_query_arg('ds_printed', '1', $base);

        $counts = self::printed_counts();
        $views['all'] = '<a href="' . esc_url($all_url) . '">' . __('All', 'ds') . '</a>';
        $views['unprinted'] = '<a href="' . esc_url($unprinted_url) . '">' . __('Unprinted', 'ds') . ' <span class="count">(' . intval($counts['unprinted']) . ')</span></a>';
        $views['printed'] = '<a href="' . esc_url($printed_url) . '">' . __('Printed', 'ds') . ' <span class="count">(' . intval($counts['printed']) . ')</span></a>';
        return $views;
    }

    protected static function printed_counts() {
        $printed = new \WP_Query([
            'post_type' => 'ds_design',
            'post_status' => 'publish',
            'posts_per_page' => 1,
            'fields' => 'ids',
            'meta_query' => [['key' => 'printed', 'value' => '1']]
        ]);
        $unprinted = new \WP_Query([
            'post_type' => 'ds_design',
            'post_status' => 'publish',
            'posts_per_page' => 1,
            'fields' => 'ids',
            'meta_query' => [['key' => 'printed', 'compare' => 'NOT EXISTS']]
        ]);
        return [ 'printed' => $printed->found_posts, 'unprinted' => $unprinted->found_posts ];
    }

    public static function filter_query_by_printed($q) {
        if (!is_admin() || !$q->is_main_query()) return;
        if ($q->get('post_type') !== 'ds_design') return;
        if (!isset($_GET['ds_printed'])) return;
        $val = sanitize_text_field(wp_unslash($_GET['ds_printed']));
        if ($val === '1') {
            $q->set('meta_query', [['key' => 'printed', 'value' => '1']]);
        } elseif ($val === '0') {
            $q->set('meta_query', [['key' => 'printed', 'compare' => 'NOT EXISTS']]);
        }
    }

    public static function bulk_actions($actions) {
        $actions['ds_mark_printed'] = __('Mark as Printed', 'ds');
        $actions['ds_mark_unprinted'] = __('Mark as Unprinted', 'ds');
        $actions['ds_export_zip'] = __('Download ZIP (PNG/JSON)', 'ds');
        return $actions;
    }

    public static function handle_bulk_actions($redirect, $doaction, $post_ids) {
        if ($doaction === 'ds_mark_printed') {
            foreach($post_ids as $pid){ self::mark_printed($pid, true); }
            $redirect = add_query_arg('ds_bulk_printed', count($post_ids), $redirect);
        } elseif ($doaction === 'ds_mark_unprinted') {
            foreach($post_ids as $pid){ self::mark_printed($pid, false); }
            $redirect = add_query_arg('ds_bulk_unprinted', count($post_ids), $redirect);
        } elseif ($doaction === 'ds_export_zip') {
            $zip = self::build_zip($post_ids);
            if ($zip) {
                $redirect = add_query_arg('ds_export_zip_url', rawurlencode($zip), $redirect);
            } else {
                $redirect = add_query_arg('ds_export_zip_error', 1, $redirect);
            }
        }
        return $redirect;
    }

    public static function row_actions($actions, $post) {
        if ($post->post_type !== 'ds_design') return $actions;
        $printed = (bool) get_post_meta($post->ID, 'printed', true);
        if ($printed) {
            $url = wp_nonce_url(admin_url('admin.php?action=ds_mark_unprinted&post=' . $post->ID), 'ds_mark_unprinted_' . $post->ID);
            $actions['ds_unprinted'] = '<a href="' . esc_url($url) . '">' . __('Mark as Unprinted', 'ds') . '</a>';
        } else {
            $url = wp_nonce_url(admin_url('admin.php?action=ds_mark_printed&post=' . $post->ID), 'ds_mark_printed_' . $post->ID);
            $actions['ds_printed'] = '<a href="' . esc_url($url) . '">' . __('Mark as Printed', 'ds') . '</a>';
        }
        $dl = wp_nonce_url(admin_url('admin.php?action=ds_download_zip&post=' . $post->ID), 'ds_download_zip_' . $post->ID);
        $actions['ds_download'] = '<a href="' . esc_url($dl) . '">' . __('Download ZIP', 'ds') . '</a>';
        return $actions;
    }

    public static function action_mark_printed() {
        if (!isset($_GET['post'])) wp_die();
        $post_id = (int) $_GET['post'];
        check_admin_referer('ds_mark_printed_' . $post_id);
        self::mark_printed($post_id, true);
        wp_redirect(remove_query_arg(['action','post'], wp_get_referer()));
        exit;
    }

    public static function action_mark_unprinted() {
        if (!isset($_GET['post'])) wp_die();
        $post_id = (int) $_GET['post'];
        check_admin_referer('ds_mark_unprinted_' . $post_id);
        self::mark_printed($post_id, false);
        wp_redirect(remove_query_arg(['action','post'], wp_get_referer()));
        exit;
    }

    protected static function mark_printed($post_id, $val) {
        update_post_meta($post_id, 'printed', $val ? '1' : '');
        if ($val) {
            update_post_meta($post_id, 'printed_at', current_time('mysql'));
        } else {
            delete_post_meta($post_id, 'printed_at');
        }
    }

    public static function add_metabox() {
        add_meta_box('ds_design_status', __('Print Status', 'ds'), [__CLASS__, 'render_metabox'], 'ds_design', 'side');
        self::register_design_editor_metabox('ds_design');
    }

    protected static function register_design_editor_metabox($screen) {
        add_meta_box('ds_design_editor_embed', __('Design Editor', 'ds'), [__CLASS__, 'render_editor_metabox'], $screen, 'normal', 'high');
    }

    public static function add_design_editor_metabox_global($post_type, $post) {
        if ($post_type !== 'ds_design') return;
        self::register_design_editor_metabox('ds_design');
    }

    public static function unhide_design_editor_metabox($hidden, $screen) {
        if (!is_array($hidden)) return $hidden;
        if (!is_object($screen) || empty($screen->id) || $screen->id !== 'ds_design') return $hidden;
        return array_values(array_diff($hidden, ['ds_design_editor', 'ds_design_editor_embed']));
    }

    public static function render_metabox($post) {
        wp_nonce_field('ds_design_meta', 'ds_design_meta_nonce');
        $printed = (bool) get_post_meta($post->ID, 'printed', true);
        ?>
        <label>
            <input type="checkbox" name="ds_printed" value="1" <?php checked($printed); ?> />
            <?php _e('Printed', 'ds'); ?>
        </label>
        <?php
    }

    public static function render_editor_metabox($post) {
        $url = self::designer_url_for_design((int) $post->ID);
        if (!$url) {
            echo '<p>' . esc_html__('Designer page not found. Create a page with [design_studio] shortcode.', 'ds') . '</p>';
            return;
        }
        echo '<p style="margin:0 0 10px;">';
        echo '<a class="button button-primary" href="' . esc_url($url) . '" target="_blank">' . esc_html__('Open in new tab', 'ds') . '</a>';
        echo '</p>';
        echo '<div style="border:1px solid #d3dde8;border-radius:8px;overflow:hidden;background:#fff;">';
        echo '<iframe src="' . esc_url($url) . '" style="display:block;width:100%;height:78vh;min-height:640px;border:0;" loading="lazy"></iframe>';
        echo '</div>';
    }

    public static function save_metabox($post_id) {
        if (!isset($_POST['ds_design_meta_nonce']) || !wp_verify_nonce($_POST['ds_design_meta_nonce'], 'ds_design_meta')) return;
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
        if (!current_user_can('edit_post', $post_id)) return;
        $printed = isset($_POST['ds_printed']);
        self::mark_printed($post_id, $printed);
    }

    public static function build_zip($post_ids) {
        if (!class_exists('ZipArchive')) return false;
        $upload_dir = wp_upload_dir();
        $base = trailingslashit($upload_dir['basedir']) . 'design-studio/exports';
        wp_mkdir_p($base);
        $uuid = wp_generate_uuid4();
        $zip_path = trailingslashit($base) . $uuid . '.zip';
        $zip_url = trailingslashit($upload_dir['baseurl']) . 'design-studio/exports/' . $uuid . '.zip';
        $zip = new \ZipArchive();
        if ($zip->open($zip_path, \ZipArchive::CREATE)!==TRUE) return false;
        foreach($post_ids as $pid){
            $title = sanitize_title(get_the_title($pid)) ?: 'design-' . $pid;
            $png = get_post_meta($pid, 'png_url', true);
            $zone_png = self::zone_png_urls($pid);
            $zone_layers = self::zone_layers_urls($pid);
            $file_to_add = $png;
            if ($file_to_add) {
                $local = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $file_to_add);
                if (file_exists($local)) {
                    $ext = pathinfo($local, PATHINFO_EXTENSION);
                    $zip->addFile($local, $title . '-' . $pid . '.' . $ext);
                }
            }
            if (!empty($zone_png)) {
                foreach ($zone_png as $zid => $url) {
                    $local = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $url);
                    if (!file_exists($local)) continue;
                    $ext = pathinfo($local, PATHINFO_EXTENSION) ?: 'png';
                    $zip->addFile($local, $title . '-' . $pid . '-zone-' . sanitize_file_name($zid) . '.' . $ext);
                }
            }
            if (!empty($zone_layers)) {
                foreach ($zone_layers as $zid => $url) {
                    $local = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $url);
                    if (!file_exists($local)) continue;
                    $ext = pathinfo($local, PATHINFO_EXTENSION) ?: 'json';
                    $zip->addFile($local, $title . '-' . $pid . '-zone-' . sanitize_file_name($zid) . '.' . $ext);
                }
            }
        }
        $zip->close();
        return $zip_url;
    }

    public static function export_notice() {
        if (!is_admin()) return;
        if (isset($_GET['ds_export_zip_url'])) {
            $url = esc_url_raw(wp_unslash($_GET['ds_export_zip_url']));
            echo '<div class="notice notice-success is-dismissible"><p>' . sprintf(__('Export ready: <a href="%s" target="_blank">Download ZIP</a>', 'ds'), esc_url($url)) . '</p></div>';
        } elseif (isset($_GET['ds_export_zip_error'])) {
            echo '<div class="notice notice-error is-dismissible"><p>' . __('Could not build ZIP (ZipArchive missing?)', 'ds') . '</p></div>';
        }
    }

    public static function action_download_zip() {
        if (!isset($_GET['post'])) wp_die();
        $post_id = (int) $_GET['post'];
        check_admin_referer('ds_download_zip_' . $post_id);
        $url = self::build_zip([$post_id]);
        if ($url) {
            wp_redirect($url);
        } else {
            wp_redirect(add_query_arg('ds_export_zip_error', 1, wp_get_referer()));
        }
        exit;
    }
}
