'Method not allowed']); exit(); } $data = json_decode(file_get_contents('php://input'), true); if (empty($data['vendor_name'])) { http_response_code(400); echo json_encode(['error' => 'Vendor name is required']); exit(); } $pdo = db(); try { $pdo->beginTransaction(); // 1. Create subledger entry for the vendor $subledger_id = uuid_v4(); $stmt = $pdo->prepare("INSERT INTO subledgers (subledger_id, subledger_type, reference_id) VALUES (?, 'Vendor', ?)"); $vendor_id = uuid_v4(); // Generate vendor ID ahead of time to link it $stmt->execute([$subledger_id, $vendor_id]); // 2. Create the vendor $stmt = $pdo->prepare( "INSERT INTO vendors (vendor_id, subledger_id, vendor_name, contact_person, email, phone, address) VALUES (?, ?, ?, ?, ?, ?, ?)" ); $stmt->execute([ $vendor_id, $subledger_id, $data['vendor_name'], $data['contact_person'] ?? null, $data['email'] ?? null, $data['phone'] ?? null, $data['address'] ?? null ]); $pdo->commit(); // Fetch and return the created vendor data $stmt = $pdo->prepare("SELECT * FROM vendors WHERE vendor_id = ?"); $stmt->execute([$vendor_id]); $new_vendor = $stmt->fetch(PDO::FETCH_ASSOC); http_response_code(201); echo json_encode($new_vendor); } catch (PDOException $e) { $pdo->rollBack(); http_response_code(500); echo json_encode(['error' => 'Database error: ' . $e->getMessage()]); }