<?php
// process.php
// --------------------------------------
// 세션, DB 연결
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

// 1) 요청 파라미터
$tablename = $_REQUEST['tablename'] ?? '';
$mode      = $_REQUEST['mode']      ?? '';

// 2) JSON 헤더
header("Content-Type: application/json; charset=utf-8");

// 3) form 데이터 변수 매핑 (_request.php 내부에서
//    $num, $vendor_code, $vendor_name, ... $fixdate, $enddate 등 설정)
include "_request.php";

// 4) 검색용 태그(searchtag) 조합
$searchtag = trim(
    "$vendor_name $representative_name $address "
  . "$business_type $item_type $phone $mobile $email "
  . "$fax $manager_name $contact_info $note $is_deleted $represent "
  . "$secondordnum $PurchaseSales $debtAmount"
);

try {
    // -------------------------------
    // 5) MODE = update
    if ($mode === "update") {
        // update_log 갱신
        $update_log = date("Y-m-d H:i:s")
                    . " - {$_SESSION['name']} "
                    . $update_log
                    . "&#10";
        $pdo->beginTransaction();
        $sql = "UPDATE {$DB}.{$tablename} SET
            vendor_code=?, vendor_name=?, representative_name=?, address=?,
            business_type=?, item_type=?, phone=?, mobile=?, email=?,
            fax=?, manager_name=?, contact_info=?, note=?, represent=?, searchtag=?, update_log=?,
            parentnum=?, secondordnum=?, registdate=?, pid=?, ppw=?, paydate=?, secondordpaydate=?,
            baddebt=?, fixdate=?, enddate=?, progress_memo=?, PurchaseSales=?, debtAmount=?
          WHERE num=? LIMIT 1";
        $stmh = $pdo->prepare($sql);
        $stmh->execute([
            $vendor_code, $vendor_name, $representative_name, $address,
            $business_type, $item_type, $phone, $mobile, $email,
            $fax, $manager_name, $contact_info, $note, $represent, $searchtag, $update_log,
            $parentnum, $secondordnum, $registdate, $pid, $ppw, $paydate, $secondordpaydate,
            $baddebt, $fixdate, $enddate, $progress_memo, $PurchaseSales, $debtAmount,
            $num
        ]);
        $pdo->commit();
    }
    // -------------------------------
    // 6) MODE = insert
    elseif ($mode === "insert") {
        $update_log = date("Y-m-d H:i:s")
                    . " - {$_SESSION['name']} "
                    . $update_log
                    . "&#10";
        $pdo->beginTransaction();
        $sql = "INSERT INTO {$DB}.{$tablename} (
            vendor_code, vendor_name, representative_name, address,
            business_type, item_type, phone, mobile, email,
            fax, manager_name, contact_info, note, represent, searchtag, update_log,
            parentnum, secondordnum, registdate, pid, ppw, paydate, secondordpaydate,
            baddebt, fixdate, enddate, progress_memo, PurchaseSales, debtAmount
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmh = $pdo->prepare($sql);
        $stmh->execute([
            $vendor_code, $vendor_name, $representative_name, $address,
            $business_type, $item_type, $phone, $mobile, $email,
            $fax, $manager_name, $contact_info, $note, $represent, $searchtag, $update_log,
            $parentnum, $secondordnum, $registdate, $pid, $ppw, $paydate, $secondordpaydate,
            $baddebt, $fixdate, $enddate, $progress_memo, $PurchaseSales, $debtAmount
        ]);
        $pdo->commit();

        // 방금 생성된 num 값 가져오기
        $row = $pdo
            ->query("SELECT num FROM {$DB}.{$tablename} ORDER BY num DESC LIMIT 1")
            ->fetch(PDO::FETCH_ASSOC);
        $num = $row['num'] ?? $num;

        // secondordnum이 비어 있으면 새로 생성된 num을 대표코드로 설정
        if (empty($secondordnum)) {
            $pdo->beginTransaction();
            $pdo->prepare("UPDATE {$DB}.{$tablename} SET secondordnum=? WHERE num=? LIMIT 1")
                ->execute([$num, $num]);
            $pdo->commit();
        }
    }
    // -------------------------------
    // 7) MODE = delete
    elseif ($mode === "delete") {
        $pdo->beginTransaction();
        $pdo->prepare("UPDATE {$DB}.{$tablename} SET is_deleted=1 WHERE num=?")
            ->execute([$num]);
        $pdo->commit();

        // 삭제는 rowHtml이 필요 없으니 바로 JSON 리턴
        echo json_encode([
            'success' => true,
            'mode'    => 'delete',
            'num'     => $num
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    else {
        throw new Exception("알 수 없는 mode: {$mode}");
    }
}
catch (Exception $e) {
    // 트랜잭션 취소 및 에러 리턴
    $pdo->rollBack();
    echo json_encode([
        'success' => false,
        'message' => '오류: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// -------------------------------

// (8) 방금 작업한 레코드 다시 조회
$stmt = $pdo->prepare("SELECT * FROM {$DB}.{$tablename} WHERE num = ? LIMIT 1");
$stmt->execute([$num]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

// (9) 배열 → 변수로 풀기
extract($row, EXTR_OVERWRITE);

// (10) _row.php로 렌더링
ob_start();
include "_rowinput.php";
$rowHtml = ob_get_clean();

// (11) JSON 응답
echo json_encode([
    'success' => true,
    'mode'    => $mode,
    'num'     => $num,
    'rowHtml' => $rowHtml
], JSON_UNESCAPED_UNICODE);
exit;