Files
2026-09-16 23:20:08 +07:00

86 lines
3.3 KiB
PHP

<?php
// api/template_actions.php - Handle CRUD for templates
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
$input = $_POST;
}
$action = $input['action'] ?? '';
if (empty($action)) {
echo json_encode(['status' => 'error', 'message' => 'Missing action']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
if ($action === 'add_template') {
$agencyId = $input['agencyId'] ?? '';
$name = $input['name'] ?? '';
$categoryId = $input['categoryId'] ?? '';
$docNumFormat = $input['docNumFormat'] ?? '';
$title = $input['title'] ?? '';
$content = $input['content'] ?? '';
if(empty($agencyId) || empty($name)) {
echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
exit;
}
// Generate unique ID
$id = 'TPL-' . time() . rand(100, 999);
$stmt = $pdo->prepare("INSERT INTO templates (id, agency_id, name, category_id, doc_num_format, title, content) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$id, $agencyId, $name, $categoryId, $docNumFormat, $title, $content]);
echo json_encode(['status' => 'success', 'message' => 'เพิ่มแม่แบบด่วนเรียบร้อยแล้ว', 'id' => $id]);
}
elseif ($action === 'edit_template') {
$id = $input['id'] ?? '';
$agencyId = $input['agencyId'] ?? '';
$name = $input['name'] ?? '';
$categoryId = $input['categoryId'] ?? '';
$docNumFormat = $input['docNumFormat'] ?? '';
$title = $input['title'] ?? '';
$content = $input['content'] ?? '';
if(empty($id) || empty($name)) {
echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
exit;
}
$stmt = $pdo->prepare("UPDATE templates SET name = ?, category_id = ?, doc_num_format = ?, title = ?, content = ? WHERE id = ? AND (agency_id = ? OR ? = 'SUPER_ADMIN')");
$stmt->execute([$name, $categoryId, $docNumFormat, $title, $content, $id, $agencyId, $agencyId]);
echo json_encode(['status' => 'success', 'message' => 'แก้ไขแม่แบบด่วนเรียบร้อยแล้ว']);
}
elseif ($action === 'delete_template') {
$id = $input['id'] ?? '';
$agencyId = $input['agencyId'] ?? '';
if(empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'Missing template ID']);
exit;
}
$stmt = $pdo->prepare("DELETE FROM templates WHERE id = ? AND (agency_id = ? OR ? = 'SUPER_ADMIN')");
$stmt->execute([$id, $agencyId, $agencyId]);
echo json_encode(['status' => 'success', 'message' => 'ลบแม่แบบด่วนเรียบร้อยแล้ว']);
}
else {
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>