<?php
// eworks_process.php

require_once($_SERVER['DOCUMENT_ROOT'] . '/session.php');
header("Content-Type: application/json; charset=utf-8");

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

$DB         = 'chandj';
$planTable  = 'account_plan';

// 1) JSON 바디 파싱
$body  = json_decode(file_get_contents('php://input'), true);
$items = $body['items'] ?? [];

if (empty($items)) {
    echo json_encode([
        'success' => false,
        'message' => '전달된 지출 데이터가 없습니다.'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// 2) 공통 변수 세팅
$first          = $items[0];
$payDate        = $first['payDate'];            // payDate 키 사용
$indate         = $payDate;
$outdate        = $payDate;
$mytitle        = '일일지출내역서';             // 문서 제목
$content        = '';                           // 본문
$content_reason = '';                           // 사유
$first_writer   = $_SESSION['name'] . ' _' . date('Y-m-d H:i:s');
$author         = '정미영';                     // 결재 작성자
$author_id         = 'jmy';                     
$update_log     = date('Y-m-d H:i:s')
                  . ' - ' . $_SESSION['name']
                  . ' 일일지출내역서 발송&#10';
$suppliercost   = array_sum(array_column($items, 'amount'));
$store          = '';
$secondordnum   = '';
$secondordpaydate = $payDate;

// 3) eworks에 저장할 contents JSON
$eworks_contents = [
    'e_title'      => $mytitle,
    'indate'       => $indate,
    'author'       => $author,
    'expense_data' => $items,
];
$contents = json_encode($eworks_contents, JSON_UNESCAPED_UNICODE);

// 4) 결재라인 조회
try {
    $msql  = "SELECT first_approval_id, first_approval_name
              FROM {$DB}.member
              WHERE name = ?";
    $mstmt = $pdo->prepare($msql);
    $mstmt->execute([ $author ]);
    $member = $mstmt->fetch(PDO::FETCH_ASSOC) ?: [];
    $first_approval_id   = trim($member['first_approval_id']   ?? '');
    $first_approval_name = trim($member['first_approval_name'] ?? '');
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => '멤버 조회 오류: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// 5) 결재 상태 및 라인 결정
$status    = 'send';
$e_line_id = $first_approval_id;
$e_line    = $first_approval_name;

// 6) eworks 신규 등록 & account_plan 컬럼 업데이트
try {
    $pdo->beginTransaction();

    // 6a) eworks INSERT
    $sql = "INSERT INTO {$DB}.eworks (
                indate,
                outdate,
                outworkplace,
                request_comment,
                first_writer,
                author,
                update_log,
                contents,
                e_title,
                eworks_item,
                registdate,
                author_id,
                status,
                e_line_id,
                e_line,
                al_content,
                suppliercost,
                store,
                secondordnum,
                secondordpaydate
            ) VALUES (
                ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
            )";
            
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $indate,
        $outdate,
        $mytitle,
        $content_reason,
        $first_writer,
        $author,
        $update_log,
        $contents,
        $mytitle,
        $mytitle,               // eworks_item = 일일지출내역서
        date('Y-m-d H:i:s'),
        $author_id,
        $status,
        $e_line_id,
        $e_line,
        $content,               // al_content
        $suppliercost,
        $store,
        $secondordnum,
        $secondordpaydate
    ]);

    // 6b) 방금 등록된 eworks num 가져오기
    $eworksNum = $pdo->lastInsertId();

    // 6c) account_plan 3개 컬럼 업데이트
    $uSql = "UPDATE {$DB}.{$planTable}
             SET approvalRequest = ?,
                 eworksNum       = ?,
                 workDone        = ?
             WHERE num = ?
             LIMIT 1";
    $uStmt = $pdo->prepare($uSql);

    foreach ($items as $item) {
        $uStmt->execute([
            $indate,                // approvalRequest
            $eworksNum,
            $status === 'send' ? '요청중' : '완료',
            (int)$item['num']
        ]);
    }

    $pdo->commit();

    echo json_encode([
        'success'   => true,
        'message'   => count($items) . '건 결재요청 및 eworks 등록 완료',
        'eworksNum' => $eworksNum,
    ], JSON_UNESCAPED_UNICODE);

} catch (PDOException $e) {
    $pdo->rollBack();
    echo json_encode([
        'success' => false,
        'message' => 'DB 오류: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}