<?php
require_once __DIR__ . '/cors_preflight_inc.php';
require_once '../../config.php';
require_once __DIR__ . '/jkex_bootstrap_inc.php';
jkex_bootstrap_daily_report_import();

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => 'POST method only'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    if (!is_array($data)) {
        throw new Exception('Invalid JSON payload');
    }

    if (empty($data['websiteId'])) {
        throw new Exception('缺少 websiteId');
    }

    $websiteId = intval($data['websiteId']);
    $dataType = isset($data['dataType']) && in_array($data['dataType'], ['normal', 'cutoff', 'closing'])
        ? $data['dataType']
        : 'normal';

    $urls = jkex_resolve_daily_report_import_urls($conn, $data);

    $results = [];
    foreach ($urls as $url) {
        try {
            $parsed = jkex_parse_daily_report_url($url);
            $apiData = jkex_fetch_api_json($url);
            if (($apiData['type'] ?? '') !== 'dailyreport') {
                throw new Exception('API 类型不是 dailyreport');
            }
            $mapped = jkex_build_daily_report_import_bundle(
                $conn,
                $apiData,
                $parsed,
                $websiteId,
                $dataType,
                $websiteId
            );
            $results[] = array_merge(['success' => true], $mapped);
        } catch (Exception $itemError) {
            $results[] = [
                'success' => false,
                'meta' => ['url' => $url],
                'message' => $itemError->getMessage(),
                'records' => [],
                'closingRecords' => [],
                'counts' => ['new' => 0, 'exists' => 0, 'changed' => 0, 'same' => 0],
                'closingCounts' => ['new' => 0, 'exists' => 0, 'changed' => 0, 'same' => 0],
            ];
        }
    }

    $summary = [
        'totalUrls' => count($urls),
        'successUrls' => 0,
        'failedUrls' => 0,
        'new' => 0,
        'exists' => 0,
        'changed' => 0,
        'same' => 0,
        'closingNew' => 0,
        'closingExists' => 0,
        'closingChanged' => 0,
        'closingSame' => 0,
    ];

    foreach ($results as $item) {
        if (!empty($item['success'])) {
            $summary['successUrls']++;
        } else {
            $summary['failedUrls']++;
        }
        if (!empty($item['counts']) && is_array($item['counts'])) {
            $summary['new'] += intval($item['counts']['new'] ?? 0);
            $summary['exists'] += intval($item['counts']['exists'] ?? 0);
            $summary['changed'] += intval($item['counts']['changed'] ?? 0);
            $summary['same'] += intval($item['counts']['same'] ?? 0);
        }
        if (!empty($item['closingCounts']) && is_array($item['closingCounts'])) {
            $summary['closingNew'] += intval($item['closingCounts']['new'] ?? 0);
            $summary['closingExists'] += intval($item['closingCounts']['exists'] ?? 0);
            $summary['closingChanged'] += intval($item['closingCounts']['changed'] ?? 0);
            $summary['closingSame'] += intval($item['closingCounts']['same'] ?? 0);
        }
    }

    echo json_encode([
        'success' => true,
        'summary' => $summary,
        'generatedUrlCount' => count($urls),
        'results' => $results,
    ], JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
    ], JSON_UNESCAPED_UNICODE);
}

if (isset($conn) && $conn) {
    mysqli_close($conn);
}
