130 lines
5.8 KiB
PHP
130 lines
5.8 KiB
PHP
<?php
|
|
require_once __DIR__ . '/db.php';
|
|
require_once __DIR__ . '/config.php';
|
|
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
echo json_encode(['success' => false, 'message' => 'Invalid request method']);
|
|
exit;
|
|
}
|
|
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$data) {
|
|
echo json_encode(['success' => false, 'message' => 'No data provided']);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
// Add vehicle_status column to history if it doesn't exist
|
|
try {
|
|
$pdo->exec("ALTER TABLE vehicle_inspections ADD COLUMN vehicle_status VARCHAR(50) NULL");
|
|
} catch (PDOException $e) {}
|
|
|
|
$pdo->beginTransaction();
|
|
|
|
// 1. Save Inspection History
|
|
$stmt = $pdo->prepare("
|
|
INSERT INTO vehicle_inspections
|
|
(vehicle_id, inspector_cid, inspection_date, inspection_time, mileage, fuel_level, other_items, items_json, vehicle_status)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
");
|
|
|
|
$stmt->execute([
|
|
$data['vehicle_id'],
|
|
$data['inspector_cid'],
|
|
$data['inspection_date'],
|
|
$data['inspection_time'],
|
|
$data['mileage'],
|
|
$data['fuel_level'],
|
|
$data['other_items'] ?? '',
|
|
json_encode($data['items'], JSON_UNESCAPED_UNICODE),
|
|
$data['vehicle_status'] ?? 'available'
|
|
]);
|
|
|
|
// 2. Update Vehicle Status
|
|
if (!empty($data['vehicle_status'])) {
|
|
$updateStmt = $pdo->prepare("UPDATE vehicles SET status = ? WHERE id = ?");
|
|
$updateStmt->execute([$data['vehicle_status'], $data['vehicle_id']]);
|
|
}
|
|
|
|
$pdo->commit();
|
|
|
|
// 3. Send Telegram Notification
|
|
if (defined('TELEGRAM_BOT_TOKEN') && defined('TELEGRAM_CHAT_ID') && !empty(TELEGRAM_BOT_TOKEN) && !empty(TELEGRAM_CHAT_ID)) {
|
|
// Get vehicle info
|
|
$vStmt = $pdo->prepare("SELECT license_plate, brand, model FROM vehicles WHERE id = ?");
|
|
$vStmt->execute([$data['vehicle_id']]);
|
|
$vehicle = $vStmt->fetch();
|
|
|
|
// Get driver info
|
|
$dStmt = $pdo->prepare("SELECT first_name, last_name FROM drivers WHERE hr_cid = ?");
|
|
$dStmt->execute([$data['inspector_cid']]);
|
|
$driver = $dStmt->fetch();
|
|
|
|
$vName = $vehicle ? trim("{$vehicle['brand']} {$vehicle['model']}") : "ID: {$data['vehicle_id']}";
|
|
$vPlate = $vehicle ? $vehicle['license_plate'] : "-";
|
|
|
|
// Use inspector_name from frontend payload if provided
|
|
$dName = !empty($data['inspector_name']) ? $data['inspector_name'] : ($driver ? "{$driver['first_name']} {$driver['last_name']}" : $data['inspector_cid']);
|
|
|
|
$abnormalCount = count(array_filter($data['items'], function($i) { return $i['status'] === 'abnormal'; }));
|
|
$statusText = $data['vehicle_status'] === 'available' ? '✅ พร้อมใช้งาน' : '❌ ไม่พร้อมใช้งาน/ส่งซ่อม';
|
|
|
|
// Convert date to Thai format (DD-MM-YYYY in BE)
|
|
$dateParts = explode('-', $data['inspection_date']);
|
|
$thaiDate = count($dateParts) == 3 ? $dateParts[2] . '-' . $dateParts[1] . '-' . ((int)$dateParts[0] + 543) : $data['inspection_date'];
|
|
|
|
$msg = "📋 <b>รายงานตรวจเช็ครถประจำวัน</b>\n\n";
|
|
$msg .= "🚗 <b>รถ:</b> {$vName}\n";
|
|
$msg .= "📝 <b>ทะเบียน:</b> {$vPlate}\n";
|
|
$msg .= "👤 <b>ผู้ตรวจ:</b> {$dName}\n";
|
|
$msg .= "📅 <b>วันที่:</b> {$thaiDate} เวลา {$data['inspection_time']} น.\n";
|
|
|
|
$formattedMileage = number_format((float)$data['mileage']);
|
|
$formattedFuel = number_format((float)$data['fuel_level'], 2); // Assuming fuel could have decimals, or we can use 0 decimals if preferred, but usually float is fine. Wait, let me just format it intelligently.
|
|
// If fuel_level has decimal part like .00, we might want to trim it, or just use number_format($data['fuel_level'], strpos($data['fuel_level'], '.') !== false ? 2 : 0)
|
|
// A simple way is to use float cast
|
|
$formattedFuel = rtrim(rtrim(number_format((float)$data['fuel_level'], 2, '.', ','), '0'), '.');
|
|
if ($formattedFuel === '') $formattedFuel = '0';
|
|
|
|
$msg .= "🛣️ <b>เลขไมล์:</b> {$formattedMileage} กม.\n";
|
|
$msg .= "⛽ <b>น้ำมัน:</b> {$formattedFuel} ลิตร\n";
|
|
$msg .= "📊 <b>สถานะรถ:</b> {$statusText}\n";
|
|
if ($abnormalCount > 0) {
|
|
$msg .= "\n⚠️ <b>พบจุดผิดปกติ {$abnormalCount} จุด:</b>\n";
|
|
foreach($data['items'] as $item) {
|
|
if($item['status'] === 'abnormal') {
|
|
$msg .= "- {$item['name']}: {$item['reason']}\n";
|
|
}
|
|
}
|
|
} else {
|
|
$msg .= "\n✨ <b>ผลการตรวจ:</b> ปกติทุกจุด";
|
|
}
|
|
|
|
$url = "https://api.telegram.org/bot" . TELEGRAM_BOT_TOKEN . "/sendMessage";
|
|
$tgData = [
|
|
'chat_id' => TELEGRAM_CHAT_ID,
|
|
'text' => $msg,
|
|
'parse_mode' => 'HTML'
|
|
];
|
|
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_URL, $url);
|
|
curl_setopt($ch, CURLOPT_POST, 1);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($tgData));
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
|
curl_exec($ch);
|
|
curl_close($ch);
|
|
}
|
|
|
|
echo json_encode(['success' => true, 'message' => 'บันทึกข้อมูลและอัปเดตสถานะรถเรียบร้อยแล้ว']);
|
|
} catch (PDOException $e) {
|
|
if ($pdo->inTransaction()) {
|
|
$pdo->rollBack();
|
|
}
|
|
echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
|
|
}
|