37241-vm/api/vendors_post.php
2026-01-03 08:40:36 +00:00

61 lines
1.7 KiB
PHP

<?php
require_once __DIR__ . '/../includes/uuid.php';
require_once __DIR__ . '/../db/config.php';
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => '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()]);
}