81 lines
2.8 KiB
PHP
81 lines
2.8 KiB
PHP
<?php
|
|
session_start();
|
|
require_once '../includes/db.php';
|
|
require_once '../includes/api_helper.php';
|
|
|
|
if (!isset($_SESSION['user_id'])) {
|
|
jsonResponse(false, 'Unauthorized', [], 401);
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
jsonResponse(false, 'Invalid request method');
|
|
}
|
|
|
|
$maintenance_record_id = $_POST['maintenance_record_id'] ?? null;
|
|
if (!$maintenance_record_id) {
|
|
jsonResponse(false, 'Missing maintenance_record_id');
|
|
}
|
|
|
|
if (!isset($_FILES['documents']) || empty($_FILES['documents']['name'][0])) {
|
|
jsonResponse(false, 'No files uploaded');
|
|
}
|
|
|
|
$uploadDir = '../uploads/maintenance/';
|
|
if (!is_dir($uploadDir)) {
|
|
mkdir($uploadDir, 0755, true);
|
|
}
|
|
|
|
$successFiles = [];
|
|
$errors = [];
|
|
|
|
foreach ($_FILES['documents']['tmp_name'] as $key => $tmp_name) {
|
|
if ($_FILES['documents']['error'][$key] === UPLOAD_ERR_OK) {
|
|
$original_name = basename($_FILES['documents']['name'][$key]);
|
|
$file_size = $_FILES['documents']['size'][$key];
|
|
$file_type = mime_content_type($tmp_name);
|
|
|
|
// Validate PDF
|
|
$ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
|
|
if ($ext !== 'pdf' || $file_type !== 'application/pdf') {
|
|
$errors[] = "$original_name ไม่ใช่ไฟล์ PDF";
|
|
continue;
|
|
}
|
|
|
|
// Max 10MB
|
|
if ($file_size > 10 * 1024 * 1024) {
|
|
$errors[] = "$original_name ขนาดเกิน 10MB";
|
|
continue;
|
|
}
|
|
|
|
// Generate unique filename
|
|
$new_filename = uniqid('maint_') . '_' . time() . '.pdf';
|
|
$dest_path = $uploadDir . $new_filename;
|
|
|
|
if (move_uploaded_file($tmp_name, $dest_path)) {
|
|
// Save to DB
|
|
try {
|
|
$stmt = $pdo->prepare("INSERT INTO maintenance_documents (maintenance_record_id, original_name, file_name, file_path) VALUES (?, ?, ?, ?)");
|
|
$relative_path = 'uploads/maintenance/' . $new_filename;
|
|
$stmt->execute([$maintenance_record_id, $original_name, $new_filename, $relative_path]);
|
|
$successFiles[] = $original_name;
|
|
} catch (PDOException $e) {
|
|
unlink($dest_path);
|
|
$errors[] = "DB Error for $original_name: " . $e->getMessage();
|
|
}
|
|
} else {
|
|
$errors[] = "ไม่สามารถบันทึกไฟล์ $original_name ได้";
|
|
}
|
|
}
|
|
}
|
|
|
|
if (count($successFiles) > 0) {
|
|
$msg = "อัปโหลดสำเร็จ " . count($successFiles) . " ไฟล์";
|
|
if (count($errors) > 0) {
|
|
$msg .= " (ไม่สำเร็จ " . count($errors) . " ไฟล์)";
|
|
}
|
|
jsonResponse(true, $msg);
|
|
} else {
|
|
jsonResponse(false, 'อัปโหลดไม่สำเร็จ: ' . implode(', ', $errors));
|
|
}
|
|
?>
|