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

/**
 * Lightweight Approval Queue for SEO/Email/Docs
 */

function vmo_queue_add($type, $payload, $title = null, $related_post_id = null, $notes = null) {
    global $wpdb;
    $table = $wpdb->prefix . 'vmo_approval_queue';
    $user_id = get_current_user_id();
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $inserted = $wpdb->insert($table, [
        'user_id' => $user_id,
        'type' => sanitize_key($type),
        'title' => $title ? sanitize_text_field($title) : null,
        'payload' => is_string($payload) ? $payload : wp_json_encode($payload),
        'related_post_id' => $related_post_id ? intval($related_post_id) : null,
        'status' => 'pending',
        'notes' => $notes ? sanitize_textarea_field($notes) : null,
        'created_at' => current_time('mysql'),
        'updated_at' => current_time('mysql'),
    ]);
    if (!$inserted) return new WP_Error('queue_insert_failed', 'Failed to add to approval queue');
    return $wpdb->insert_id;
}

function vmo_queue_list($status = 'pending', $type = null, $limit = 50, $offset = 0) {
    global $wpdb;
    $table = $wpdb->prefix . 'vmo_approval_queue';
    $user_id = get_current_user_id();
    $where = ['user_id = %d'];
    $params = [$user_id];
    if ($status) { $where[] = 'status = %s'; $params[] = $status; }
    if ($type) { $where[] = 'type = %s'; $params[] = $type; }
    $where_sql = implode(' AND ', $where);
    $sql = $wpdb->prepare("SELECT * FROM $table WHERE $where_sql ORDER BY created_at DESC LIMIT %d OFFSET %d", array_merge($params, [intval($limit), intval($offset)]));
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    return $wpdb->get_results($sql);
}

function vmo_queue_update_status($id, $status) {
    global $wpdb; $table = $wpdb->prefix . 'vmo_approval_queue';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    return $wpdb->update($table, [ 'status' => sanitize_key($status), 'updated_at' => current_time('mysql') ], [ 'id' => intval($id), 'user_id' => get_current_user_id() ]);
}

// AJAX: Add to queue
add_action('wp_ajax_vmo_queue_add', function() {
    check_ajax_referer('vmo_builder_nonce', 'security');
    $type = sanitize_key($_POST['type'] ?? 'other');
    $title = sanitize_text_field($_POST['title'] ?? '');
    $payload = wp_unslash($_POST['payload'] ?? '');
    $related = isset($_POST['related_post_id']) ? intval($_POST['related_post_id']) : null;
    $notes = sanitize_textarea_field($_POST['notes'] ?? '');
    $id = vmo_queue_add($type, $payload, $title ?: null, $related, $notes ?: null);
    if (is_wp_error($id)) wp_send_json_error(['message' => $id->get_error_message()]);
    wp_send_json_success(['id' => $id]);
});

// AJAX: List queue
add_action('wp_ajax_vmo_queue_list', function() {
    check_ajax_referer('vmo_builder_nonce', 'security');
    $status = sanitize_key($_GET['status'] ?? 'pending');
    $type = isset($_GET['type']) ? sanitize_key($_GET['type']) : null;
    $items = vmo_queue_list($status, $type);
    wp_send_json_success(['items' => $items]);
});

// AJAX: Approve / Reject
add_action('wp_ajax_vmo_queue_approve', function() {
    check_ajax_referer('vmo_builder_nonce', 'security');
    $id = intval($_POST['id'] ?? 0);
    if (!$id) wp_send_json_error(['message' => 'Missing id']);
    $ok = vmo_queue_update_status($id, 'approved');
    if ($ok === false) wp_send_json_error(['message' => 'Failed to approve']);
    // Auto-apply if payload contains SEO directives
    global $wpdb; $table = $wpdb->prefix . 'vmo_approval_queue';
    $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE id=%d AND user_id=%d", $id, get_current_user_id()));
    if ($row) {
        $payload = json_decode($row->payload, true);
        $live_id = intval($row->related_post_id);
        if ($payload && $live_id) {
            // meta title / description
            if (!empty($payload['meta_title'])) update_post_meta($live_id, 'vmo_seo_title', sanitize_text_field($payload['meta_title']));
            if (!empty($payload['meta_description'])) update_post_meta($live_id, 'vmo_seo_description', sanitize_textarea_field($payload['meta_description']));
            if (!empty($payload['json_ld'])) update_post_meta($live_id, 'vmo_seo_json_ld', wp_kses_post($payload['json_ld']));
            // canonical
            if (!empty($payload['canonical'])) update_post_meta($live_id, 'vmo_seo_canonical', esc_url_raw($payload['canonical']));
            // alt-text batch (array of {selector, alt} or image URLs)
            if (!empty($payload['alt_text']) && is_array($payload['alt_text'])) {
                $alts = array_map(function($i){
                    return [
                        'selector' => isset($i['selector']) ? sanitize_text_field($i['selector']) : null,
                        'alt' => isset($i['alt']) ? sanitize_text_field($i['alt']) : null,
                        'src' => isset($i['src']) ? esc_url_raw($i['src']) : null,
                    ];
                }, $payload['alt_text']);
                update_post_meta($live_id, 'vmo_alt_text_overrides', $alts);
            }
        }
    }
    wp_send_json_success(['updated' => true]);
});
add_action('wp_ajax_vmo_queue_reject', function() {
    check_ajax_referer('vmo_builder_nonce', 'security');
    $id = intval($_POST['id'] ?? 0);
    if (!$id) wp_send_json_error(['message' => 'Missing id']);
    $ok = vmo_queue_update_status($id, 'rejected');
    if ($ok === false) wp_send_json_error(['message' => 'Failed to reject']);
    wp_send_json_success(['updated' => true]);
});

?>
