<?php
/**
 * Notebook Stratégique : sauvegarde et récupération des brouillons par niveau (user_meta).
 * AJAX : avision_save_draft, avision_get_draft. Sécurisé par nonce avision_nonce.
 */

if (!defined('ABSPATH')) {
    exit;
}

class Avision_Draft {

    const META_PREFIX = 'avision_draft_level_';

    public static function init() {
        add_action('wp_ajax_avision_save_draft', array(__CLASS__, 'save_draft'));
        add_action('wp_ajax_avision_get_draft', array(__CLASS__, 'get_draft'));
        add_action('wp_ajax_nopriv_avision_get_draft', array(__CLASS__, 'get_draft'));
    }

    /**
     * Retourne l'ID niveau numérique à partir de levelId (ex: level2 -> 2).
     */
    private static function get_level_number($level_id) {
        if (preg_match('/^level(\d+)$/i', trim($level_id), $m)) {
            return max(1, min(21, (int) $m[1]));
        }
        return 0;
    }

    /**
     * AJAX : Enregistre le brouillon pour un niveau. POST: nonce, level_id, content.
     */
    public static function save_draft() {
        check_ajax_referer('avision_nonce', 'nonce');
        if (!is_user_logged_in()) {
            wp_send_json_error(array('error' => 'Non autorisé'));
            return;
        }
        $level_id = isset($_POST['level_id']) ? sanitize_text_field($_POST['level_id']) : '';
        $level_num = self::get_level_number($level_id);
        if ($level_num === 0) {
            wp_send_json_error(array('error' => 'Niveau invalide'));
            return;
        }
        $content = isset($_POST['content']) ? wp_unslash($_POST['content']) : '';
        if (!is_string($content)) {
            $content = '';
        }
        $content = wp_kses_post($content);
        $meta_key = self::META_PREFIX . $level_num;
        update_user_meta(get_current_user_id(), $meta_key, $content);
        wp_send_json_success(array('saved' => true));
    }

    /**
     * AJAX : Récupère le brouillon pour un niveau. POST: nonce, level_id.
     */
    public static function get_draft() {
        check_ajax_referer('avision_nonce', 'nonce');
        $meta_user_id = 0;
        if (is_user_logged_in()) {
            $meta_user_id = (int) get_current_user_id();
        } else {
            $profile_id = isset($_POST['profile_id']) ? (int) wp_unslash($_POST['profile_id']) : 0;
            $allowed = $profile_id > 0 && (
                (function_exists('avi_premium_report_request_uri_or_referer_authorizes_profile') && avi_premium_report_request_uri_or_referer_authorizes_profile($profile_id))
                || (function_exists('avi_premium_referer_allows_shared_profile_readonly') && avi_premium_referer_allows_shared_profile_readonly($profile_id))
                || (function_exists('avi_premium_shared_report_access_allowed_for_profile') && avi_premium_shared_report_access_allowed_for_profile($profile_id))
            );
            if (!$allowed) {
                wp_send_json_error(array('message' => 'unauthorized'), 401);
                return;
            }
            if (!function_exists('avi_mysql_profile_owner_ids_for_acl')) {
                wp_send_json_error(array('message' => 'unauthorized'), 401);
                return;
            }
            $owners = avi_mysql_profile_owner_ids_for_acl($profile_id);
            $meta_user_id = isset($owners['wp_user_id']) ? (int) $owners['wp_user_id'] : 0;
            if ($meta_user_id <= 0) {
                wp_send_json_success(array('content' => ''));
                return;
            }
        }
        $level_id = isset($_POST['level_id']) ? sanitize_text_field($_POST['level_id']) : '';
        $level_num = self::get_level_number($level_id);
        if ($level_num === 0) {
            wp_send_json_success(array('content' => ''));
            return;
        }
        $meta_key = self::META_PREFIX . $level_num;
        $content = get_user_meta($meta_user_id, $meta_key, true);
        if (!is_string($content)) {
            $content = '';
        }
        wp_send_json_success(array('content' => $content));
    }
}

Avision_Draft::init();
