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

82 lines
3.2 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');
}
$driver_id = $_POST['driver_id'] ?? '';
if (empty($driver_id)) {
jsonResponse(false, 'Driver ID is required');
}
// ตรวจสอบว่ามีไฟล์ส่งมาหรือไม่
if (!isset($_FILES['document']) || $_FILES['document']['error'] === UPLOAD_ERR_NO_FILE) {
jsonResponse(false, 'กรุณาเลือกไฟล์เอกสาร (PDF)');
}
$file = $_FILES['document'];
// ตรวจสอบ Error ของไฟล์
if ($file['error'] !== UPLOAD_ERR_OK) {
jsonResponse(false, 'เกิดข้อผิดพลาดในการอัปโหลดไฟล์: ' . $file['error']);
}
// ตรวจสอบประเภทไฟล์ (ต้องเป็น PDF เท่านั้น)
$fileType = mime_content_type($file['tmp_name']);
$allowedTypes = ['application/pdf'];
if (!in_array($fileType, $allowedTypes)) {
jsonResponse(false, 'อนุญาตให้อัปโหลดเฉพาะไฟล์ PDF เท่านั้น');
}
// ตรวจสอบขนาดไฟล์ (เช่น ไม่เกิน 5MB)
$maxSize = 5 * 1024 * 1024;
if ($file['size'] > $maxSize) {
jsonResponse(false, 'ขนาดไฟล์ต้องไม่เกิน 5MB');
}
// สร้างโฟลเดอร์สำหรับเก็บไฟล์ถ้ายังไม่มี
$uploadDir = '../uploads/driver_docs/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// สร้างชื่อไฟล์ใหม่เพื่อป้องกันชื่อซ้ำ และปัญหาภาษาไทย
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$newFileName = 'drv_' . $driver_id . '_' . time() . '_' . uniqid() . '.' . $extension;
$destination = $uploadDir . $newFileName;
$dbPath = 'uploads/driver_docs/' . $newFileName;
// ย้ายไฟล์ไปยังโฟลเดอร์ปลายทาง
if (move_uploaded_file($file['tmp_name'], $destination)) {
try {
// บันทึกข้อมูลลงฐานข้อมูล
$stmt = $pdo->prepare("INSERT INTO driver_documents (driver_id, original_name, file_name, file_path) VALUES (?, ?, ?, ?)");
$stmt->execute([
$driver_id,
$file['name'],
$newFileName,
$dbPath
]);
jsonResponse(true, 'อัปโหลดไฟล์สำเร็จ');
} catch (PDOException $e) {
// หากบันทึกฐานข้อมูลลบเหลว ให้ลบไฟล์ที่อัปโหลดไปแล้วด้วย
if (file_exists($destination)) {
unlink($destination);
}
jsonResponse(false, 'Database Error: ' . $e->getMessage());
}
} else {
jsonResponse(false, 'ไม่สามารถบันทึกไฟล์ได้ กรุณาลองใหม่อีกครั้ง');
}
?>