<?php

// includes/load-project.php
if (!defined('ABSPATH')) exit;

if (!function_exists('vmo_builder_reset_mode_active')) {
    function vmo_builder_reset_mode_active($user_id) {
        return (bool) get_user_meta($user_id, 'vmo_builder_reset_to_demo', true);
    }
}

if (!function_exists('vmo_builder_visible_project_meta_query')) {
    function vmo_builder_visible_project_meta_query() {
        return [
            'relation' => 'OR',
            [
                'key'     => 'vmo_builder_archived_by_reset',
                'compare' => 'NOT EXISTS',
            ],
            [
                'key'     => 'vmo_builder_archived_by_reset',
                'value'   => '1',
                'compare' => '!=',
            ],
        ];
    }
}

if (!function_exists('vmo_builder_normalize_preview_html')) {
    function vmo_builder_normalize_preview_html($html) {
        $value = is_string($html) ? $html : '';
        if ($value === '') {
            return '';
        }

        $value = preg_replace('/<!--[\s\S]*?-->/', '', $value);
        $value = preg_replace('/AI\s+Image\s+Generating\.\.\.?/i', '', $value);
        $value = preg_replace('/AI\s+Video\s+Generating\.\.\.?/i', '', $value);
        $value = preg_replace('/\bImage\s+generating\.\.\.?/i', '', $value);
        $value = preg_replace('/\bVideo\s+generating\.\.\.?/i', '', $value);
        $value = preg_replace('/A professional (?:image|video) will appear here\.?/i', '', $value);
        $value = preg_replace('/(^|[\r\n>])\s*[\'\"]?;>\s*(?=<|[\r\n]|$)/', '$1', $value);
        if (function_exists('vmo_builder_repair_stripped_shell_text')) {
            $value = vmo_builder_repair_stripped_shell_text($value);
        }

        return trim((string) $value);
    }
}

if (!function_exists('vmo_builder_looks_like_stripped_shell_text')) {
    function vmo_builder_looks_like_stripped_shell_text($html) {
        $value = is_string($html) ? trim($html) : '';
        if ($value === '' || preg_match('/<script\b|<style\b/i', $value)) {
            return false;
        }

        $score = 0;
        foreach (array('tailwind.config', ':root{--vmo-primary', '[data-vmo-animate]', '.vmo-overlay-container', '.vmo-fallback-page{', 'window.Lenis', 'window.gsap', 'document.querySelectorAll') as $marker) {
            if (stripos($value, $marker) !== false) {
                $score++;
            }
        }

        return $score >= 2 && (bool) preg_match('/<(?:div|header|main|section|article|footer)\b/i', $value);
    }
}

if (!function_exists('vmo_builder_repair_stripped_shell_text')) {
    function vmo_builder_repair_stripped_shell_text($html) {
        $value = is_string($html) ? $html : '';
        if ($value === '' || !vmo_builder_looks_like_stripped_shell_text($value)) {
            return $value;
        }

        $content_tag = '<(?:div|header|main|section|article|footer)\b';
        $value = preg_replace('/^\s*tailwind\.config\s*=\s*\{[\s\S]*?(?=' . $content_tag . ')/i', '', $value);
        $value = preg_replace('/^\s*:root\{--vmo-primary:[\s\S]*?(?=' . $content_tag . ')/i', '', $value);
        $value = preg_replace('/\s*\.vmo-fallback-page\{[\s\S]*$/i', '', $value);
        $value = preg_replace('/\s*\(function\(\)\{\s*["\']use strict["\'];[\s\S]*?\}\)\(\);\s*$/i', '', $value);

        return trim(is_string($value) ? $value : '');
    }
}

