begin_transaction(); // Get or create WBS $stmt = $conn->prepare("SELECT wbs_id FROM project_wbs WHERE project_id = ? AND activity_id = ?"); $stmt->bind_param('ii', $project_id, $activity_id); $stmt->execute(); $result = $stmt->get_result(); if ($row = $result->fetch_assoc()) { $wbs_id = $row['wbs_id']; } else { $wbs_code = 'WBS-' . str_pad($activity_id, 4, '0', STR_PAD_LEFT); $stmt = $conn->prepare("INSERT INTO project_wbs (project_id, activity_id, wbs_code, is_active) VALUES (?, ?, ?, 1)"); $stmt->bind_param('iis', $project_id, $activity_id, $wbs_code); $stmt->execute(); $wbs_id = $conn->insert_id; } // Prepare data for simplified system $date = $_POST['report_date']; $remarks = trim($_POST['remarks'] ?? ''); $delay = trim($_POST['delay_reason'] ?? ''); $status = in_array($_POST['status'] ?? '', ['Draft','Submitted','Approved','Rejected']) ? $_POST['status'] : 'Submitted'; // Insert report - simplified version (no shift, quantity, progress, manpower, weather, etc.) $sql = "INSERT INTO daily_reports ( project_id, area_id, wbs_id, engineer_id, report_date, remarks, delay_reason, status, submitted_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())"; $stmt = $conn->prepare($sql); $stmt->bind_param('iiiissss', $project_id, $area_id, $wbs_id, $engineer_id, $date, $remarks, $delay, $status ); if (!$stmt->execute()) { throw new Exception('Insert failed: ' . $stmt->error); } $report_id = $conn->insert_id; // Handle photos $photo_count = 0; $upload_dir = '/var/www/nangan.online/construction_reports/uploads/reports/' . date('Y/m/d') . '/'; if (!is_dir($upload_dir)) { mkdir($upload_dir, 0775, true); } foreach ($_FILES as $key => $file) { if (strpos($key, 'photo_') === 0 && $file['error'] === 0) { $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); if (in_array($ext, ['jpg','jpeg','png','gif'])) { $fname = 'report_' . $report_id . '_' . uniqid() . '.' . $ext; $fpath = $upload_dir . $fname; if (move_uploaded_file($file['tmp_name'], $fpath)) { $idx = str_replace('photo_', '', $key); $lat = isset($_POST["photo_{$idx}_lat"]) ? floatval($_POST["photo_{$idx}_lat"]) : null; $lng = isset($_POST["photo_{$idx}_lng"]) ? floatval($_POST["photo_{$idx}_lng"]) : null; $size = round(filesize($fpath)/1024, 2); $cap = "Photo " . ($photo_count+1); $ps = $conn->prepare("INSERT INTO report_photos (report_id, photo_filename, photo_path, photo_caption, gps_latitude, gps_longitude, file_size_kb) VALUES (?, ?, ?, ?, ?, ?, ?)"); $ps->bind_param('isssddd', $report_id, $fname, $fpath, $cap, $lat, $lng, $size); if ($ps->execute()) $photo_count++; } } } } $conn->commit(); echo json_encode([ 'success' => true, 'message' => 'Report submitted successfully', 'report_id' => $report_id, 'photos_uploaded' => $photo_count ]); } catch (Exception $e) { if (isset($conn)) $conn->rollback(); http_response_code(400); echo json_encode(['success' => false, 'message' => $e->getMessage()]); } if (isset($conn)) $conn->close(); ?>