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

function wpsec_scan_status_endpoint($request) {
    $scan_id = $request['id'];
    
    $status = get_option('wpsec_scan_' . $scan_id . '_status', 'unknown');
    $start_time = get_option('wpsec_scan_' . $scan_id . '_start', 0);
    $end_time = get_option('wpsec_scan_' . $scan_id . '_end', 0);
    $duration = get_option('wpsec_scan_' . $scan_id . '_duration', 0);
    $files_scanned = get_option('wpsec_scan_' . $scan_id . '_files_scanned', 0);
    $total_files = get_option('wpsec_scan_' . $scan_id . '_total_files', 0);
    $progress = get_option('wpsec_scan_' . $scan_id . '_progress', 0);
    
    // Normalize scanning/running status to ensure consistent API responses
    if ($status === 'scanning') {
        $status = 'running';
    }
    
    // Ensure we always have valid integer values for progress tracking
    $progress = intval($progress);
    $files_scanned = intval($files_scanned);
    $total_files = intval($total_files);
    
    $response = [
        'scan_id' => $scan_id,
        'status' => $status,
        'started_at' => gmdate('Y-m-d H:i:s', $start_time),
        'progress' => (string)$progress,
        'files_scanned' => (string)$files_scanned,
        'total_files' => (string)$total_files
    ];
    
    if ($status === 'completed') {
        $response['completed_at'] = gmdate('Y-m-d H:i:s', $end_time);
        $response['duration'] = $duration;
        $response['results_endpoint'] = rest_url('wpsec/v1/results');
    } else if ($status === 'running' || $status === 'scanning') {
        $current_time = time();
        $response['elapsed'] = $current_time - $start_time;
        $response['estimated_completion'] = gmdate('Y-m-d H:i:s', $start_time + get_option('wpsec_last_scan_duration', 300));
    }
    
    return rest_ensure_response($response);
}