if (!function_exists('vmo_builder_looks_like_legacy_demo_html')) {
    function vmo_builder_looks_like_legacy_demo_html($html) {
        $normalized_html = vmo_builder_normalize_preview_html($html);
        $plain_text = strtolower(wp_strip_all_tags($normalized_html));
        $markers = [
            'welcome to virtual media office',
            'revolutionizing e-commerce solutions',
            'feature one',
            'feature two',
            'image generating',
            'video generating',
        ];
        $score = 0;

        if ($normalized_html === '') {
            return false;
        }

        if (preg_match('/vmo-premium-page|vmo-gjs-page|data-vmo-generated|id=["\']vmo-demo-showcase["\']|demo-hero-backdrop/i', $normalized_html)) {
            return false;
        }

        foreach ($markers as $marker) {
            if (strpos($plain_text, $marker) !== false) {
                $score++;
            }
        }

        $looks_broken = strpos($plain_text, 'image generating') !== false
            || strpos($plain_text, 'video generating') !== false
            || preg_match('/(^|[\s>])[\'\"]?;>/', $normalized_html);

        return $score >= 2 || ($looks_broken && $score >= 1);
    }
}

if (!function_exists('vmo_builder_decode_project_json')) {
    function vmo_builder_decode_project_json($value) {
        if (is_array($value)) {
            return $value;
        }

        if (!is_string($value) || trim($value) === '') {
            return [];
        }

        $decoded = json_decode($value, true);
        return is_array($decoded) ? $decoded : [];
    }
}

if (!function_exists('vmo_builder_extract_html_from_state')) {
    function vmo_builder_extract_html_from_state($state) {
        $decoded = vmo_builder_decode_project_json($state);
        $blocks = is_array($decoded['blocks'] ?? null) ? $decoded['blocks'] : [];
        if (!$blocks) {
            return '';
        }

        $html_parts = [];
        foreach ($blocks as $block) {
            if (is_array($block) && !empty($block['html']) && is_string($block['html'])) {
                $html_parts[] = $block['html'];
            }
        }

        return implode("\n", $html_parts);
    }
}

if (!function_exists('vmo_builder_extract_primary_page_html')) {
    function vmo_builder_extract_primary_page_html($pages_map) {
        $decoded = vmo_builder_decode_project_json($pages_map);
        if (!$decoded) {
            return '';
        }

        $candidate = $decoded['home'] ?? reset($decoded);
        if (is_string($candidate)) {
            return $candidate;
        }

        if (is_array($candidate)) {
            foreach (['html', 'content', 'markup'] as $key) {
                if (!empty($candidate[$key]) && is_string($candidate[$key])) {
                    return $candidate[$key];
                }
            }
        }

        return '';
    }
}

if (!function_exists('vmo_builder_resolve_project_html')) {
    function vmo_builder_resolve_project_html($html, $pages_map = [], $state = null) {
        $resolved = is_string($html) ? $html : '';

        if ($resolved === '' || vmo_builder_looks_like_legacy_demo_html($resolved)) {
            $pages_html = vmo_builder_extract_primary_page_html($pages_map);
            if ($pages_html !== '') {
                $resolved = $pages_html;
            }
        }

        if ($resolved === '') {
            $state_html = vmo_builder_extract_html_from_state($state);
            if ($state_html !== '') {
                $resolved = $state_html;
            }
        }

        return vmo_builder_normalize_preview_html($resolved);
    }
}

if (!function_exists('vmo_builder_build_state_from_project_payload')) {
    function vmo_builder_build_state_from_project_payload($project_id, $html, $state = null, $pages_map = []) {
        $resolved_state = vmo_builder_decode_project_json($state);
        $resolved_pages = vmo_builder_decode_project_json($pages_map);
        $normalized_html = vmo_builder_normalize_preview_html($html);

        if (empty($resolved_state['blocks']) && $normalized_html !== '') {
            $resolved_state['blocks'] = [[
                'id' => 'project_' . intval($project_id) . '_home',
                'html' => $normalized_html,
                'type' => 'restored_project',
            ]];
        }

        if (!empty($resolved_pages)) {
            if (empty($resolved_state['pagesMap'])) {
                $resolved_state['pagesMap'] = $resolved_pages;
            }
            if (empty($resolved_state['pageOrder'])) {
                $resolved_state['pageOrder'] = array_values(array_keys($resolved_pages));
            }
            if (empty($resolved_state['currentPage'])) {
                $resolved_state['currentPage'] = array_key_exists('home', $resolved_pages)
                    ? 'home'
                    : (($resolved_state['pageOrder'][0] ?? null));
            }
            $resolved_state['generatedFromConsultation'] = !empty($resolved_state['generatedFromConsultation']) || !empty($resolved_pages);
        }

        return $resolved_state;
    }
}

