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

// Helper: verify security (accepts both admin and builder nonces)
if (!function_exists('vmo_verify_admin_security')) {
    function vmo_verify_admin_security(): bool {
        $nonce = sanitize_text_field(wp_unslash($_POST['security'] ?? $_POST['nonce'] ?? ''));
        if (!$nonce) return false;
        if (wp_verify_nonce($nonce, 'vmo_admin_nonce')) return true;
        if (wp_verify_nonce($nonce, 'vmo_builder_nonce')) return true;
        return false;
    }
}

// === Long-term Memory: Upsert ===
add_action('wp_ajax_vmo_memory_upsert', function() {
    if (!vmo_verify_admin_security()) {
        wp_send_json_error(['message' => 'Security check failed']);
    }
    $user_id = get_current_user_id();
    if (!$user_id) wp_send_json_error(['message' => 'Not logged in']);

    global $wpdb;
    $table = $wpdb->prefix . 'vmo_long_term_memory';

    $memory_type = isset($_POST['memory_type']) ? sanitize_text_field(wp_unslash($_POST['memory_type'])) : '';
    $memory_key  = isset($_POST['memory_key']) ? sanitize_text_field(wp_unslash($_POST['memory_key'])) : null;
    $importance  = isset($_POST['importance']) ? (int) $_POST['importance'] : 0;
    $content     = isset($_POST['content']) ? wp_kses_post(wp_unslash($_POST['content'])) : '';

    if (!$memory_type || !$content) {
        wp_send_json_error(['message' => 'Missing memory_type or content']);
    }

    $now = current_time('mysql');

    if ($memory_key) {
        // Upsert by (user_id, memory_key)
        $existing_id = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM $table WHERE user_id = %d AND memory_key = %s",
            $user_id, $memory_key
        ));
        if ($existing_id) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->update($table, [
                'memory_type' => $memory_type,
                'importance' => $importance,
                'content' => $content,
                'updated_at' => $now
            ], [ 'id' => $existing_id ], [ '%s', '%d', '%s', '%s' ], [ '%d' ]);
            wp_send_json_success(['id' => (int)$existing_id, 'action' => 'updated']);
        }
    }

    // Insert new
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->insert($table, [
        'user_id' => $user_id,
        'memory_type' => $memory_type,
        'memory_key' => $memory_key,
        'importance' => $importance,
        'content' => $content,
        'created_at' => $now
    ], [ '%d', '%s', '%s', '%d', '%s', '%s' ]);

    if ($wpdb->insert_id) {
        wp_send_json_success(['id' => (int)$wpdb->insert_id, 'action' => 'inserted']);
    }
    wp_send_json_error(['message' => 'Failed to insert memory']);
});

// === Long-term Memory: List ===
add_action('wp_ajax_vmo_memory_list', function() {
    if (!vmo_verify_admin_security()) {
        wp_send_json_error(['message' => 'Security check failed']);
    }
    $user_id = get_current_user_id();
    if (!$user_id) wp_send_json_error(['message' => 'Not logged in']);

    global $wpdb;
    $table = $wpdb->prefix . 'vmo_long_term_memory';

    $memory_type = isset($_POST['memory_type']) ? sanitize_text_field(wp_unslash($_POST['memory_type'])) : '';
    $limit = isset($_POST['limit']) ? max(1, min(100, (int)$_POST['limit'])) : 50;

    if ($memory_type) {
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table WHERE user_id = %d AND memory_type = %s ORDER BY importance DESC, updated_at DESC LIMIT %d",
            $user_id, $memory_type, $limit
        ), ARRAY_A);
    } else {
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table WHERE user_id = %d ORDER BY importance DESC, updated_at DESC LIMIT %d",
            $user_id, $limit
        ), ARRAY_A);
    }

    wp_send_json_success(['items' => $rows]);
});

// === Milestones: Create/Update ===
add_action('wp_ajax_vmo_milestone_upsert', function() {
    if (!vmo_verify_admin_security()) {
        wp_send_json_error(['message' => 'Security check failed']);
    }
    $user_id = get_current_user_id();
    if (!$user_id) wp_send_json_error(['message' => 'Not logged in']);

    global $wpdb;
    $table = $wpdb->prefix . 'vmo_roadmap_milestones';

    $id          = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $title       = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '';
    $target_date = isset($_POST['target_date']) ? sanitize_text_field(wp_unslash($_POST['target_date'])) : null;
    $owner       = isset($_POST['owner']) ? sanitize_text_field(wp_unslash($_POST['owner'])) : 'jarvis';
    $status      = isset($_POST['status']) ? sanitize_text_field(wp_unslash($_POST['status'])) : 'planned';
    $progress    = isset($_POST['progress']) ? max(0, min(100, (int)$_POST['progress'])) : 0;
    $notes       = isset($_POST['notes']) ? wp_kses_post(wp_unslash($_POST['notes'])) : '';

    if (!$title) {
        wp_send_json_error(['message' => 'Missing title']);
    }

    $data = [
        'user_id' => $user_id,
        'title' => $title,
        'target_date' => $target_date,
        'owner' => $owner,
        'status' => $status,
        'progress' => $progress,
        'notes' => $notes,
        'updated_at' => current_time('mysql')
    ];

    if ($id > 0) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->update($table, $data, [ 'id' => $id, 'user_id' => $user_id ]);
        wp_send_json_success(['id' => $id, 'action' => 'updated']);
    } else {
        $data['created_at'] = current_time('mysql');
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->insert($table, $data);
        if ($wpdb->insert_id) {
            wp_send_json_success(['id' => (int)$wpdb->insert_id, 'action' => 'inserted']);
        }
        wp_send_json_error(['message' => 'Failed to save milestone']);
    }
});

// === Milestones: List ===
add_action('wp_ajax_vmo_milestone_list', function() {
    if (!vmo_verify_admin_security()) {
        wp_send_json_error(['message' => 'Security check failed']);
    }
    $user_id = get_current_user_id();
    if (!$user_id) wp_send_json_error(['message' => 'Not logged in']);

    global $wpdb;
    $table = $wpdb->prefix . 'vmo_roadmap_milestones';
    $status = isset($_POST['status']) ? sanitize_text_field(wp_unslash($_POST['status'])) : '';
    $limit  = isset($_POST['limit']) ? max(1, min(100, (int)$_POST['limit'])) : 50;

    if ($status) {
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table WHERE user_id = %d AND status = %s ORDER BY target_date IS NULL, target_date ASC, updated_at DESC LIMIT %d",
            $user_id, $status, $limit
        ), ARRAY_A);
    } else {
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table WHERE user_id = %d ORDER BY target_date IS NULL, target_date ASC, updated_at DESC LIMIT %d",
            $user_id, $limit
        ), ARRAY_A);
    }

    wp_send_json_success(['items' => $rows]);
});
