<?php
/**
 * Admin: import and export dishes as CSV.
 *
 * @package Maca_Menu_List
 */

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

/**
 * Dish CSV import/export admin screen.
 */
class Maca_MenuList_Admin_Dish_Csv {

    /**
     * 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/exportera CSV', 'maca-restu-pro'),
            __('Importera/exportera CSV', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-dish-csv',
            array($this, 'render_page')
        );
    }

    /**
     * Handle export, parse, and import.
     */
    public function handle_actions() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (isset($_GET['page']) && sanitize_key(wp_unslash($_GET['page'])) === 'maca-restu-dish-csv') {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if (isset($_GET['maca_dish_csv_cancel'])) {
                if (!maca_menulist_user_can_manage_import_export() || !maca_menulist_pro_has_feature('dishes')) {
                    return;
                }

                check_admin_referer('maca_dish_csv_cancel');
                maca_menulist_dish_csv_clear_preview();
                wp_safe_redirect(admin_url('admin.php?page=maca-restu-dish-csv'));
                exit;
            }

            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if (isset($_GET['maca_export']) && sanitize_key(wp_unslash($_GET['maca_export'])) === 'csv') {
                if (!maca_menulist_user_can_manage_import_export() || !maca_menulist_pro_has_feature('dishes')) {
                    return;
                }

                check_admin_referer('maca_dish_csv_export');
                maca_menulist_dish_csv_emit_export();
            }
        }

        if (!isset($_POST['maca_dish_csv_action'])) {
            return;
        }

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

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

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

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

    /**
     * Parse uploaded CSV.
     */
    private function handle_parse() {
        // phpcs:disable WordPress.Security.NonceVerification.Missing -- Verified in handle_actions().
        if (!isset($_FILES['csv_upload']['error']) || UPLOAD_ERR_OK !== (int) $_FILES['csv_upload']['error']) {
            add_settings_error(
                'maca_dish_csv',
                'error',
                __('Välj en CSV-fil att ladda upp.', 'maca-restu-pro')
            );
            return;
        }

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $uploaded = $_FILES['csv_upload'];
        $ext = strtolower(pathinfo($uploaded['name'], PATHINFO_EXTENSION));

        if (!in_array($ext, array('csv', 'txt'), true)) {
            add_settings_error('maca_dish_csv', 'error', __('Ladda upp en CSV-fil.', 'maca-restu-pro'));
            return;
        }

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

        $upload = wp_handle_upload(
            $uploaded,
            array(
                'test_form' => false,
                'mimes' => array(
                    'csv' => 'text/csv',
                    'txt' => 'text/plain',
                ),
            )
        );

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

        if (empty($upload['file'])) {
            add_settings_error('maca_dish_csv', 'error', __('Uppladdningen misslyckades.', 'maca-restu-pro'));
            return;
        }
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        $rows = maca_menulist_dish_csv_parse_file($upload['file']);
        wp_delete_file($upload['file']);

        if (is_wp_error($rows)) {
            maca_menulist_dish_csv_flash_notice($rows->get_error_message(), 'error');
            $this->redirect_page();
        }

        maca_menulist_dish_csv_set_preview(
            array(
                'source' => sanitize_file_name($uploaded['name']),
                'rows' => $rows,
                'created' => time(),
            )
        );

        maca_menulist_dish_csv_flash_notice(
            sprintf(
                /* translators: %d: number of dishes found */
                _n('%d rad hittades — granska nedan innan import.', '%d rader hittades — granska nedan innan import.', count($rows), 'maca-restu-pro'),
                count($rows)
            ),
            'success'
        );

        $this->redirect_page();
    }

