<?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';
    // Prefer explicit user link; fallback to most recent updated
    $row = $wpdb->get_row(
        $wpdb->prepare("SELECT * FROM $table WHERE user_id = %d ORDER BY updated_at DESC, id DESC LIMIT 1", $user_id)
    );
    if (!$row) {
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $row = $wpdb->get_row("SELECT * FROM $table ORDER BY updated_at DESC, id DESC LIMIT 1");
    }
    return $row;
}

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) return true;

    $row = vmo_get_latest_consultation_by_user($user_id);
    if ($row && isset($row->status) && $row->status === 'implemented') return true;

    return false;
}

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 = json_decode($profile_json, true);
        if (is_array($data)) return $data;
    }

    $row = vmo_get_latest_consultation_by_user($user_id);
    if ($row && !empty($row->client_data)) {
        $data = json_decode($row->client_data, true);
        return is_array($data) ? $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();
    $ready = vmo_is_consultation_ready($user_id);
    $profile = $ready ? vmo_get_consultation_profile($user_id) : [];
    wp_send_json_success([
        'ready' => (bool)$ready,
        'profile_summary' => [
            'responses' => isset($profile['responses']) ? count((array)$profile['responses']) : 0,
            'agents' => isset($profile['agents']) ? array_keys((array)$profile['agents']) : [],
            'status' => $ready ? 'ready' : 'incomplete',
        ]
    ]);
});
