<?php
/**
 * 대량등록 모달에서 전달된 데이터를 account_plan 테이블에 저장
 */

ob_start();
header('Content-Type: application/json; charset=utf-8');

// 세션 및 권한 검사
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
if (!isset($_SESSION["level"]) || $_SESSION["level"] > 5) {
    ob_end_clean();
    echo json_encode(['status' => 'error', 'message' => '권한이 없습니다.']);
    exit;
}

// DB 연결
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

$DB        = 'chandj';
$tablename = 'account_plan';

// 클라이언트로부터 JSON 받기
$input = file_get_contents('php://input');
$data  = json_decode($input, true);

// 자바스크립트에서 _bulk는 제거되서 넘어옴       

if (empty($data['entries']) || !is_array($data['entries'])) {
    ob_end_clean();
    echo json_encode(['status' => 'error', 'message' => '저장할 데이터가 없습니다.']);
    exit;
}

try {
    $pdo->beginTransaction();

    $insertedCount = 0;
    $errors        = [];

    $sql = "INSERT INTO {$DB}.{$tablename} (
        registDate, inoutsep, content, amount, memo,
        ForeDate, first_writer, searchtag, update_log
    ) VALUES (
        :registDate, :inoutsep, :content, :amount, :memo,
        :ForeDate, :first_writer, :searchtag, :update_log
    )";
    $stmt = $pdo->prepare($sql);

    foreach ($data['entries'] as $entry) {
        // bulk 필드에서 원본 컬럼으로 매핑
        $registDate = $entry['registDate'] ?? date('Y-m-d');
        $inoutsep   = $entry['inoutsep']   ?? '';
        $content    = $entry['content']    ?? '';
        $amount     = str_replace(',', '', $entry['amount']) ?? '' ;
        $memo       = $entry['memo']       ?? '';
        $ForeDate   = $entry['ForeDate']   ?? '';


        // Construct the searchtag value
        $searchtag = $registDate . ' ' . $inoutsep . ' ' . $content . ' ' . $amount . $memo ;
        $first_writer = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] ;
        $update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . " " . $update_log . "&#10"; 

        $ok = $stmt->execute([
            ':registDate'   => $registDate,
            ':inoutsep'     => $inoutsep,
            ':content'      => $content,
            ':amount'       => $amount,
            ':memo'         => $memo,
            ':ForeDate'     => $ForeDate,
            ':first_writer' => $first_writer,
            ':searchtag'    => $searchtag,
            ':update_log'   => $update_log
        ]);

        if ($ok) {
            $insertedCount++;
        } else {
            $errors[] = "등록 실패: {$content} ({$registDate})";
        }
    }

    if (!empty($errors)) {
        $pdo->rollBack();
        ob_end_clean();
        echo json_encode([
            'status'  => 'error',
            'message' => '일부 저장 실패: ' . implode('; ', $errors)
        ]);
        exit;
    }

    $pdo->commit();
    ob_end_clean();
    echo json_encode([
        'status'        => 'success',
        'message'       => "{$insertedCount}건 저장 완료",
        'insertedCount'=> $insertedCount
    ]);
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    ob_end_clean();
    echo json_encode([
        'status'  => 'error',
        'message' => '서버 오류: ' . $e->getMessage()
    ]);
}
