<?php
if (!defined('ABSPATH')) exit;

/**
 * Handles template-started website requests.
 * Templates are visual direction hints; full generation runs through the canonical pipeline.
 */
class VMO_Template_Handler {

    public function __construct() {
        add_action('wp_ajax_vmo_generate_template', array($this, 'handle_generate_template'));
        add_action('wp_ajax_vmo_get_template_preview', array($this, 'handle_get_template_preview'));
    }

    public function handle_generate_template() {
        check_ajax_referer('vmo_builder_nonce', 'security');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => 'Insufficient permissions'));
        }

        $template_id = sanitize_text_field(wp_unslash($_POST['template_id'] ?? ''));
        $category = sanitize_text_field(wp_unslash($_POST['category'] ?? ''));
        $token_cost = max(0, absint($_POST['token_cost'] ?? 0));
        $user_id = get_current_user_id();
        $current_balance = (int) get_user_meta($user_id, 'vmo_token_balance', true);

        if ($template_id === '') {
            wp_send_json_error(array('message' => 'Template ID is required'));
        }

        if ($current_balance < $token_cost) {
            wp_send_json_error(array('message' => 'Insufficient tokens'));
        }

        if (!class_exists('VMO_Canonical_Website_Pipeline')) {
            wp_send_json_error(array('message' => 'Canonical website pipeline is required for template-based website generation.'), 500);
        }

        $template_prompt = sprintf(
            'Generate a complete premium standalone website from the current consultation profile. WordPress is only the VMO builder/staging shell; the generated site must run as plain HTML/CSS/JS without WordPress, shortcodes, wp-admin/admin-ajax/wp-json, or plugin asset dependencies. Use this requested template only as a visual starting point, never as a static template: template_id=%s, category=%s. The result must be a polished consultation-backed website draft with real business-specific sections, media planning, mobile readiness, SEO structure, portable integrations, and publish readiness gates.',
            $template_id,
            $category
        );

        $canonical_result = VMO_Canonical_Website_Pipeline::get_instance()->run_from_builder_prompt(0, $template_prompt);
        if (is_wp_error($canonical_result)) {
            wp_send_json_error(array('message' => $canonical_result->get_error_message()));
        }

        $website_draft = is_array($canonical_result['website_draft'] ?? null) ? $canonical_result['website_draft'] : array();
        $html = (string) ($canonical_result['content'] ?? $website_draft['homepage_html'] ?? $canonical_result['homepage_html'] ?? '');
        $new_balance = $current_balance - $token_cost;
        update_user_meta($user_id, 'vmo_token_balance', $new_balance);

        wp_send_json_success(array(
            'blocks' => array(array(
                'type' => 'canonical_website',
                'html' => $html,
                'id' => 'canonical-' . (int) ($website_draft['post_id'] ?? ($canonical_result['post_id'] ?? 0)),
            )),
            'website_draft' => $website_draft,
            'draft_id' => $website_draft['post_id'] ?? ($canonical_result['post_id'] ?? 0),
            'preview_url' => !empty($canonical_result['preview_ready']) ? ($website_draft['preview_url'] ?? ($canonical_result['preview_url'] ?? '')) : '',
            'preview_ready' => !empty($canonical_result['preview_ready']),
            'media_complete' => !empty($canonical_result['media_complete']),
            'final_qa_gate' => $canonical_result['final_qa_gate'] ?? ($website_draft['final_qa_gate'] ?? array()),
            'visual_preset' => $canonical_result['visual_preset'] ?? ($website_draft['visual_preset'] ?? ''),
            'canonical_pipeline' => true,
            'generation_mode' => 'canonical_template_request',
            'new_balance' => $new_balance,
            'message' => 'Template request generated through the canonical website pipeline',
        ));
    }

    public function handle_get_template_preview() {
        check_ajax_referer('vmo_builder_nonce', 'security');

        $template_id = sanitize_text_field(wp_unslash($_POST['template_id'] ?? ''));
        $category = sanitize_text_field(wp_unslash($_POST['category'] ?? ''));

        if ($template_id === '') {
            wp_send_json_error(array('message' => 'Template ID is required'));
        }

        $safe_id = preg_replace('/[^a-zA-Z0-9_-]/', '', $template_id);
        if ($safe_id !== $template_id) {
            wp_send_json_error(array('message' => 'Invalid template ID'));
        }

        $preview_path = VMO_AI_BUILDER_DIR . 'assets/templates/previews/' . $safe_id . '.html';
        if (file_exists($preview_path)) {
            wp_send_json_success(array(
                'preview_url' => VMO_AI_BUILDER_URL . 'assets/templates/previews/' . $safe_id . '.html',
                'category' => $category,
            ));
        }

        $template_data = $this->get_template_data($safe_id);
        if ($template_data) {
            wp_send_json_success(array(
                'preview_html' => $template_data['preview_html'],
                'template_name' => $template_data['name'],
                'category' => $category,
            ));
        }

        wp_send_json_error(array('message' => 'Template preview not found'));
    }

    private function get_template_data($template_id) {
        $previews = array(
            'modern-restaurant' => array(
                'name' => 'Modern Restaurant',
                'preview_html' => '<section class="vmo-template-preview"><h1>Modern Restaurant</h1><p>Cinematic food, reservations, menus, and local trust signals.</p></section>',
            ),
            'coffee-shop' => array(
                'name' => 'Coffee Shop',
                'preview_html' => '<section class="vmo-template-preview"><h1>Coffee Shop</h1><p>Warm product storytelling, community moments, menu highlights, and ordering paths.</p></section>',
            ),
            'corporate-modern' => array(
                'name' => 'Corporate Modern',
                'preview_html' => '<section class="vmo-template-preview"><h1>Corporate Modern</h1><p>Premium service positioning, proof, case sections, and consultation conversion.</p></section>',
            ),
            'design-agency' => array(
                'name' => 'Design Agency',
                'preview_html' => '<section class="vmo-template-preview"><h1>Design Agency</h1><p>Editorial portfolio storytelling, creative proof, and project inquiry flows.</p></section>',
            ),
        );

        return $previews[$template_id] ?? null;
    }
}

new VMO_Template_Handler();