<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// end paintops_fs()->is__premium_only()
/**
 * Instant, free, keyword-based guess of an expense category from a vendor
 * name (and optional note), covers the common painting-contractor
 * vendors without an API call. Returns one of the four categories, or ''
 * when nothing matches confidently (the AJAX handler then falls back to a
 * cheap AI call). "Rental" is checked before the paint/hardware list so
 * e.g. "Home Depot Tool Rental" reads as Equipment/Rental.
 */
function paintops_guess_expense_category(  string $vendor, string $note = ''  ) : string {
    $v = strtolower( trim( $vendor . ' ' . $note ) );
    if ( $v === '' ) {
        return '';
    }
    $has = function ( array $kws ) use($v) {
        foreach ( $kws as $kw ) {
            if ( strpos( $v, $kw ) !== false ) {
                return true;
            }
        }
        return false;
    };
    if ( $has( [
        'rental',
        'sunbelt',
        'united rent',
        'herc rent',
        'scaffold',
        'boom lift',
        'tool rent',
        'equipment rent',
        'sprayer rent'
    ] ) ) {
        return 'Equipment/Rental';
    }
    if ( $has( [
        'subcontract',
        'sub-contract',
        'subcontractor',
        'labor only',
        '1099'
    ] ) ) {
        return 'Subcontractor';
    }
    if ( $has( [
        'sherwin',
        'williams',
        'benjamin moore',
        'ppg',
        'behr',
        'dunn-edwards',
        'dunn edwards',
        'kelly-moore',
        'kelly moore',
        'home depot',
        'lowe',
        'menards',
        'ace hardware',
        'true value',
        'hardware',
        'paint',
        'supply',
        'supplies',
        'ferguson',
        'floor & decor',
        'sundries'
    ] ) ) {
        return 'Materials/Supplies';
    }
    return '';
}

// end paintops_fs()->is__premium_only()
/**
 * AJAX: suggest an expense category from a typed/selected vendor when the
 * estimator ISN'T scanning a receipt photo (the photo scan already fills
 * the category). Tries the free keyword map first; only on a miss does it
 * spend a cheap AI text call (shares the receipt_scan cap). Same
 * add-receipt permission as the rest of that page. Returns {category,
 * source: 'rule'|'ai', confidence}.
 */
function paintops_ajax_ai_suggest_expense_category() : void {
    if ( !check_ajax_referer( 'paintops_ai_suggest_category', 'nonce', false ) ) {
        wp_send_json_error( [
            'message' => 'That request could not be verified.',
        ], 403 );
    }
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- value is cast to a number, sanitization not applicable
    $job_id = (int) ($_POST['job_id'] ?? 0);
    if ( $job_id <= 0 || !function_exists( 'paintops_user_can_add_job_receipt' ) || !paintops_user_can_add_job_receipt( $job_id ) ) {
        wp_send_json_error( [
            'message' => 'You do not have permission for this.',
        ], 403 );
    }
    $vendor = sanitize_text_field( wp_unslash( $_POST['vendor'] ?? '' ) );
    $note = sanitize_text_field( wp_unslash( $_POST['note'] ?? '' ) );
    if ( trim( $vendor ) === '' && trim( $note ) === '' ) {
        wp_send_json_error( [
            'message' => 'No vendor to categorize.',
        ] );
    }
    // 1) Free keyword guess.
    $guess = ( function_exists( 'paintops_guess_expense_category' ) ? paintops_guess_expense_category( $vendor, $note ) : '' );
    if ( $guess !== '' ) {
        wp_send_json_success( [
            'category'   => $guess,
            'source'     => 'rule',
            'confidence' => 'high',
        ] );
    }
    // 2) AI fallback, premium build only. This handler ships free (the
    // keyword guess above is a free feature), but the AI categorizer and
    // cap framework exist only in the premium build, so probe for them;
    // in the free build every one of these probes is simply absent.
    if ( !function_exists( 'paintops_ai_ready' ) || !paintops_ai_ready() || !function_exists( 'paintops_ai_categorize_expense' ) || !function_exists( 'paintops_ai_usage_allowed' ) || !paintops_ai_usage_allowed( 'receipt_scan' ) ) {
        wp_send_json_success( [
            'category' => '',
            'source'   => 'none',
        ] );
    }
    $result = paintops_ai_categorize_expense( $vendor, $note );
    if ( is_wp_error( $result ) ) {
        wp_send_json_success( [
            'category' => '',
            'source'   => 'none',
        ] );
    }
    if ( function_exists( 'paintops_ai_usage_record' ) ) {
        paintops_ai_usage_record( 'receipt_scan' );
    }
    wp_send_json_success( [
        'category'   => $result['category'],
        'source'     => 'ai',
        'confidence' => $result['confidence'],
    ] );
}

add_action( 'wp_ajax_paintops_ai_suggest_expense_category', 'paintops_ajax_ai_suggest_expense_category' );
// end paintops_fs()->is__premium_only()