Files
2026-06-06 10:05:39 +07:00

522 lines
22 KiB
PHP

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\operation;
use App\Models\photo;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use ZipArchive;
use App\Http\Controllers\RequestController;
class OperationController extends Controller
{
public function store(Request $request)
{
try {
// Validate the request data
$validated = $request->validate([
'nama' => 'required|string|max:255',
'tanggal_lahir' => 'required|date',
'umur' => 'required|integer',
'alamat' => 'required|string|max:255',
'suku' => 'required|string|max:255',
'kelamin' => 'required|string|in:Laki-laki,Perempuan',
'anak_ke' => 'required|integer',
'riwayathamil' => 'required|string',
'riwayatkeluarga' => 'required|string',
'riwayat_kawin_kerabat' => 'required|string',
'riwayat_penyakit_terdahulu' => 'required|string',
'kelainan_kongenital' => 'required|string|max:255',
'jenis_cleft' => 'required|string|in:sindromik,non_sindromik',
'jenis_terapi' => 'required|string|in:labioplasty,palatoplasty,gnatoplasty',
'diagnosa' => 'required|string|in:labioschisis,palatoschisis,labiopalatoschisis,labiognatoschisis,labiopalatognatoschisis',
'tanggal_operasi' => 'required|date',
'teknikoperasi' => 'required|string|max:255',
'operator' => 'required|string|max:255',
'lokasioperasi' => 'required|string|max:255',
'followup' => 'required|string',
'created_by_id' => 'required|integer',
'created_by_name' => 'required|string|max:255',
'photos_pre_op' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
'photos_post_op' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
'photos_kontrol' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
]);
// Check for existing operation with the same nama, tanggal_lahir, and tanggal_operasi
$existingOperation = operation::where('nama', $validated['nama'])
->where('tanggal_lahir', $validated['tanggal_lahir'])
->where('tanggal_operasi', $validated['tanggal_operasi'])
// ->where('teknikoperasi', $validated['teknikoperasi'])
->first();
if ($existingOperation) {
return redirect()->back()->with('error', 'Terdapat data dengan Nama Pasien, Tanggal lahir, Tanggal operasi yang sama, Pastikan Data yang diinput bukan duplikat')->withInput();
}
// Create the operation
$operation = operation::create($validated);
// Handle photo uploads
$categories = ['pre_op', 'post_op', 'kontrol'];
foreach ($categories as $category) {
if ($request->hasFile("photos_$category")) {
$file = $request->file("photos_$category");
$fileName = time() . '_' . $category . '.' . $file->getClientOriginalExtension();
$file->move(public_path('photos'), $fileName);
photo::create([
'operation_id' => $operation->id,
// 'gambar' => 'photos/' . $fileName,
// Kalo pake server humic yang aneh pake yang dibawah ini, yang atas ini dikomen
'gambar' => 'public/photos/' . $fileName,
'kategori' => $category,
]);
}
}
return redirect()->route('upload_data')->with('success', 'Operation created successfully!');
} catch (\Exception $e) {
return redirect()->back()->with('error', 'An error occurred while creating the operation. ' . $e->getMessage());
}
}
public function index(Request $request)
{
$query = Operation::query();
if ($request->filled('pengunggah')) {
$query->where('created_by_name', 'like', '%' . $request->pengunggah . '%');
}
if ($request->filled('teknik')) {
$query->where('teknikoperasi', 'like', '%' . $request->teknik . '%');
}
if ($request->filled('gender') && $request->gender !== 'Semua') {
$query->where('kelamin', $request->gender);
}
if ($request->filled('umur_min')) {
$query->where('umur', '>=', $request->umur_min);
}
if ($request->filled('umur_max')) {
$query->where('umur', '<=', $request->umur_max);
}
if ($request->filled('nama_pasien')) {
$query->where('nama', 'like', '%' . $request->nama_pasien . '%');
}
$totalCount = $query->count();
$operations = $query->orderBy('created_at', 'desc')->simplePaginate(15);
$displayedCount = $operations->count();
return view('browse_data', compact('operations', 'totalCount', 'displayedCount'));
}
public function mydata(Request $request)
{
$userId = auth()->user()->id;
$query = Operation::where('created_by_id', $userId);
if ($request->filled('nama_pasien')) {
$query->where('nama', 'like', '%' . $request->nama_pasien . '%');
}
if ($request->filled('teknik')) {
$query->where('teknikoperasi', 'like', '%' . $request->teknik . '%');
}
if ($request->filled('gender') && $request->gender !== 'Semua') {
$query->where('kelamin', $request->gender);
}
if ($request->filled('umur_min')) {
$query->where('umur', '>=', $request->umur_min);
}
if ($request->filled('umur_max')) {
$query->where('umur', '<=', $request->umur_max);
}
$totalCount = $query->count();
$operations = $query->orderBy('created_at', 'desc')->simplePaginate(15);
$displayedCount = $operations->count();
return view('my_data', compact('operations', 'totalCount', 'displayedCount'));
}
public function edit(operation $operation)
{
// Check if the current authenticated user is the creator of the operation
if ($operation->created_by_id == Auth::id()) {
$preOpPhoto = photo::where('operation_id', $operation->id)->where('kategori', 'pre_op')->first();
$kontrolPhoto = photo::where('operation_id', $operation->id)->where('kategori', 'kontrol')->first();
$postOpPhoto = photo::where('operation_id', $operation->id)->where('kategori', 'post_op')->first();
return view('edit_data', compact('operation', 'preOpPhoto', 'kontrolPhoto', 'postOpPhoto'));
}
// If the user is not the creator, you can redirect them or show an error message
return redirect()->route('dashboard')->with('error', 'You do not have permission to edit this operation.');
}
public function update(Request $request, operation $operation)
{
// Check if the current authenticated user is the creator of the operation
if ($operation->created_by_id != Auth::id()) {
return redirect()->route('dashboard')->with('error', 'You do not have permission to update this operation.');
}
try{
// Validate the request data
$validated = $request->validate([
'nama' => 'required|string|max:255',
'tanggal_lahir' => 'required|date',
'umur' => 'required|integer',
'alamat' => 'required|string|max:255',
'suku' => 'required|string|max:255',
'kelamin' => 'required|string|in:Laki-laki,Perempuan',
'anak_ke' => 'required|integer',
'riwayathamil' => 'required|string',
'riwayatkeluarga' => 'required|string',
'riwayat_kawin_kerabat' => 'required|string',
'riwayat_penyakit_terdahulu' => 'required|string',
'kelainan_kongenital' => 'required|string|max:255',
'jenis_cleft' => 'required|string|in:sindromik,non_sindromik',
'jenis_terapi' => 'required|string|in:labioplasty,palatoplasty,gnatoplasty',
'diagnosa' => 'required|string|in:labioschisis,palatoschisis,labiopalatoschisis,labiognatoschisis,labiopalatognatoschisis',
'tanggal_operasi' => 'required|date',
'teknikoperasi' => 'required|string|max:255',
'operator' => 'required|string|max:255',
'lokasioperasi' => 'required|string|max:255',
'followup' => 'required|string',
'photos_pre_op' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
'photos_post_op' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
'photos_kontrol' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
]);
// Update the operation
$operation->update($validated);
// Handle photo uploads
$categories = ['pre_op', 'post_op', 'kontrol'];
foreach ($categories as $category) {
if ($request->hasFile("photos_$category")) {
$file = $request->file("photos_$category");
$fileName = time() . '_' . $category . '.' . $file->getClientOriginalExtension();
// Find existing photo or create a new one
$photo = photo::where('operation_id', $operation->id)->where('kategori', $category)->first();
if ($photo) {
// Delete the old photo file
if (File::exists(public_path($photo->gambar))) {
File::delete(public_path($photo->gambar));
}
// Update the photo record
$file->move(public_path('photos'), $fileName);
// $photo->update(['gambar' => 'photos/' . $fileName]);
// Kalo pake server humic yang aneh pake yang dibawah ini, yang atas ini dikomen
$photo->update(['gambar' => 'public/photos/' . $fileName]);
} else {
// Create a new photo record
$file->move(public_path('photos'), $fileName);
photo::create([
'operation_id' => $operation->id,
// 'gambar' => 'photos/' . $fileName,
// Kalo pake server humic yang aneh pake yang dibawah ini, yang atas ini dikomen
'gambar' => 'public/photos/' . $fileName,
'kategori' => $category,
]);
}
}
}
return redirect()->route('my_data')->with('success', 'Operation updated successfully!');
} catch (\Exception $e) {
return redirect()->back()->with('error', 'An error occurred while updating the operation. ' . $e->getMessage());
}
}
public function show($id)
{
$operation = operation::findOrFail($id);
$preOpPhoto = photo::where('operation_id', $operation->id)->where('kategori', 'pre_op')->first();
$kontrolPhoto = photo::where('operation_id', $operation->id)->where('kategori', 'kontrol')->first();
$postOpPhoto = photo::where('operation_id', $operation->id)->where('kategori', 'post_op')->first();
return view('specific_data', compact('operation', 'preOpPhoto', 'kontrolPhoto', 'postOpPhoto'));
}
public function request_data($id)
{
$operation = operation::findOrFail($id);
return view('request_specific_data', compact('operation'));
}
// public function store_request_data(Request $request)
// {
// // Validate the request data
// $validated = $request->validate([
// 'nama_lengkap' => 'required|string|max:255',
// 'nomor_handphone' => 'required|integer',
// 'email' => 'required|string',
// 'nik' => 'required|integer',
// 'jenis_pengajuan' => 'required|string',
// 'tujuan_permohonan' => 'required|string',
// ]);
// // Create the request
// $operation = Operation::create([
// ]);
// return redirect()->route('upload_data')->with('success', 'Operation created successfully!');
// }
public function destroy(operation $operation)
{
// Check if the user has permission to delete this operation
if ($operation->created_by_id != Auth::id()) {
return redirect()->back()->with('error', 'You do not have permission to delete this operation.');
}
try {
DB::beginTransaction();
// Delete related photos first
photo::where('operation_id', $operation->id)->delete();
// Now delete the operation
$operation->delete();
DB::commit();
return redirect()->route('my_data')->with('success', 'Operation and related photos deleted successfully.');
} catch (\Exception $e) {
DB::rollBack();
return redirect()->back()->with('error', 'An error occurred while deleting the operation. ' . $e->getMessage());
}
}
public function download($id)
{
$operation = operation::findOrFail($id);
// Create a text file with operation data
$textContent = "";
foreach ($operation->getAttributes() as $key => $value) {
if (!in_array($key, ['id', 'created_by_id'])) {
$textContent .= ucfirst(str_replace('_', ' ', $key)) . ": " . $value . "\n";
}
}
$zipFileName = "operation_{$id}_data.zip";
$zipFilePath = storage_path("app/{$zipFileName}");
$zip = new \ZipArchive();
if ($zip->open($zipFilePath, \ZipArchive::CREATE) === TRUE) {
$zip->addFromString('operation_data.txt', $textContent);
// Add photos to the zip file
$photoCategories = ['pre_op', 'post_op'];
foreach ($photoCategories as $category) {
$photo = photo::where('operation_id', $operation->id)
->where('kategori', $category)
->first();
if ($photo) {
// Remove 'public/' from the beginning of the path
$relativePath = str_replace('public/', '', $photo->gambar);
$photoPath = public_path($relativePath);
if (file_exists($photoPath)) {
$zip->addFile($photoPath, $category . '_photo.' . pathinfo($photoPath, PATHINFO_EXTENSION));
}
}
}
$zip->close();
}
return response()->download($zipFilePath)->deleteFileAfterSend(true);
}
public function downall(Request $request)
{
function getExcelColumn($n) {
$string = '';
while ($n > 0) {
$n--;
$string = chr(65 + ($n % 26)) . $string;
$n = intdiv($n, 26);
}
return $string;
}
$query = Operation::query();
// Apply filters if they exist
if ($request->filled('pengunggah')) {
$query->where('created_by_name', 'like', '%' . $request->pengunggah . '%');
}
if ($request->filled('teknik')) {
$query->where('teknikoperasi', 'like', '%' . $request->teknik . '%');
}
if ($request->filled('gender') && $request->gender !== 'Semua') {
$query->where('kelamin', $request->gender);
}
if ($request->filled('umur_min')) {
$query->where('umur', '>=', $request->umur_min);
}
if ($request->filled('umur_max')) {
$query->where('umur', '<=', $request->umur_max);
}
if ($request->filled('nama_pasien')) {
$query->where('nama', 'like', '%' . $request->nama_pasien . '%');
}
$operations = $query->get();
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Set headers
$headers = ['ID', 'Nama', 'Tanggal Lahir', 'Umur', 'Alamat', 'Suku', 'Kelamin', 'Anak Ke', 'Riwayat Hamil', 'Riwayat Keluarga', 'Riwayat Kawin Kerabat', 'Riwayat Penyakit Terdahulu', 'Kelainan Kongenital', 'Jenis Cleft', 'Jenis Terapi', 'Diagnosa', 'Tanggal Operasi', 'Teknik Operasi', 'Operator', 'Lokasi Operasi', 'Follow Up', 'Created By Name', 'Created At', 'Updated At', 'Pre Op Photo', 'Post Op Photo', 'Kontrol Photo'];
$sheet->fromArray([$headers], NULL, 'A1');
// Populate data
$row = 2;
foreach ($operations as $operation) {
$data = [
$operation->id,
$operation->nama,
$operation->tanggal_lahir,
$operation->umur,
$operation->alamat,
$operation->suku,
$operation->kelamin,
$operation->anak_ke,
$operation->riwayathamil,
$operation->riwayatkeluarga,
$operation->riwayat_kawin_kerabat,
$operation->riwayat_penyakit_terdahulu,
$operation->kelainan_kongenital,
$operation->jenis_cleft,
$operation->jenis_terapi,
$operation->diagnosa,
$operation->tanggal_operasi,
$operation->teknikoperasi,
$operation->operator,
$operation->lokasioperasi,
$operation->followup,
$operation->created_by_name,
$operation->created_at,
$operation->updated_at,
];
$sheet->fromArray([$data], NULL, 'A' . $row);
// Add photos
$photoCategories = ['pre_op', 'post_op'];
$col = 25; // Start from column Y
foreach ($photoCategories as $category) {
$photo = photo::where('operation_id', $operation->id)
->where('kategori', $category)
->first();
if ($photo) {
$relativePath = str_replace('public/', '', $photo->gambar);
$photoPath = public_path($relativePath);
if (file_exists($photoPath)) {
$drawing = new Drawing();
$drawing->setName($category);
$drawing->setDescription($category);
$drawing->setPath($photoPath);
$drawing->setCoordinates(getExcelColumn($col) . $row);
$drawing->setWidth(100);
$drawing->setHeight(100);
$drawing->setWorksheet($sheet);
$sheet->getColumnDimension(getExcelColumn($col))->setWidth(15);
$sheet->getRowDimension($row)->setRowHeight(75);
}
}
$col++;
}
$row++;
}
// Auto-size columns
foreach (range('A', 'X') as $column) {
$sheet->getColumnDimension($column)->setAutoSize(true);
}
$writer = new Xlsx($spreadsheet);
$excelFilename = 'operations_data_' . time() . '.xlsx';
$zipFilename = 'operations_data_' . time() . '.zip';
$excelFilePath = storage_path('app/temp/' . $excelFilename);
$zipFilePath = storage_path('app/temp/' . $zipFilename);
// Ensure the temp directory exists
if (!file_exists(storage_path('app/temp'))) {
mkdir(storage_path('app/temp'), 0755, true);
}
// Save Excel file
$writer->save($excelFilePath);
// Create ZIP file
$zip = new ZipArchive();
if ($zip->open($zipFilePath, ZipArchive::CREATE) === TRUE) {
$zip->addFile($excelFilePath, $excelFilename);
// Add photos to ZIP
foreach ($operations as $operation) {
foreach ($photoCategories as $category) {
$photo = photo::where('operation_id', $operation->id)
->where('kategori', $category)
->first();
if ($photo) {
$relativePath = str_replace('public/', '', $photo->gambar);
$photoPath = public_path($relativePath);
if (file_exists($photoPath)) {
$zip->addFile($photoPath, "photos/{$operation->id}_{$category}." . pathinfo($photoPath, PATHINFO_EXTENSION));
}
}
}
}
$zip->close();
// Delete the Excel file after adding it to the zip
unlink($excelFilePath);
// Set headers for download
$headers = [
'Content-Type' => 'application/zip',
'Content-Disposition' => 'attachment; filename="' . $zipFilename . '"',
'Content-Length' => filesize($zipFilePath),
'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
'Pragma' => 'no-cache',
];
// Return the file download response
return response()->download($zipFilePath, $zipFilename, $headers)->deleteFileAfterSend(true);
} else {
return redirect()->back()->with('error', 'Failed to create zip file');
}
}
}