<?php

namespace SoftminalB2B\Http\Controllers;

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

use SoftminalB2B\Services\Pdf\Invoice;
use SoftminalB2B\Services\Settings;
use SoftminalB2B\Support\Tier;

/**
 * The PDF documents picker: list the ready-made templates, choose one, and
 * render a live preview. There is no block editor — a merchant selects a design,
 * not builds one. Pro templates appear here too, locked, as an upsell.
 */
class DocumentsController extends Controller
{
    public function index(\WP_REST_Request $request, $params = [])
    {
        $selected = Invoice::template();
        $isPro    = Tier::isPro();

        $templates = [];

        foreach (Invoice::templates() as $slug => $entry) {
            $templates[] = [
                'slug'     => (string) $slug,
                'label'    => (string) $entry['label'],
                'pro'      => (bool) $entry['pro'],
                'accent'   => (string) $entry['accent'],
                'locked'   => $entry['pro'] && !$isPro,
                'selected' => $slug === $selected,
            ];
        }

        return $this->success([
            'templates' => $templates,
            'selected'  => $selected,
            'enabled'   => Settings::get('invoices_enabled', 'yes') !== 'no',
            'tier'      => Tier::toArray(),
            // Pro fills this with the font + watermark controls; null on free.
            'customization' => apply_filters('smb2b_documents_customization', null),
        ]);
    }

    /**
     * Choose a template. A free install cannot select a Pro design.
     */
    public function select(\WP_REST_Request $request, $params = [])
    {
        $slug      = sanitize_key((string) $request->get_param('slug'));
        $templates = Invoice::templates();

        if (!isset($templates[$slug])) {
            return $this->error(__('That template does not exist.', 'softminal-b2b-wholesale-for-woocommerce'), 422);
        }

        if ($templates[$slug]['pro'] && !Tier::isPro()) {
            return $this->error(__('That template is part of Pro.', 'softminal-b2b-wholesale-for-woocommerce'), 403);
        }

        Settings::set('invoice_template', $slug);

        return $this->success(
            ['selected' => $slug],
            __('Template selected.', 'softminal-b2b-wholesale-for-woocommerce')
        );
    }

    /**
     * Render one template with sample data, for the picker's live preview. Only
     * a template that exists and is available to this tier is rendered.
     */
    public function preview(\WP_REST_Request $request, $params = [])
    {
        $slug      = sanitize_key((string) ($params['slug'] ?? $request->get_param('slug')));
        $templates = Invoice::templates();

        if (!isset($templates[$slug])) {
            $slug = Invoice::DEFAULT_TEMPLATE;
        }

        // Pro designs are not rendered on a free install — their template files
        // ship only in the Pro add-on, so there is nothing to render here. The
        // picker shows a locked placeholder instead. When Pro is active it has
        // registered the real files and they render normally.
        if ($templates[$slug]['pro'] && !Tier::isPro()) {
            return $this->success([
                'slug'   => $slug,
                'locked' => true,
                'html'   => '',
            ]);
        }

        return $this->success([
            'slug'   => $slug,
            'locked' => false,
            'html'   => Invoice::renderTemplate($slug, Invoice::sampleData()),
        ]);
    }
}
