<?php
defined('ABSPATH') || exit;

function wpsec_get_scan_status_endpoint($request) {
    // Debug logging
    wpsec_debug_log('WPSEC Debug - Scan status endpoint called', 'debug');
    wpsec_debug_log('WPSEC Debug - Request: ' . print_r($request, true), 'debug');
    
    // Validate API key (double check)
    if (!wpsec_validate_api_key()) {
        wpsec_debug_log('WPSEC Debug - API key validation failed', 'debug');
        return new WP_Error(
            'rest_forbidden',
            'Sorry, you are not allowed to do that.',
            array('status' => 401)
        );
    }

    $scan_id = $request['scan_id'];
    
    // Validate scan ID format
    if (!preg_match('/^wpsec_[a-f0-9]+\.[0-9]+$/', $scan_id)) {
        wpsec_debug_log('WPSEC Debug - Invalid scan ID format: ' . $scan_id, 'debug');
        return new WP_Error(
            'rest_invalid_param',
            'Invalid scan ID format',
            array('status' => 400)
        );
    }
    
    // Get scan status
    $status = get_option('wpsec_scan_' . $scan_id . '_status', '');
    $start_time = get_option('wpsec_scan_' . $scan_id . '_start', 0);
    $files_scanned = get_option('wpsec_scan_' . $scan_id . '_files_scanned', 0);
    $total_files = get_option('wpsec_scan_' . $scan_id . '_total_files', 0);
    
    // CRITICAL FIX: Ensure files_scanned never exceeds total_files
    if ($files_scanned > $total_files && $total_files > 0) {
        wpsec_debug_log('⚠️ WPFort Status Endpoint: Correcting invalid file count - scanned: ' . $files_scanned . ', total: ' . $total_files, 'warning');
        $files_scanned = $total_files;
    }
    
    // Calculate progress based on files (don't use stored progress which might be wrong)
    if ($total_files > 0) {
        $progress = min(100, round((intval($files_scanned) / intval($total_files)) * 100));
    } else {
        $progress = 0;
    }
    
    // Force progress to 100% if scan is completed
    if ($status === 'completed') {
        $progress = 100;
    }
    
    wpsec_debug_log('📊 WPFort Status Debug: ' . $files_scanned . '/' . $total_files . ' = ' . $progress . '%', 'debug');
    
    if (empty($status)) {
        wpsec_debug_log('WPSEC Debug - Scan ID not found: ' . $scan_id, 'debug');
        return rest_ensure_response([
            'scan_id' => $scan_id,
            'status' => 'unknown',
            'started_at' => null,
            'message' => 'Scan not found or expired'
        ]);
    }
    
    wpsec_debug_log('WPSEC Debug - Scan status found: ' . $status, 'debug');
    
    $response = [
        'scan_id' => $scan_id,
        'status' => $status,
        'started_at' => gmdate('Y-m-d H:i:s', $start_time),
        'progress' => $progress,
        'files_scanned' => $files_scanned,
        'total_files' => $total_files,
        'results_endpoint' => rest_url('wpsec/v1/results')
    ];
    
    if ($status === 'completed') {
        // Try both possible end time option names for compatibility
        $end_time = get_option('wpsec_scan_' . $scan_id . '_end', null);
        if (!$end_time) {
            $end_time = get_option('wpsec_scan_' . $scan_id . '_completed_time', time());
        }
        $response['completed_at'] = gmdate('Y-m-d H:i:s', $end_time);
        $response['duration'] = $end_time - $start_time;
    }
    
    return rest_ensure_response($response);
}
