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

/**
 * Consultation Profile helpers and status endpoints
 */

function vmo_get_latest_consultation_by_user($user_id) {
    global $wpdb;
    $table = $wpdb->prefix . 'vmo_consultations';
    // Only return consultations that belong to the requested user.
    $row = $wpdb->get_row(
        $wpdb->prepare("SELECT * FROM $table WHERE user_id = %d ORDER BY updated_at DESC, id DESC LIMIT 1", $user_id)
    );
    return $row;
}

function vmo_decode_consultation_json($value) {
    if (is_array($value)) {
        return $value;
    }

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

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

function vmo_is_consultation_ready($user_id = 0) {
    $user_id = $user_id ?: get_current_user_id();
    if (!$user_id) return false;

    $flag = get_user_meta($user_id, 'vmo_consultation_ready', true);
    if ($flag === '1' || $flag === 1 || $flag === true) return true;

    $row = vmo_get_latest_consultation_by_user($user_id);
    if (!$row) return false;

    $status = strtolower((string) ($row->status ?? ''));
    if (in_array($status, ['completed', 'generating_media', 'implemented'], true)) {
        return true;
    }

    $website_data = vmo_decode_consultation_json($row->website_data ?? '');
    if (!empty($website_data['draft_assembled']) || !empty($website_data['generation_completed']) || !empty($website_data['media_complete']) || !empty($website_data['preview_ready'])) {
        return true;
    }

    $client_data = vmo_decode_consultation_json($row->client_data ?? '');
    return !empty($client_data['implementation']['website_code']);

}

function vmo_get_consultation_profile($user_id = 0) {
    $user_id = $user_id ?: get_current_user_id();
    if (!$user_id) return [];

    $profile_json = get_user_meta($user_id, 'vmo_business_profile', true);
    if ($profile_json) {
        $data = vmo_decode_consultation_json($profile_json);
        if ($data) return $data;
    }

    $row = vmo_get_latest_consultation_by_user($user_id);
    if ($row && !empty($row->client_data)) {
        return vmo_decode_consultation_json($row->client_data);
    }
    return [];
}

function vmo_require_profile_or_error($user_id = 0) {
    $user_id = $user_id ?: get_current_user_id();
    if (!vmo_is_consultation_ready($user_id)) {
        wp_send_json_error([
            'message' => 'Complete the Business Consultation to enable automated generation.',
            'code' => 'CONSULTATION_REQUIRED',
        ], 400);
    }
}

// AJAX: get consultation status
add_action('wp_ajax_vmo_get_consultation_status', function() {
    check_ajax_referer('vmo_builder_nonce', 'security');
    $user_id = get_current_user_id();
    $row = vmo_get_latest_consultation_by_user($user_id);
    $ready = vmo_is_consultation_ready($user_id);
    $profile = $ready ? vmo_get_consultation_profile($user_id) : [];
    $row_status = $row && !empty($row->status) ? (string) $row->status : 'incomplete';
    wp_send_json_success([
        'ready' => (bool)$ready,
        'consultation_status' => $row_status,
        'profile_summary' => [
            'responses' => isset($profile['responses']) ? count((array)$profile['responses']) : 0,
            'agents' => isset($profile['agents']) ? array_keys((array)$profile['agents']) : [],
            'status' => $ready ? $row_status : 'incomplete',
        ]
    ]);
});
