<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// Mock Data - 가상의 전자세금계산서 발행 내역
$invoices = [
    [
        "id" => "inv_001",
        "issueKey" => "BARO-2024-001",
        "supplierBizno" => "123-45-67890",
        "supplierName" => "(주)건축자재",
        "recipientBizno" => "987-65-43210",
        "recipientName" => "대박 건설(주)",
        "supplyDate" => "2024-11-01",
        "items" => [
            [
                "name" => "시멘트 50kg",
                "qty" => 100,
                "unitPrice" => 8000,
                "supplyAmt" => 800000,
                "vat" => 80000,
                "vatType" => "vat"
            ],
            [
                "name" => "철근 10mm",
                "qty" => 50,
                "unitPrice" => 12000,
                "supplyAmt" => 600000,
                "vat" => 60000,
                "vatType" => "vat"
            ]
        ],
        "totalSupplyAmt" => 1400000,
        "totalVat" => 140000,
        "total" => 1540000,
        "status" => "sent",
        "ntsReceiptNo" => "NTS-2024-001234",
        "memo" => "정기 납품",
        "createdAt" => "2024-11-01T10:30:00",
        "sentAt" => "2024-11-01T10:35:00"
    ],
    [
        "id" => "inv_002",
        "issueKey" => "BARO-2024-002",
        "supplierBizno" => "123-45-67890",
        "supplierName" => "(주)건축자재",
        "recipientBizno" => "111-22-33333",
        "recipientName" => "강남 부동산(주)",
        "supplyDate" => "2024-11-05",
        "items" => [
            [
                "name" => "도배지",
                "qty" => 200,
                "unitPrice" => 5000,
                "supplyAmt" => 1000000,
                "vat" => 100000,
                "vatType" => "vat"
            ]
        ],
        "totalSupplyAmt" => 1000000,
        "totalVat" => 100000,
        "total" => 1100000,
        "status" => "issued",
        "memo" => "",
        "createdAt" => "2024-11-05T14:20:00"
    ],
    [
        "id" => "inv_003",
        "issueKey" => "BARO-2024-003",
        "supplierBizno" => "123-45-67890",
        "supplierName" => "(주)건축자재",
        "recipientBizno" => "555-66-77777",
        "recipientName" => "성수 인테리어(주)",
        "supplyDate" => "2024-11-10",
        "items" => [
            [
                "name" => "타일 30x30",
                "qty" => 500,
                "unitPrice" => 3000,
                "supplyAmt" => 1500000,
                "vat" => 150000,
                "vatType" => "vat"
            ],
            [
                "name" => "접착제",
                "qty" => 20,
                "unitPrice" => 15000,
                "supplyAmt" => 300000,
                "vat" => 30000,
                "vatType" => "vat"
            ]
        ],
        "totalSupplyAmt" => 1800000,
        "totalVat" => 180000,
        "total" => 1980000,
        "status" => "sent",
        "ntsReceiptNo" => "NTS-2024-001567",
        "memo" => "긴급 납품",
        "createdAt" => "2024-11-10T09:15:00",
        "sentAt" => "2024-11-10T09:20:00"
    ]
];

// 삭제된 ID 목록 읽기
$deletedIdsFile = __DIR__ . '/deleted_ids.json';
$deletedIds = [];
if (file_exists($deletedIdsFile)) {
    $deletedContent = file_get_contents($deletedIdsFile);
    if ($deletedContent !== false) {
        $deletedIds = json_decode($deletedContent, true);
        if (!is_array($deletedIds)) {
            $deletedIds = [];
        }
    }
}

// 기본 mock 데이터에서 삭제된 항목 제외
$invoices = array_filter($invoices, function($invoice) use ($deletedIds) {
    return !in_array($invoice['id'] ?? '', $deletedIds);
});
$invoices = array_values($invoices); // 인덱스 재정렬

// 파일에서 저장된 데이터 읽기 (있는 경우)
$dataFile = __DIR__ . '/invoices_data.json';
if (file_exists($dataFile)) {
    $fileContent = file_get_contents($dataFile);
    if ($fileContent !== false) {
        $savedData = json_decode($fileContent, true);
        if (json_last_error() === JSON_ERROR_NONE && isset($savedData['invoices']) && is_array($savedData['invoices']) && count($savedData['invoices']) > 0) {
            // 저장된 데이터에서도 삭제된 항목 제외
            $savedData['invoices'] = array_filter($savedData['invoices'], function($invoice) use ($deletedIds) {
                return !in_array($invoice['id'] ?? '', $deletedIds);
            });
            $savedData['invoices'] = array_values($savedData['invoices']);
            
            // 저장된 데이터를 우선하고, 기본 mock 데이터와 병합
            // 저장된 데이터가 최신이므로 먼저 배치
            $invoices = array_merge($savedData['invoices'], $invoices);
            // 중복 제거 (id 기준) - 먼저 나온 것이 유지됨 (저장된 데이터 우선)
            $uniqueInvoices = [];
            $seenIds = [];
            foreach ($invoices as $invoice) {
                if (!in_array($invoice['id'], $seenIds)) {
                    $uniqueInvoices[] = $invoice;
                    $seenIds[] = $invoice['id'];
                }
            }
            $invoices = $uniqueInvoices;
        } elseif (json_last_error() !== JSON_ERROR_NONE) {
            error_log("invoices_data.json JSON 파싱 오류: " . json_last_error_msg());
        }
    } else {
        error_log("invoices_data.json 파일 읽기 실패: " . $dataFile);
    }
}

// 최신순 정렬
usort($invoices, function($a, $b) {
    return strtotime($b['createdAt'] ?? $b['supplyDate']) - strtotime($a['createdAt'] ?? $a['supplyDate']);
});

$response = [
    "success" => true,
    "invoices" => $invoices,
    "count" => count($invoices)
];

echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
?>

