<?php
// save_biz.php - 사업자등록증 OCR 데이터 저장 API
header('Content-Type: application/json; charset=utf-8');
require_once(__DIR__ . '/../lib/mydb.php');
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");

// 권한 체크 (레벨 5 이하만 접근)
if ($level > 5) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => '접근 권한이 없습니다.']);
    exit;
}

// 사업자번호 정규화 (000-00-00000 형식)
function normalize_biz($v) {
    $d = preg_replace('/\D/', '', $v ?? '');
    return (strlen($d) === 10) ? substr($d, 0, 3) . '-' . substr($d, 3, 2) . '-' . substr($d, 5) : ($v ?? '');
}

// 사업자번호 검증 (체크섬)
function valid_biz_no($s) {
    $d = preg_replace('/\D/', '', $s ?? '');
    if (strlen($d) != 10) return false;
    
    $w = [1, 3, 7, 1, 3, 7, 1, 3, 5];
    $sum = 0;
    for ($i = 0; $i < 9; $i++) {
        $sum += intval($d[$i]) * $w[$i];
    }
    $sum += intdiv(intval($d[8]) * 5, 10);
    $check = (10 - ($sum % 10)) % 10;
    return $check == intval($d[9]);
}

// 날짜 정규화
function to_date($s) {
    if (!$s) return null;
    $d = preg_replace('/[년월.\-\/\s]+/', '-', $s);
    $d = preg_replace('/-+/', '-', $d);
    $d = rtrim($d, '-');
    
    if (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $d, $m)) {
        return sprintf('%04d-%02d-%02d', $m[1], $m[2], $m[3]);
    }
    return null;
}

// JSON 입력 받기
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Invalid JSON']);
    exit;
}

// 데이터 추출 및 검증
$biz_no = normalize_biz($input['biz_no'] ?? '');
$company_name = trim($input['company_name'] ?? '');
$representative = trim($input['representative'] ?? '');
$open_date = to_date($input['open_date'] ?? '');
$address = trim($input['address'] ?? '');
$type = trim($input['type'] ?? '');
$item = trim($input['item'] ?? '');
$issue_date = to_date($input['issue_date'] ?? '');
$raw_text = $input['raw_text'] ?? '';

// 필수값 체크
if (!$biz_no || !$company_name || !$representative) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => '필수값 누락 (사업자번호/상호명/대표자명)']);
    exit;
}

// 사업자번호 유효성 체크
$is_valid_biz = valid_biz_no($biz_no);

try {
    $pdo = db_connect();
    
    $stmt = $pdo->prepare("
        INSERT INTO biz_cert
        (biz_no, company_name, representative, open_date, address, type, item, issue_date, raw_text)
        VALUES (:biz_no, :company_name, :representative, :open_date, :address, :type, :item, :issue_date, :raw_text)
    ");
    
    $stmt->execute([
        ':biz_no' => $biz_no,
        ':company_name' => $company_name,
        ':representative' => $representative,
        ':open_date' => $open_date,
        ':address' => $address,
        ':type' => $type,
        ':item' => $item,
        ':issue_date' => $issue_date,
        ':raw_text' => $raw_text,
    ]);
    
    $id = $pdo->lastInsertId();
    
    echo json_encode([
        'ok' => true,
        'id' => $id,
        'valid_biz_no' => $is_valid_biz,
        'message' => $is_valid_biz ? '저장되었습니다.' : '저장되었으나 사업자번호 검증 실패 (수동 확인 필요)'
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => '데이터베이스 오류: ' . $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}

