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

105 lines
4.2 KiB
PHP

<?php
// api/save_news.php - PHP REST Endpoint to insert or update news in database
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/logger.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;
}
$id = $input['id'] ?? '';
$docNum = trim($input['docNum'] ?? $input['doc_num'] ?? '');
if ($docNum === '') $docNum = '-';
$title = trim($input['title'] ?? '');
$agencyId = $input['agencyId'] ?? $input['agency_id'] ?? '';
$categoryId = $input['categoryId'] ?? $input['category_id'] ?? '';
$date = $input['date'] ?? $input['publish_date'] ?? date('Y-m-d');
$content = trim($input['content'] ?? '');
$isPinned = !empty($input['isPinned']) || !empty($input['is_pinned']) ? 1 : 0;
$isUrgent = !empty($input['isUrgent']) || !empty($input['is_urgent']) ? 1 : 0;
$attachments = $input['attachments'] ?? [];
if (empty($title) || empty($agencyId) || empty($categoryId)) {
echo json_encode(['status' => 'error', 'message' => 'กรุณากรอกข้อมูลที่จำเป็นให้ครบถ้วน']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
$pdo->beginTransaction();
if (!empty($id)) {
// Update existing document
$stmt = $pdo->prepare("
UPDATE news
SET doc_num = ?, title = ?, agency_id = ?, category_id = ?, publish_date = ?, content = ?, is_pinned = ?, is_urgent = ?
WHERE id = ?
");
$stmt->execute([$docNum, $title, $agencyId, $categoryId, $date, $content, $isPinned, $isUrgent, $id]);
// Delete existing attachments to recreate
$delAttach = $pdo->prepare("DELETE FROM attachments WHERE news_id = ?");
$delAttach->execute([$id]);
$newsId = $id;
$message = 'บันทึกการแก้ไขข้อมูลลงในฐานข้อมูลเรียบร้อยแล้ว';
} else {
// Generate new ID
$countStmt = $pdo->query("SELECT COUNT(*) AS total FROM news");
$total = $countStmt->fetch()['total'] + 1;
$newsId = 'DOC-2026-' . str_pad($total, 3, '0', STR_PAD_LEFT);
$stmt = $pdo->prepare("
INSERT INTO news (id, doc_num, title, agency_id, category_id, publish_date, content, is_pinned, is_urgent, views)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
");
$stmt->execute([$newsId, $docNum, $title, $agencyId, $categoryId, $date, $content, $isPinned, $isUrgent]);
$message = 'เผยแพร่บันทึกข้อความลงในฐานข้อมูลเรียบร้อยแล้ว';
}
// Insert attachments
if (is_array($attachments) && count($attachments) > 0) {
$attachStmt = $pdo->prepare("
INSERT INTO attachments (news_id, file_name, file_type, file_size, file_url)
VALUES (?, ?, ?, ?, ?)
");
foreach ($attachments as $att) {
$fileName = trim($att['name'] ?? $att['file_name'] ?? '');
$fileType = $att['type'] ?? $att['file_type'] ?? 'pdf';
$fileSize = $att['size'] ?? $att['file_size'] ?? '1.0 MB';
$fileUrl = $att['url'] ?? $att['file_url'] ?? null;
if (!empty($fileName)) {
$attachStmt->execute([$newsId, $fileName, $fileType, $fileSize, $fileUrl]);
}
}
}
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
$actionType = $id ? 'UPDATE_NEWS' : 'CREATE_NEWS';
logActivity($pdo, $actionUserId, $actionUserName, $actionType, ['news_id' => $newsId, 'title' => $title]);
$pdo->commit();
echo json_encode(['status' => 'success', 'message' => $message, 'id' => $newsId], JSON_UNESCAPED_UNICODE);
} catch (\Exception $e) {
if (isset($pdo) && $pdo->inTransaction()) {
$pdo->rollBack();
}
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>