<?php
/**
 * Shared admin notes (team memos) for the ZERTI shell.
 */

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

const ZERTI_ADMIN_NOTES_OPTION = 'zerti_admin_notes';

/**
 * @return list<array{id:string,text:string,created:int,updated:int,author_id:int}>
 */
function zerti_get_admin_notes_raw(): array
{
    $stored = get_option(ZERTI_ADMIN_NOTES_OPTION, []);
    if (!is_array($stored)) {
        return [];
    }

    $out = [];
    foreach ($stored as $row) {
        if (!is_array($row)) {
            continue;
        }
        $id = isset($row['id']) ? sanitize_text_field((string) $row['id']) : '';
        $text = isset($row['text']) ? sanitize_textarea_field((string) $row['text']) : '';
        if ($id === '' || $text === '') {
            continue;
        }
        $out[] = [
            'id' => $id,
            'text' => $text,
            'created' => isset($row['created']) ? (int) $row['created'] : 0,
            'updated' => isset($row['updated']) ? (int) $row['updated'] : 0,
            'author_id' => isset($row['author_id']) ? absint($row['author_id']) : 0,
        ];
    }

    return $out;
}

/**
 * @param list<array{id:string,text:string,created:int,updated:int,author_id:int}> $notes
 */
function zerti_save_admin_notes_raw(array $notes): void
{
    update_option(ZERTI_ADMIN_NOTES_OPTION, array_values($notes), false);
}

/**
 * Resolve author display name for a user id.
 */
function zerti_admin_note_author_name(int $author_id): string
{
    if ($author_id <= 0) {
        return __('Unknown user', 'zerti');
    }
    $user = get_userdata($author_id);
    if (!$user instanceof WP_User) {
        return __('Unknown user', 'zerti');
    }
    $name = trim((string) $user->display_name);
    if ($name === '') {
        $name = trim((string) $user->user_login);
    }

    return $name !== '' ? $name : __('Unknown user', 'zerti');
}

/**
 * Format note timestamp for the admin UI.
 */
function zerti_admin_note_format_date(int $timestamp): string
{
    if ($timestamp <= 0) {
        return '';
    }
    if (function_exists('zerti_format_datetime')) {
        return zerti_format_datetime($timestamp, false);
    }
    if (function_exists('wp_date')) {
        $formatted = wp_date('Y/m/d H:i', $timestamp);
        return function_exists('zerti_localize_digits')
            ? zerti_localize_digits((string) $formatted)
            : (string) $formatted;
    }

    return (string) $timestamp;
}

/**
 * @param array{id:string,text:string,created:int,updated:int,author_id:int} $note
 * @return array{id:string,text:string,created:int,updated:int,author_id:int,author_name:string,date_label:string}
 */
function zerti_admin_note_for_client(array $note): array
{
    $ts = !empty($note['updated']) ? (int) $note['updated'] : (int) $note['created'];

    return [
        'id' => $note['id'],
        'text' => $note['text'],
        'created' => (int) $note['created'],
        'updated' => (int) $note['updated'],
        'author_id' => (int) $note['author_id'],
        'author_name' => zerti_admin_note_author_name((int) $note['author_id']),
        'date_label' => zerti_admin_note_format_date($ts),
    ];
}

/**
 * @return list<array{id:string,text:string,created:int,updated:int,author_id:int,author_name:string,date_label:string}>
 */
function zerti_get_admin_notes_for_client(): array
{
    $notes = zerti_get_admin_notes_raw();
    usort(
        $notes,
        static function (array $a, array $b): int {
            $ta = !empty($a['updated']) ? (int) $a['updated'] : (int) $a['created'];
            $tb = !empty($b['updated']) ? (int) $b['updated'] : (int) $b['created'];

            return $tb <=> $ta;
        }
    );

    return array_map('zerti_admin_note_for_client', $notes);
}

function zerti_ajax_admin_notes_guard(): void
{
    check_ajax_referer('zerti_admin_notes', 'nonce');

    if (!zerti_user_can_access_admin()) {
        wp_send_json_error(['message' => __('You do not have permission to access the ZERTI panel.', 'zerti')], 403);
    }
}

function zerti_ajax_admin_notes_list(): void
{
    zerti_ajax_admin_notes_guard();
    wp_send_json_success(['notes' => zerti_get_admin_notes_for_client()]);
}