    /**
     * Save reviewed rows.
     */
    private function handle_import() {
        $preview = maca_menulist_dish_csv_get_preview();

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

        // phpcs:disable WordPress.Security.NonceVerification.Missing
        $create_categories = !empty($_POST['create_categories']);
        $update_existing = !empty($_POST['update_existing']);
        $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']),
                'id' => sanitize_text_field((string) ($item['id'] ?? '')),
                'category' => sanitize_text_field((string) ($item['category'] ?? '')),
                'title' => sanitize_text_field((string) ($item['title'] ?? '')),
                'title_en' => sanitize_text_field((string) ($item['title_en'] ?? '')),
                'description' => sanitize_textarea_field((string) ($item['description'] ?? '')),
                'description_en' => sanitize_textarea_field((string) ($item['description_en'] ?? '')),
                'price' => sanitize_text_field((string) ($item['price'] ?? '')),
                'price_takeaway' => sanitize_text_field((string) ($item['price_takeaway'] ?? '')),
                'takeaway_active' => sanitize_text_field((string) ($item['takeaway_active'] ?? '')),
                'vat_code' => sanitize_text_field((string) ($item['vat_code'] ?? '')),
                'image_url' => esc_url_raw((string) ($item['image_url'] ?? '')),
                'is_active' => sanitize_text_field((string) ($item['is_active'] ?? '')),
                'allergens' => sanitize_text_field((string) ($item['allergens'] ?? '')),
                'sort_order' => sanitize_text_field((string) ($item['sort_order'] ?? '')),
            );
        }

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

        $result = maca_menulist_dish_csv_save_rows(
            $rows,
            array(
                'create_categories' => $create_categories,
                'update_existing' => $update_existing,
            )
        );
        maca_menulist_dish_csv_clear_preview();

        $messages = array();

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

        if ($result['updated'] > 0) {
            $messages[] = sprintf(
                /* translators: %d: number of dishes updated */
                _n('%d rätt uppdaterades.', '%d rätter uppdaterades.', $result['updated'], 'maca-restu-pro'),
                $result['updated']
            );
        }

        if ($result['skipped'] > 0) {
            $messages[] = sprintf(
                /* translators: %d: skipped rows */
                _n('%d rad hoppades över.', '%d rader hoppades över.', $result['skipped'], 'maca-restu-pro'),
                $result['skipped']
            );
        }

        if (!empty($result['errors'])) {
            $messages[] = sprintf(
                /* translators: %d: failed rows */
                _n('%d rad kunde inte sparas.', '%d rader kunde inte sparas.', count($result['errors']), 'maca-restu-pro'),
                count($result['errors'])
            );
        }

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

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

    /**
     * Redirect to CSV admin page.
     */
    private function redirect_page() {
        wp_safe_redirect(admin_url('admin.php?page=maca-restu-dish-csv'));
        exit;
    }

    /**
     * Export URL with nonce.
     *
     * @return string
     */
    private function export_url() {
        return wp_nonce_url(
            admin_url('admin.php?page=maca-restu-dish-csv&maca_export=csv'),
            'maca_dish_csv_export'
        );
    }

    /**
     * URL that clears the CSV preview and returns to the upload form.
     *
     * @return string
     */
    private function cancel_preview_url() {
        return wp_nonce_url(
            admin_url('admin.php?page=maca-restu-dish-csv&maca_dish_csv_cancel=1'),
            'maca_dish_csv_cancel'
        );
    }

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

        maca_menulist_dish_csv_show_flash_notice();

        $preview = maca_menulist_dish_csv_get_preview();
        $dish_categories = maca_menulist_db_get_dish_categories();
        $dish_count = count(maca_menulist_db_get_dishes(false));

        ?>
        <div class="wrap maca-dish-csv-wrap<?php echo esc_attr(maca_menulist_admin_demo_readonly_wrap_class()); ?>">
            <h1><?php esc_html_e('Importera och exportera rätter (CSV)', 'maca-restu-pro'); ?></h1>

            <?php maca_menulist_render_admin_demo_readonly_notice(); ?>
            <p class="description">
                <?php esc_html_e('Exportera onlinemenyn till kalkylblad, redigera offline och importera igen. Kolumner avgränsas med semikolon (;) så komma i beskrivningar fungerar i Excel. Allergener matchas på namn (semikolonseparerade i allergenkolumnen).', 'maca-restu-pro'); ?>
            </p>

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

            <h2><?php esc_html_e('Exportera', 'maca-restu-pro'); ?></h2>
            <p>
                <?php
                printf(
                    /* translators: %d: dish count */
                    esc_html(_n('%d rätt i databasen.', '%d rätter i databasen.', $dish_count, 'maca-restu-pro')),
                    (int) $dish_count
                );
                ?>
            </p>
            <p>
                <a class="button button-primary" href="<?php echo esc_url($this->export_url()); ?>">
                    <?php esc_html_e('Ladda ner CSV', 'maca-restu-pro'); ?>
                </a>
            </p>
            <p class="description">
                <?php esc_html_e('Kolumner: id, category, title, title_en, description, price, vat_code, allergens, active status med mera. Importera samma fil igen för att uppdatera befintliga rätter när id är satt och kryssrutan för uppdatering är ikryssad.', 'maca-restu-pro'); ?>
            </p>
            <p class="description">
                <?php esc_html_e('Momskod (vat_code): använd food eller alcohol, eller svenska etiketter som Mat / alkoholfritt och Alkohol.', 'maca-restu-pro'); ?>
            </p>

            <hr>

            <h2><?php esc_html_e('Importera', 'maca-restu-pro'); ?></h2>

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

    /**
     * Upload form.
     */
    private function render_upload_form() {
        ?>
        <form method="post" enctype="multipart/form-data" class="maca-dish-csv-upload">
            <?php wp_nonce_field('maca_dish_csv', 'maca_dish_csv_nonce'); ?>
            <input type="hidden" name="maca_dish_csv_action" value="parse">

            <table class="form-table" role="presentation">
                <tr>
                    <th scope="row"><label for="csv_upload"><?php esc_html_e('CSV-fil', 'maca-restu-pro'); ?></label></th>
                    <td>
                        <input type="file" name="csv_upload" id="csv_upload" accept=".csv,text/csv,text/plain">
                        <p class="description">
                            <?php esc_html_e('UTF-8 CSV med rubrikrad; kolumner avgränsas med semikolon (;). Minst kolumnerna category och title (eller title_en).', 'maca-restu-pro'); ?>
                        </p>
                    </td>
                </tr>
            </table>

            <?php submit_button(__('Ladda upp och förhandsgranska', 'maca-restu-pro'), 'primary', 'submit', false); ?>
        </form>
        <?php
    }

    /**
     * @param array<string, mixed> $preview Preview transient.
     * @param array<int, object>   $dish_categories Existing 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($this->cancel_preview_url()); ?>">
                <?php esc_html_e('Ladda upp en annan fil', 'maca-restu-pro'); ?>
            </a>
        </p>

        <form method="post" class="maca-dish-csv-preview">
            <?php wp_nonce_field('maca_dish_csv', 'maca_dish_csv_nonce'); ?>
            <input type="hidden" name="maca_dish_csv_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>
            <p>
                <label>
                    <input type="checkbox" name="update_existing" value="1" checked>
                    <?php esc_html_e('Uppdatera befintliga rätter när id finns', '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-dish-csv-table">
                <thead>
                    <tr>
                        <td class="check-column">
                            <input type="checkbox" id="maca-dish-csv-toggle-all" checked>
                        </td>
                        <th><?php esc_html_e('ID', 'maca-restu-pro'); ?></th>
                        <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('Pris', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('VAT code', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Allergener', 'maca-restu-pro'); ?></th>
                        <th><?php esc_html_e('Aktiv', '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-dish-csv-row-check"
                                    <?php checked(!empty($row['import'])); ?>
                                >
                            </th>
                            <td>
                                <input type="text" class="small-text" name="rows[<?php echo esc_attr((string) $index); ?>][id]" value="<?php echo esc_attr((string) ($row['id'] ?? '')); ?>">
                            </td>
                            <td>
                                <input type="text" class="regular-text" name="rows[<?php echo esc_attr((string) $index); ?>][category]" value="<?php echo esc_attr((string) ($row['category'] ?? '')); ?>">
                            </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>
                                <input type="text" class="small-text" name="rows[<?php echo esc_attr((string) $index); ?>][price]" value="<?php echo esc_attr((string) ($row['price'] ?? '')); ?>">
                            </td>
                            <td>
                                <?php
                                $row_vat_code = maca_menulist_parse_dish_vat_code($row['vat_code'] ?? 'food');
                                $vat_code_options = maca_menulist_get_dish_vat_code_options();
                                ?>
                                <select name="rows[<?php echo esc_attr((string) $index); ?>][vat_code]">
                                    <?php foreach ($vat_code_options as $vat_option => $vat_label) : ?>
                                        <option value="<?php echo esc_attr($vat_option); ?>" <?php selected($row_vat_code, $vat_option); ?>>
                                            <?php echo esc_html($vat_label); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td>
                                <input type="text" class="regular-text" name="rows[<?php echo esc_attr((string) $index); ?>][allergens]" value="<?php echo esc_attr((string) ($row['allergens'] ?? '')); ?>">
                            </td>
                            <td>
                                <input type="text" class="small-text" name="rows[<?php echo esc_attr((string) $index); ?>][is_active]" value="<?php echo esc_attr((string) ($row['is_active'] ?? '1')); ?>">
                                <input type="hidden" name="rows[<?php echo esc_attr((string) $index); ?>][title_en]" value="<?php echo esc_attr((string) ($row['title_en'] ?? '')); ?>">
                                <input type="hidden" name="rows[<?php echo esc_attr((string) $index); ?>][description]" value="<?php echo esc_attr((string) ($row['description'] ?? '')); ?>">
                                <input type="hidden" name="rows[<?php echo esc_attr((string) $index); ?>][description_en]" value="<?php echo esc_attr((string) ($row['description_en'] ?? '')); ?>">
                                <input type="hidden" name="rows[<?php echo esc_attr((string) $index); ?>][price_takeaway]" value="<?php echo esc_attr((string) ($row['price_takeaway'] ?? '')); ?>">
                                <input type="hidden" name="rows[<?php echo esc_attr((string) $index); ?>][takeaway_active]" value="<?php echo esc_attr((string) ($row['takeaway_active'] ?? '0')); ?>">
                                <input type="hidden" name="rows[<?php echo esc_attr((string) $index); ?>][image_url]" value="<?php echo esc_attr((string) ($row['image_url'] ?? '')); ?>">
                                <input type="hidden" name="rows[<?php echo esc_attr((string) $index); ?>][sort_order]" value="<?php echo esc_attr((string) ($row['sort_order'] ?? '')); ?>">
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

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

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

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