<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");  

if (!isset($_SESSION["level"]) || $_SESSION["level"] > 5) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => '권한이 없습니다.']);
    exit;
}

require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");

try {
    $pdo = db_connect();
    
    // POST 데이터 받기
    $work_date = isset($_POST['work_date']) ? $_POST['work_date'] : '';
    $work_order_no = isset($_POST['work_order_no']) ? $_POST['work_order_no'] : '';
    $work_type = isset($_POST['work_type']) ? $_POST['work_type'] : '';
    $worker = isset($_POST['worker']) ? $_POST['worker'] : '';
    $prod_code = isset($_POST['prod_code']) ? $_POST['prod_code'] : '';
    $spec_code = isset($_POST['spec_code']) ? $_POST['spec_code'] : '';
    $slength_code = isset($_POST['slength_code']) ? $_POST['slength_code'] : '';
    $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 0;
    $remark = isset($_POST['remark']) ? $_POST['remark'] : '';
    
    // 필수 필드 검증
    if (empty($work_date) || empty($prod_code) || empty($spec_code) || empty($slength_code) || $quantity <= 0) {
        throw new Exception('필수 항목이 누락되었습니다.');
    }
    
    // 데이터 삽입
    $sql = "INSERT INTO bending_work_log (work_date, work_order_no, work_type, worker, prod_code, spec_code, slength_code, quantity, remark) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $pdo->prepare($sql);
    $result = $stmt->execute([
        $work_date,
        $work_order_no,
        $work_type,
        $worker,
        $prod_code,
        $spec_code,
        $slength_code,
        $quantity,
        $remark
    ]);
    
    if ($result) {
        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'message' => '저장되었습니다.']);
    } else {
        throw new Exception('저장에 실패했습니다.');
    }
    
} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?> 