function zerti_ajax_admin_note_save(): void
{
    zerti_ajax_admin_notes_guard();

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified via check_ajax_referer().
    $id = isset($_POST['id']) ? sanitize_text_field(wp_unslash((string) $_POST['id'])) : '';
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified via check_ajax_referer().
    $text = isset($_POST['text']) ? sanitize_textarea_field(wp_unslash((string) $_POST['text'])) : '';
    $text = trim($text);

    if ($text === '') {
        wp_send_json_error(['message' => __('Note text is required.', 'zerti')], 400);
    }

    $notes = zerti_get_admin_notes_raw();
    $now = time();
    $found = false;

    if ($id !== '') {
        foreach ($notes as $i => $note) {
            if ($note['id'] !== $id) {
                continue;
            }
            $notes[$i]['text'] = $text;
            $notes[$i]['updated'] = $now;
            $found = true;
            $id = $notes[$i]['id'];
            break;
        }
        if (!$found) {
            wp_send_json_error(['message' => __('Note not found.', 'zerti')], 404);
        }
    } else {
        $id = function_exists('wp_generate_uuid4') ? wp_generate_uuid4() : uniqid('n_', true);
        $notes[] = [
            'id' => $id,
            'text' => $text,
            'created' => $now,
            'updated' => $now,
            'author_id' => get_current_user_id(),
        ];
    }

    zerti_save_admin_notes_raw($notes);

    $saved = null;
    foreach (zerti_get_admin_notes_for_client() as $note) {
        if ($note['id'] === $id) {
            $saved = $note;
            break;
        }
    }

    wp_send_json_success([
        'note' => $saved,
        'notes' => zerti_get_admin_notes_for_client(),
        'message' => __('Note saved.', 'zerti'),
    ]);
}

function zerti_ajax_admin_note_delete(): void
{
    zerti_ajax_admin_notes_guard();

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified via check_ajax_referer().
    $id = isset($_POST['id']) ? sanitize_text_field(wp_unslash((string) $_POST['id'])) : '';
    if ($id === '') {
        wp_send_json_error(['message' => __('Note not found.', 'zerti')], 400);
    }

    $notes = zerti_get_admin_notes_raw();
    $next = [];
    $found = false;
    foreach ($notes as $note) {
        if ($note['id'] === $id) {
            $found = true;
            continue;
        }
        $next[] = $note;
    }

    if (!$found) {
        wp_send_json_error(['message' => __('Note not found.', 'zerti')], 404);
    }

    zerti_save_admin_notes_raw($next);

    wp_send_json_success([
        'notes' => zerti_get_admin_notes_for_client(),
        'message' => __('Note deleted.', 'zerti'),
    ]);
}

/**
 * Notes toggle under the license / Get Pro badge.
 */
function zerti_render_admin_notes_toggle(): void
{
    $count = count(zerti_get_admin_notes_raw());
    $count_label = function_exists('zerti_localize_digits')
        ? zerti_localize_digits((string) $count)
        : (string) $count;
    /* translators: %s: number of notes */
    $label = sprintf(__('Fast notes (%s)', 'zerti'), $count_label);
    ?>
    <div class="zerti-sidebar-notes-toggle-wrap">
        <button
            type="button"
            class="zerti-notes-toggle"
            data-zerti-notes-toggle
            aria-expanded="false"
            aria-controls="zertiNotesPanel"
        >
            <i class="fa-solid fa-sticky-note" aria-hidden="true"></i>
            <span class="zerti-notes-toggle__label" data-zerti-notes-toggle-label><?php echo esc_html($label); ?></span>
        </button>
    </div>
    <?php
}

/**
 * Shared notes slide-over panel (opposite the nav sidebar).
 */
function zerti_render_admin_notes_panel(): void
{
    ?>
    <div class="zerti-notes-backdrop" data-zerti-notes-backdrop hidden></div>
    <aside
        id="zertiNotesPanel"
        class="zerti-notes-panel"
        data-zerti-notes-panel
        hidden
        aria-hidden="true"
        aria-labelledby="zertiNotesPanelTitle"
    >
        <div class="zerti-notes-panel__inner">
            <div class="zerti-notes-panel__busy" data-zerti-notes-busy hidden aria-hidden="true">
                <span class="spinner-border text-primary" role="status" aria-hidden="true"></span>
                <span class="visually-hidden"><?php esc_html_e('Saving…', 'zerti'); ?></span>
            </div>
            <header class="zerti-notes-panel__header">
                <h2 id="zertiNotesPanelTitle" class="zerti-notes-panel__title"><?php esc_html_e('Notes', 'zerti'); ?></h2>
                <button type="button" class="zerti-notes-panel__close" data-zerti-notes-close aria-label="<?php echo esc_attr__('Close', 'zerti'); ?>">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </button>
            </header>
            <div class="zerti-notes-panel__body">
                <div class="zerti-notes-panel__list" data-zerti-notes-list></div>
                <p class="zerti-notes-panel__empty text-body-secondary small" data-zerti-notes-empty hidden>
                    <?php esc_html_e('No notes yet.', 'zerti'); ?>
                </p>
            </div>
            <div class="zerti-notes-panel__composer">
                <label class="visually-hidden" for="zertiNotesInput"><?php esc_html_e('Note text', 'zerti'); ?></label>
                <textarea
                    id="zertiNotesInput"
                    class="form-control zerti-notes-panel__input"
                    data-zerti-notes-input
                    rows="4"
                    placeholder="<?php echo esc_attr__('Write a note…', 'zerti'); ?>"
                ></textarea>
                <input type="hidden" data-zerti-notes-edit-id value="" />
                <div class="zerti-notes-panel__composer-actions">
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-zerti-notes-cancel hidden>
                        <?php esc_html_e('Cancel', 'zerti'); ?>
                    </button>
                    <button type="button" class="btn btn-primary btn-sm" data-zerti-notes-save>
                        <?php esc_html_e('Save', 'zerti'); ?>
                    </button>
                </div>
            </div>
        </div>
    </aside>
    <?php
}