/**
 * AJAX: Return list of project titles
 */
add_action('wp_ajax_vmo_list_projects', function () {
    check_ajax_referer('vmo_builder_nonce', 'security');

    $user_id = get_current_user_id();
    if (vmo_builder_reset_mode_active($user_id)) {
        wp_send_json_success(['projects' => []]);
    }

    $projects = get_posts([
        'post_type'   => 'vmo_project',
        'author'      => $user_id,
        'post_status' => 'any',
        'numberposts' => -1,
        'orderby'     => 'modified',
        'order'       => 'DESC',
        'meta_query'  => vmo_builder_visible_project_meta_query(),
    ]);

    $names = array_map(function ($p) {
        return $p->post_title;
    }, $projects);

    wp_send_json_success(['projects' => $names]);
});

/**
 * AJAX: Load full project data by title
 */
add_action('wp_ajax_vmo_load_project', function () {
    check_ajax_referer('vmo_builder_nonce', 'security');

    global $wpdb;
    $user_id = get_current_user_id();
    $name = sanitize_text_field($_POST['name'] ?? '');

    if (vmo_builder_reset_mode_active($user_id)) {
        wp_send_json_error(['message' => 'Reset Builder mode is active. Restore a backup or generate a new site first.']);
    }

    if (!$name) {
        wp_send_json_error(['message' => 'Project name required.']);
    }

    // Load from post type
    $projects = get_posts([
        'post_type'   => 'vmo_project',
        'title'       => $name,
        'author'      => $user_id,
        'post_status' => 'any',
        'numberposts' => 1,
        'meta_query'  => vmo_builder_visible_project_meta_query(),
    ]);

    if (empty($projects)) {
        wp_send_json_error(['message' => 'Project not found in posts.']);
    }

    $project = $projects[0];
    $chat    = get_post_meta($project->ID, 'vmo_chat', true);
    $images  = get_post_meta($project->ID, 'vmo_images', true);
    $state   = get_post_meta($project->ID, 'vmo_state', true);
    $pages_map = get_post_meta($project->ID, 'vmo_pages_map', true);
    $live_id = get_post_meta($project->ID, 'vmo_live_page_id', true);

    // Load backup from DB table, now including chat and state_json
    $db_row = $wpdb->get_row($wpdb->prepare(
        "SELECT html, images, chat, state_json FROM {$wpdb->prefix}vmo_projects WHERE user_id = %d AND project_title = %s",
        $user_id, $name
    ));

    if ($db_row) {
        $html   = $db_row->html ?: $project->post_content;
        $images = maybe_unserialize($db_row->images);
        $chat   = $db_row->chat ?: $chat;
        $state  = $db_row->state_json ?: $state;
    } else {
        $html = $project->post_content;
    }

    $raw_html = get_post_meta($project->ID, 'vmo_project_raw_html', true);
    if (is_string($raw_html) && trim($raw_html) !== '' && vmo_builder_looks_like_stripped_shell_text($html) && !vmo_builder_looks_like_stripped_shell_text($raw_html)) {
        $html = $raw_html;
    }

    $html = vmo_builder_resolve_project_html($html, $pages_map, $state);
    $state = vmo_builder_build_state_from_project_payload($project->ID, $html, $state, $pages_map);

    wp_send_json_success([
        'id'         => $project->ID,
        'project_id' => $project->ID,
        'title'      => $project->post_title,
        'html'       => $html,
        'chat'       => is_array($chat) ? $chat : json_decode($chat, true),
        'images'     => is_array($images) ? $images : json_decode($images, true),
        'state'      => $state,
        'pages_map'  => vmo_builder_decode_project_json($pages_map),
    'live_page_id' => $live_id ? intval($live_id) : null,
        'updated_at' => get_post_meta($project->ID, 'vmo_last_updated', true)
    ]);
});

