38960-vm/api/pharmacy_lpo.php
2026-03-21 09:33:13 +00:00

94 lines
3.4 KiB
PHP

<?php
require_once __DIR__ . '/../db/config.php';
header('Content-Type: application/json');
$action = $_GET['action'] ?? '';
try {
$pdo = db();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ($action === 'create_lpo') {
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['supplier_id']) || empty($data['items'])) {
throw new Exception("Supplier and items are required.");
}
$pdo->beginTransaction();
$stmt = $pdo->prepare("INSERT INTO pharmacy_lpos (supplier_id, lpo_date, status, total_amount, notes) VALUES (?, ?, 'Draft', ?, ?)");
$stmt->execute([
$data['supplier_id'],
$data['lpo_date'] ?? date('Y-m-d'),
$data['total_amount'] ?? 0,
$data['notes'] ?? ''
]);
$lpoId = $pdo->lastInsertId();
$stmtItem = $pdo->prepare("INSERT INTO pharmacy_lpo_items (lpo_id, drug_id, quantity, cost_price, total_cost) VALUES (?, ?, ?, ?, ?)");
foreach ($data['items'] as $item) {
$stmtItem->execute([
$lpoId,
$item['drug_id'],
$item['quantity'],
$item['cost_price'],
$item['total_cost']
]);
}
$pdo->commit();
echo json_encode(['success' => true, 'message' => 'LPO created successfully']);
} elseif ($action === 'update_status') {
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['id']) || empty($data['status'])) {
throw new Exception("ID and Status are required");
}
$stmt = $pdo->prepare("UPDATE pharmacy_lpos SET status = ? WHERE id = ?");
$stmt->execute([$data['status'], $data['id']]);
echo json_encode(['success' => true]);
}
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
if ($action === 'get_lpos') {
$stmt = $pdo->query("
SELECT l.*, s.name_en as supplier_name
FROM pharmacy_lpos l
LEFT JOIN suppliers s ON l.supplier_id = s.id
ORDER BY l.created_at DESC
");
echo json_encode($stmt->fetchAll());
} elseif ($action === 'get_lpo_details') {
$id = $_GET['id'] ?? 0;
$stmt = $pdo->prepare("
SELECT i.*, d.name_en as drug_name, d.sku
FROM pharmacy_lpo_items i
LEFT JOIN drugs d ON i.drug_id = d.id
WHERE i.lpo_id = ?
");
$stmt->execute([$id]);
echo json_encode($stmt->fetchAll());
} elseif ($action === 'get_suppliers') {
$stmt = $pdo->query("SELECT id, name_en, name_ar FROM suppliers ORDER BY name_en ASC");
echo json_encode($stmt->fetchAll());
} elseif ($action === 'get_drugs') {
$stmt = $pdo->query("SELECT id, name_en, name_ar, sku, price FROM drugs ORDER BY name_en ASC");
echo json_encode($stmt->fetchAll());
}
}
} catch (Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}