<?php
/**
 * Admin: import dishes from a menu PDF.
 *
 * @package Maca_Menu_List
 */

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

/**
 * Dish PDF import admin screen.
 */
class Maca_MenuList_Admin_Dish_Pdf_Import {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'), 21);
        add_action('admin_init', array($this, 'handle_actions'));
    }

    /**
     * Register submenu under maca Restu.
     */
    public function add_admin_menu() {
        if (!maca_menulist_is_dishes_mode()) {
            return;
        }

        add_submenu_page(
            'maca-restu',
            __('Importera från PDF', 'maca-restu-pro'),
            __('Importera från PDF', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-import-pdf',
            array($this, 'render_page')
        );
    }

    /**
     * Handle parse and import submissions.
     */
    public function handle_actions() {
        if (!isset($_POST['maca_pdf_import_action'])) {
            return;
        }

        if (!maca_menulist_user_can_manage_import_export() || !maca_menulist_pro_has_feature('dishes')) {
            return;
        }

        if (!isset($_POST['maca_pdf_import_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['maca_pdf_import_nonce'])), 'maca_pdf_import')) {
            add_settings_error('maca_pdf_import', 'error', __('Säkerhetskontroll misslyckades. Försök igen.', 'maca-restu-pro'));
            return;
        }

        $action = sanitize_key(wp_unslash($_POST['maca_pdf_import_action']));

        if ($action === 'parse') {
            $this->handle_parse();
        } elseif ($action === 'import') {
            $this->handle_import();
        } elseif ($action === 'cancel') {
            maca_menulist_pdf_import_clear_preview();
            maca_menulist_pdf_import_flash_notice(__('Import avbruten.', 'maca-restu-pro'), 'success');
            $this->redirect_import_page();
        }
    }

    /**
     * Parse uploaded or selected PDF.
     */
    private function handle_parse() {
        maca_menulist_pdf_import_raise_limits();

        $source_label = '';
        $file_path = '';
        $temp_file = '';

        // phpcs:disable WordPress.Security.NonceVerification.Missing -- Verified in handle_actions().
        $menu_id = isset($_POST['pdf_menu_id']) ? intval($_POST['pdf_menu_id']) : 0;

        if ($menu_id > 0) {
            $menu = maca_menulist_db_get_menu($menu_id);

            if ($menu && $menu->file_type === 'pdf' && !empty($menu->file_url)) {
                $file_path = maca_menulist_pdf_resolve_local_path($menu->file_url);
                $source_label = maca_menulist_get_menu_display_title($menu);

                if ($file_path === '') {
                    require_once ABSPATH . 'wp-admin/includes/file.php';
                    $downloaded = download_url($menu->file_url, 30);

                    if (!is_wp_error($downloaded)) {
                        $file_path = $downloaded;
                        $temp_file = $downloaded;
                    }
                }
            }
        }

        if ($file_path === '' && isset($_FILES['pdf_upload']['error']) && UPLOAD_ERR_OK === (int) $_FILES['pdf_upload']['error']) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $uploaded = $_FILES['pdf_upload'];
            $ext = strtolower(pathinfo($uploaded['name'], PATHINFO_EXTENSION));

            if ($ext !== 'pdf') {
                add_settings_error('maca_pdf_import', 'error', __('Ladda upp en PDF-fil.', 'maca-restu-pro'));
                return;
            }

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

            $upload = wp_handle_upload(
                $uploaded,
                array(
                    'test_form' => false,
                    'mimes' => array('pdf' => 'application/pdf'),
                )
            );

            if (isset($upload['error'])) {
                add_settings_error('maca_pdf_import', 'error', esc_html($upload['error']));
                return;
            }

            if (!empty($upload['file'])) {
                $file_path = $upload['file'];
                $source_label = sanitize_file_name($uploaded['name']);
            }
        }
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        if ($file_path === '') {
            add_settings_error(
                'maca_pdf_import',
                'error',
                __('Välj en befintlig meny-PDF eller ladda upp en ny PDF-fil.', 'maca-restu-pro')
            );
            return;
        }

        $cleanup_temp = static function () use ($temp_file) {
            if ($temp_file !== '' && is_file($temp_file)) {
                wp_delete_file($temp_file);
            }
        };

        $text = maca_menulist_pdf_extract_text($file_path);
        $cleanup_temp();

        if (is_wp_error($text)) {
            maca_menulist_pdf_import_flash_notice($text->get_error_message(), 'error');
            $this->redirect_import_page();
        }

        $rows = maca_menulist_pdf_parse_menu_text($text);

        if (empty($rows)) {
            maca_menulist_pdf_import_flash_notice(
                __('Inga rätter hittades. PDF:en kan vara bildbaserad eller ha ett layoutformat som inte stöds.', 'maca-restu-pro'),
                'error'
            );
            $this->redirect_import_page();
        }

        maca_menulist_pdf_import_set_preview(
            array(
                'source' => $source_label !== '' ? $source_label : basename($file_path),
                'rows' => $rows,
                'created' => time(),
            )
        );

        maca_menulist_pdf_import_flash_notice(
            sprintf(
                /* translators: %d: number of dishes found */
                _n('%d dish found — review below before importing.', '%d dishes found — review below before importing.', count($rows), 'maca-restu-pro'),
                count($rows)
            ),
            'success'
        );

        $this->redirect_import_page();
    }

    /**
     * Redirect back to the import admin screen (avoids repost/timeouts).
     */
    private function redirect_import_page() {
        wp_safe_redirect(admin_url('admin.php?page=maca-restu-import-pdf'));
        exit;
    }

    /**
     * Save reviewed rows to the database.
     */
    private function handle_import() {
        maca_menulist_pdf_import_raise_limits();

        $preview = maca_menulist_pdf_import_get_preview();

        if ($preview === null || empty($preview['rows']) || !is_array($preview['rows'])) {
            maca_menulist_pdf_import_flash_notice(__('Ingen förhandsgranskning. Ladda upp och analysera en PDF först.', 'maca-restu-pro'), 'error');
            $this->redirect_import_page();
        }

        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $create_categories = !empty($_POST['create_categories']);
        $submitted = isset($_POST['rows']) && is_array($_POST['rows']) ? wp_unslash($_POST['rows']) : array();
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        $rows = array();

        foreach ($submitted as $index => $item) {
            if (!is_array($item)) {
                continue;
            }

            $rows[] = array(
                'import' => !empty($item['import']),
                'category_name' => sanitize_text_field((string) ($item['category_name'] ?? '')),
                'title' => sanitize_text_field((string) ($item['title'] ?? '')),
                'description' => sanitize_textarea_field((string) ($item['description'] ?? '')),
                'price' => sanitize_text_field((string) ($item['price'] ?? '')),
            );
        }

        if (empty($rows)) {
            maca_menulist_pdf_import_flash_notice(__('Inga rader att importera.', 'maca-restu-pro'), 'error');
            $this->redirect_import_page();
        }

        $result = maca_menulist_pdf_import_save_rows($rows, $create_categories);
        maca_menulist_pdf_import_clear_preview();

        $messages = array();

        if ($result['imported'] > 0) {
            $messages[] = sprintf(
                /* translators: %d: number of dishes imported */
                _n('%d dish imported successfully.', '%d dishes imported successfully.', $result['imported'], 'maca-restu-pro'),
                $result['imported']
            );
        }

        if ($result['skipped'] > 0) {
            $messages[] = sprintf(
                /* translators: %d: skipped rows */
                _n('%d row was skipped (unchecked).', '%d rows were skipped (unchecked).', $result['skipped'], 'maca-restu-pro'),
                $result['skipped']
            );
        }

        if (!empty($result['errors'])) {
            $messages[] = sprintf(
                /* translators: %d: failed rows */
                _n('%d row could not be saved.', '%d rows could not be saved.', count($result['errors']), 'maca-restu-pro'),
                count($result['errors'])
            );
        }

        if ($result['imported'] === 0 && empty($result['errors'])) {
            maca_menulist_pdf_import_flash_notice(__('Inget importerades. Välj minst en rad.', 'maca-restu-pro'), 'error');
            $this->redirect_import_page();
        }

        maca_menulist_pdf_import_flash_notice(implode(' ', $messages), $result['imported'] > 0 ? 'success' : 'error');
        wp_safe_redirect(admin_url('admin.php?page=maca-restu-dishes'));
        exit;
    }

    /**
     * Render admin page.
     */
    public function render_page() {
        if (!maca_menulist_pro_has_feature('dishes')) {
            ?>
            <div class="wrap">
                <h1><?php esc_html_e('Importera från PDF', 'maca-restu-pro'); ?></h1>
                <?php echo wp_kses_post(maca_menulist_pro_locked_notice('dishes')); ?>
            </div>
            <?php
            return;
        }

        maca_menulist_pdf_import_show_flash_notice();

        $preview = maca_menulist_pdf_import_get_preview();
        $pdf_menus = maca_menulist_pdf_import_get_pdf_menus();
        $dish_categories = maca_menulist_db_get_dish_categories();

        ?>
        <div class="wrap maca-pdf-import-wrap<?php echo esc_attr(maca_menulist_admin_demo_readonly_wrap_class()); ?>">
            <h1><?php esc_html_e('Importera rätter från PDF', 'maca-restu-pro'); ?></h1>

            <?php maca_menulist_render_admin_demo_readonly_notice(); ?>

            <p class="description">
                <?php esc_html_e('Extrahera rätttitlar, beskrivningar och priser från en textbaserad meny-PDF. Granska och redigera resultatet innan du sparar i onlinemenyn.', 'maca-restu-pro'); ?>
            </p>

            <?php settings_errors('maca_pdf_import'); ?>

            <?php if ($preview === null) : ?>
                <?php $this->render_upload_form($pdf_menus); ?>
            <?php else : ?>
                <?php $this->render_preview_form($preview, $dish_categories); ?>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * @param array<int, object> $pdf_menus Menu PDF records.
     */
    private function render_upload_form($pdf_menus) {
        ?>
        <form method="post" enctype="multipart/form-data" class="maca-pdf-import-upload">
            <?php wp_nonce_field('maca_pdf_import', 'maca_pdf_import_nonce'); ?>
            <input type="hidden" name="maca_pdf_import_action" value="parse">

            <?php if (!empty($pdf_menus)) : ?>
                <h2><?php esc_html_e('Använd befintlig meny-PDF', 'maca-restu-pro'); ?></h2>
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><label for="pdf_menu_id"><?php esc_html_e('Meny-PDF', 'maca-restu-pro'); ?></label></th>
                        <td>
                            <select name="pdf_menu_id" id="pdf_menu_id" class="regular-text">
                                <option value="0"><?php esc_html_e('— Välj —', 'maca-restu-pro'); ?></option>
                                <?php foreach ($pdf_menus as $menu) : ?>
                                    <option value="<?php echo esc_attr((int) $menu->id); ?>">
                                        <?php
                                        echo esc_html(
                                            sprintf(
                                                '%s (%s)',
                                                maca_menulist_get_menu_display_title($menu),
                                                $menu->category_name ? $menu->category_name : __('Ingen kategori', 'maca-restu-pro')
                                            )
                                        );
                                        ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description"><?php esc_html_e('PDF-filer som redan laddats upp under Menyer (PDF/bild-läge).', 'maca-restu-pro'); ?></p>
                        </td>
                    </tr>
                </table>
                <p><em><?php esc_html_e('eller', 'maca-restu-pro'); ?></em></p>
            <?php endif; ?>

            <h2><?php esc_html_e('Ladda upp PDF', 'maca-restu-pro'); ?></h2>
            <table class="form-table" role="presentation">
                <tr>
                    <th scope="row"><label for="pdf_upload"><?php esc_html_e('PDF-fil', 'maca-restu-pro'); ?></label></th>
                    <td>
                        <input type="file" name="pdf_upload" id="pdf_upload" accept="application/pdf,.pdf">
                        <p class="description">
                            <?php esc_html_e('Fungerar bäst med PDF:er som har markerbar text (exporterade från designprogram). Skannade bildmenyer stöds inte ännu.', 'maca-restu-pro'); ?>
                        </p>
                    </td>
                </tr>
            </table>

            <?php submit_button(__('Analysera PDF', 'maca-restu-pro'), 'primary', 'submit', false); ?>
        </form>
        <?php
    }

    /**
     * @param array<string, mixed>   $preview Preview transient.
     * @param array<int, object>     $dish_categories Existing dish categories.
     */
    private function render_preview_form($preview, $dish_categories) {
        $rows = isset($preview['rows']) && is_array($preview['rows']) ? $preview['rows'] : array();
        $source = isset($preview['source']) ? (string) $preview['source'] : '';

        ?>
        <p>
            <strong><?php esc_html_e('Källa:', 'maca-restu-pro'); ?></strong>
            <?php echo esc_html($source); ?>
            —
            <a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-import-pdf')); ?>">
                <?php esc_html_e('Analysera en annan PDF', 'maca-restu-pro'); ?>
            </a>
        </p>

        <form method="post" class="maca-pdf-import-preview">
            <?php wp_nonce_field('maca_pdf_import', 'maca_pdf_import_nonce'); ?>
            <input type="hidden" name="maca_pdf_import_action" value="import">

            <p>
                <label>
                    <input type="checkbox" name="create_categories" value="1" checked>
                    <?php esc_html_e('Skapa rättkategorier som saknas (matchas på namn)', 'maca-restu-pro'); ?>
                </label>
            </p>

            <?php if (!empty($dish_categories)) : ?>
                <p class="description">
                    <?php esc_html_e('Befintliga rättkategorier:', 'maca-restu-pro'); ?>
                    <?php
                    $names = array();
                    foreach ($dish_categories as $cat) {
                        $names[] = $cat->name;
                    }
                    echo esc_html(implode(', ', $names));
                    ?>
                </p>
            <?php endif; ?>

            <table class="widefat striped maca-pdf-import-table">
                <thead>
                    <tr>
                        <td class="check-column">
                            <input type="checkbox" id="maca-pdf-import-toggle-all" checked>
                        </td>
                        <th><?php esc_html_e('Kategori', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Titel', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Beskrivning', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Pris', 'maca-restu-pro'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($rows as $index => $row) : ?>
                        <tr>
                            <th scope="row" class="check-column">
                                <input
                                    type="checkbox"
                                    name="rows[<?php echo esc_attr((string) $index); ?>][import]"
                                    value="1"
                                    class="maca-pdf-import-row-check"
                                    <?php checked(!empty($row['import'])); ?>
                                >
                            </th>
                            <td>
                                <input
                                    type="text"
                                    class="regular-text"
                                    name="rows[<?php echo esc_attr((string) $index); ?>][category_name]"
                                    value="<?php echo esc_attr((string) ($row['category_name'] ?? '')); ?>"
                                >
                            </td>
                            <td>
                                <input
                                    type="text"
                                    class="regular-text"
                                    name="rows[<?php echo esc_attr((string) $index); ?>][title]"
                                    value="<?php echo esc_attr((string) ($row['title'] ?? '')); ?>"
                                >
                            </td>
                            <td>
                                <textarea
                                    class="large-text"
                                    rows="2"
                                    name="rows[<?php echo esc_attr((string) $index); ?>][description]"
                                ><?php echo esc_textarea((string) ($row['description'] ?? '')); ?></textarea>
                            </td>
                            <td>
                                <input
                                    type="text"
                                    class="small-text"
                                    name="rows[<?php echo esc_attr((string) $index); ?>][price]"
                                    value="<?php echo esc_attr((string) ($row['price'] ?? '')); ?>"
                                >
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <p class="submit">
                <?php submit_button(__('Importera valda rätter', 'maca-restu-pro'), 'primary', 'submit', false); ?>
            </p>
        </form>

        <form method="post" style="display:inline;margin-left:8px;">
            <?php wp_nonce_field('maca_pdf_import', 'maca_pdf_import_nonce'); ?>
            <input type="hidden" name="maca_pdf_import_action" value="cancel">
            <?php submit_button(__('Avbryt', 'maca-restu-pro'), 'secondary', 'submit', false); ?>
        </form>

        <script>
        (function () {
            var toggleAll = document.getElementById('maca-pdf-import-toggle-all');
            if (!toggleAll) {
                return;
            }
            toggleAll.addEventListener('change', function () {
                document.querySelectorAll('.maca-pdf-import-row-check').forEach(function (cb) {
                    cb.checked = toggleAll.checked;
                });
            });
        })();
        </script>
        <style>
            .maca-pdf-import-table input.regular-text { width: 100%; max-width: 220px; }
            .maca-pdf-import-table textarea { width: 100%; min-width: 200px; }
        </style>
        <?php
    }
}