/**
 * Return full list of user projects
 */
add_action('wp_ajax_vmo_get_projects', function () {
    check_ajax_referer('vmo_nonce', 'security');

    $user_id = get_current_user_id();
    if (vmo_builder_reset_mode_active($user_id)) {
        wp_send_json_success([]);
    }

    $projects = get_posts([
        'post_type'   => 'vmo_project',
        'post_status' => ['publish', 'private'],
        'author'      => $user_id,
        'numberposts' => 20,
        'orderby'     => 'modified',
        'order'       => 'DESC',
        'meta_query'  => vmo_builder_visible_project_meta_query(),
    ]);

    $data = array_map(function($p) {
        return [
            'id'      => $p->ID,
            'project_id' => $p->ID,
            'title'   => $p->post_title,
            'html'    => $p->post_content,
            'chat'    => json_decode(get_post_meta($p->ID, 'vmo_chat', true), true),
            'images'  => json_decode(get_post_meta($p->ID, 'vmo_images', true), true),
            'state'   => json_decode(get_post_meta($p->ID, 'vmo_state', true), true),
            'updated' => get_post_meta($p->ID, 'vmo_last_updated', true),
        ];
    }, $projects);

    wp_send_json_success($data);
});

/**
 * AJAX: Get latest project (most recently modified) for current user
 */
add_action('wp_ajax_vmo_get_latest_project', function () {
    check_ajax_referer('vmo_builder_nonce', 'security');

    $user_id = get_current_user_id();
    if (vmo_builder_reset_mode_active($user_id)) {
        wp_send_json_success(['project' => null]);
    }

    $projects = get_posts([
        'post_type'   => 'vmo_project',
        'post_status' => ['publish', 'private', 'draft'],
        'author'      => $user_id,
        'numberposts' => 5,
        'orderby'     => 'modified',
        'order'       => 'DESC',
        'meta_query'  => vmo_builder_visible_project_meta_query(),
    ]);

    if (empty($projects)) {
        wp_send_json_success(['project' => null]);
    }

    $selected = null;
    foreach ($projects as $p) {
        $chat  = get_post_meta($p->ID, 'vmo_chat', true);
        $state = get_post_meta($p->ID, 'vmo_state', true);
        $images = get_post_meta($p->ID, 'vmo_images', true);
        $pages_map = get_post_meta($p->ID, 'vmo_pages_map', true);
        $live_id = get_post_meta($p->ID, 'vmo_live_page_id', true);
        $raw_html = get_post_meta($p->ID, 'vmo_project_raw_html', true);
        $source_html = is_string($raw_html) && trim($raw_html) !== '' && vmo_builder_looks_like_stripped_shell_text($p->post_content) && !vmo_builder_looks_like_stripped_shell_text($raw_html)
            ? $raw_html
            : $p->post_content;
        $html = vmo_builder_resolve_project_html($source_html, $pages_map, $state);

        if ($html === '' || vmo_builder_looks_like_legacy_demo_html($html)) {
            continue;
        }

        $selected = [
            'title'  => $p->post_title,
            'html'   => $html,
            'chat'   => is_array($chat) ? $chat : json_decode($chat, true),
            'state'  => vmo_builder_build_state_from_project_payload($p->ID, $html, $state, $pages_map),
            'images' => is_array($images) ? $images : json_decode($images, true),
            'pages_map' => vmo_builder_decode_project_json($pages_map),
            'id'     => $p->ID,
            'live_page_id' => $live_id ? intval($live_id) : null,
        ];
        break;
    }

    if (!$selected) {
        wp_send_json_success(['project' => null]);
        return;
    }

    wp_send_json_success([
        'project' => $selected
    ]);
});