<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use App\Jawaban;
use App\Subjawaban;
use App\SiraB;
use App\Organisms;
use App\Periksa;
use App\KomponenJawaban;
use Validator;
use Picqer\Barcode\BarcodeGeneratorPNG;
use Session;

class TemplateController extends Controller
{
    public function index() {
		if (Session::get('previlage') == ''){
			return redirect('/login');
		} else {
			$data 				= [];
			$getsirab 			= Organisms::whereNotIn('kelompok', ['biakankultur', 'mikroorganisme', 'listkodespesimen'])->select('kelompok')->groupBy('kelompok')->orderBy('kelompok', 'ASC')->get();
			$data['parameters'] = $getsirab;
			return view('admin.template', $data);
		}
    }
	public function viewSIRAb() {
		$previlage 			= Session('previlage');
		if ($previlage == 'developer' OR $previlage == 'supervisor') {
			$data 		= 	[];
			return view('admin.sirab', $data);
		} else {
			$data                       = [];
            $data['kalimatheader']  	= 'Access Denied';
            $data['kalimatbody']  		= 'Laman khusus SPV';
            return view('errors.error', $data);
		}
    }
    public function backup() {
		$previlage 			= Session('previlage');
		if ($previlage == 'developer' OR $previlage == 'supervisor') {
			$data 				= [];
			$data['alldata']	= Storage::allFiles('/usr/share/nginx/html/rispacs/public/backupdata');
			return view('backup', $data);
		} else {
			$data                       = [];
            $data['kalimatheader']  	= 'Access Denied';
            $data['kalimatbody']  		= 'Laman khusus SPV';
            return view('errors.error', $data);
		}
    }
    public function getListJawaban() {
	    $results	=   DB::table('jawaban')->get();
        $arraylist  =   [];
		$arraylist[]= array(
			'id'        =>  'new',   
			'jawaban' 	=>  '<span class="badge badge-primary">Add New</span>'
		); 
        foreach ($results as $result) {
            $arraylist[] = array(
                'id'        =>  $result->id,   
                'jawaban' 	=>  $result->jawaban,
            );   
        }
		
	    echo json_encode($arraylist);
    }
    public function updateJawaban(Request $request) {
    	$validator = Validator::make($request->all(), [
      		'val01' => 'required',
            'val02' => 'required'
        ]);

    	if($validator->fails()) {
          return response()->json(['status' => 'error', 'message' => 'Please fill input field or fill with right input']);
        } else {
        	$id   =   $request->input('val02');
			if ($id != 'new'){
				Jawaban::where('id', $id)->update(['jawaban' => $request->input('val01')]);
			}
        	else {
				Jawaban::create(['jawaban' => $request->input('val01')]);
			}
			return response()->json(['status' => 'Success !!', 'message' => 'Category Saved..!!']);
        }
    }
    public function deleteJawaban(Request $request) {
		try {
			$id 		=	$request->id;
			if ($id == 'sirab'){
				$data 	=	SiraB::find($request->idsirab);
			} else if ($id == 'mikroorganisme'){
				$data 	=	Organisms::find($request->idsirab);
			} else {
				$data 	=	Jawaban::find($id);
			}
			$data->delete();
			if ($data){
				return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Deleted']);
				return back();
			} else {
				return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Failed', 'message' => 'Unkown Error']);
				return back();
			}
		} catch (\Exception $e) {
			return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Failed', 'message' => $e->getMessage()]);
			return back();
		}
    	
    }
    public function getListSubjawaban(Request $request) {
		$idkat 		= 	$request->input('val01');
		$kategori 	= 	$request->input('val02');
		if ($idkat == 'new') {
			$arraylist  =   [];
			$arraylist[]= array(
				'id'        =>  'gakboleh',
				'kategori'  =>  '-',
				'judul'  	=>  '<span class="badge badge-danger">Please Select Category First</span>',
				'isine' 	=>  '-',
				'kesimpulan'=>  '-'
			);
        } else {
			$arraylist	= [];
			$arraylist[]= array(
				'id'        =>  'new',
				'kategori'  =>  '-',
				'judul'  	=>  '<span class="badge badge-custom">Add New Expertise Themplate</span>',
				'isine' 	=>  '-',
				'kesimpulan'=>  '-'
			);
            $results	= Subjawaban::where('kategori', $idkat)->get();
			
			foreach ($results as $result) {
				$isine 		= $result->subjawaban;
				$kesimpulan	= $result->kesimpulan;
				$isine 		= $isine.' '.$kesimpulan;
				$arraylist[] = array(
					'id'        =>  $result->id,   
					'kategori'	=>  $kategori,
					'judul'		=>  $result->judul,
					'isine'		=>  $isine,
					'kesimpulan'=>  ''
				);   
			}
        }
	    echo json_encode($arraylist);
    }
    public function updateSubjawaban(Request $request) {
    	$validator  =   Validator::make($request->all(), [
	    	'val01' => 'required',
			'val02' => 'required',
			'val03' => 'required',
			'val04' => 'required'
        ]);
    	if($validator->fails()) {
    		return response()->json(['status' => 'Error !!', 'message' => 'Please fill input field or fill with right input']);
    	} else {
			$id   =   $request->input('val02');
			if ($id != 'new'){
				Subjawaban::where('id', $id)->update([
				'judul' 	=> $request->input('val03'),
				'subjawaban'=> $request->input('val04'),
				'kesimpulan'=> ''
				]);
			}
			else {
				Subjawaban::create([
				'kategori' 	=> $request->input('val01'),
				'judul' 	=> $request->input('val03'),
				'subjawaban'=> $request->input('val04'),
				'kesimpulan'=> ''
				]);
			}
			return response()->json(['status' => 'Success !!', 'message' => 'Template Saved..!!']);
       		
      	}
    }
    public function deleteSubjawaban(Request $request) {
    	$id 		=	$request->id;
	   	$subjawaban =	Subjawaban::find($id);

	   	$subjawaban->delete();

	   	return back();
    }
	public function showImage($imageName){
		// Menentukan path gambar di storage
		$filePath = public_path("{$imageName}");
		
		// Cek apakah file ada
		if (!file_exists($filePath)) {
			abort(404); // Jika file tidak ditemukan, tampilkan error 404
		}

		// Ambil konten file gambar
		$imageContent = file_get_contents($filePath);

		// Tentukan MIME type untuk gambar PNG
		$mimeType = mime_content_type($filePath);

		// Kirim gambar sebagai response dengan header untuk mencegah cache
		return response($imageContent, 200)
			->header('Content-Type', $mimeType)   // Tentukan MIME type gambar
			->header('Cache-Control', 'no-store, no-cache, must-revalidate')  // Tidak cache di browser
			->header('Pragma', 'no-cache')        // Tidak menggunakan cache pada browser lama
			->header('Expires', '0');             // Jangan pernah kadaluarsa
	}
	public function exUploadKOP(Request $request) {
    	if($request->hasFile('file')) {
			$ImageExt	= $request->file('file')->getClientOriginalExtension();
			$file_tmp	= $request->file('file');
			$data 		= file_get_contents($file_tmp);
			if ($ImageExt == 'png'){
				try {
					$unggah = Storage::disk('langsungpublic')->put('kopsurat.png', $data);

					if ($unggah){
						return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Pictures Saved, please refresh to apply the change']);
						return back();
					} else {
						return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Failed', 'message' => 'Unkown Error']);
						return back();
					}
				} catch (\Exception $e) {
					return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Failed', 'message' => $e->getMessage()]);
					return back();
				}
			} else {
				return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Failed', 'message' => 'Only Accept PNG File']);
				return back();
			}
		} else {
			return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Failed', 'message' => 'No File Selected']);
			return back();
		}
    }
	public function showBarcode($nofoto){
		$generator 		= new BarcodeGeneratorPNG();
		$barcodeImage 	= $generator->getBarcode($nofoto, $generator::TYPE_CODE_128);
		return response($barcodeImage, 200)->header('Content-Type', 'image/png');
	}
	public function exSIRAb(Request $request) {
    	try {
			$id 	= $request->id;
			$tabel 	= $request->tabel;
			$data 	= null;
			$pesan 	= 'Unkown Error';
			if ($tabel == 'Organisme'){
				if ($id == 'new'){
					$ceksudah = Organisms::where('name', $request->name)->where('category', $request->category)->where('kelompok', $request->kelompok)->count();
					if ($ceksudah == 0){
						$data 		= new Organisms;
						$inputData 	= $request->except(['id', 'tabel', '_token']);
						$data->fill($inputData);
						$data->save();
					} else {
						$pesan 		= $request->name.' ('.$request->category.') Sudah ada, Mohon ubah Data sebelum simpan kembali';
					}
				} else {
					$ceksudah = Organisms::where('id', '!=', $id)->where('name', $request->name)->where('category', $request->category)->where('kelompok', $request->kelompok)->count();
					if ($ceksudah == 0){
						$data 		= Organisms::find($id);
						$inputData 	= $request->except(['id', 'tabel', '_token']);
						$data->update($inputData);
					} else {
						$pesan 		= $request->name.' ('.$request->category.') Sudah ada, Mohon ubah Data sebelum simpan kembali';
					}
				}
				if ($data){
					return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Saved']);
					return back();
				} else {
					return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Failed', 'message' => 'Unkown Error']);
					return back();
				}
			} else if ($tabel == 'Speciment'){
				$kodelama 	= '';
				if ($id == 'new'){
					$ceksudah = Organisms::where('name', $request->name)->where('kelompok', $request->kelompok)->count();
					if ($ceksudah == 0){
						$data 		= new Organisms;
						$inputData 	= $request->except(['id', 'tabel', '_token']);
						$data->fill($inputData);
						$data->save();
					} else {
						$pesan 		= $request->name.' ('.$request->category.') Sudah ada, Mohon ubah Data sebelum simpan kembali';
					}
				} else {
					$ceksudah = Organisms::where('id', '!=', $id)->where('name', $request->name)->where('kelompok', $request->kelompok)->count();
					if ($ceksudah == 0){
						$data 		= Organisms::find($id);
						$kodelama 	= $data->category;
						$kodebaru 	= $request->category;
						$inputData 	= $request->except(['id', 'tabel', '_token']);
						$data->update($inputData);
					} else {
						$pesan 		= $request->name.' ('.$request->category.') Sudah ada, Mohon ubah Data sebelum simpan kembali';
					}
				}
				if ($data){
					if ($kodelama != ''){
						Periksa::where('kd_spesimen', $kodelama)->update(['kd_spesimen' => $kodebaru]);
					}
					return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Saved']);
					return back();
				} else {
					return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Failed', 'message' => 'Unkown Error']);
					return back();
				}
			} else if ($tabel == 'Parameter'){
				$getdatalama 	= Organisms::where('kelompok', $request->kelompok)->first();
				$category		= $getdatalama->category ??  $request->kelompok;
				if ($id == 'new'){
					$ceksudah = Organisms::where('name', $request->name)->where('category', $category)->where('kelompok', $request->kelompok)->count();
					if ($ceksudah == 0){
						$data = Organisms::create([
							'name'		=> $request->name,
							'category'	=> $category,
							'kelompok'	=> $request->kelompok
						]);
					} else {
						$pesan 		= $request->name.' ('.$request->category.') Sudah ada, Mohon ubah Data sebelum simpan kembali';
					}
				} else {
					$ceksudah = Organisms::where('id', '!=', $id)->where('name', $request->name)->where('category', $category)->where('kelompok', $request->kelompok)->count();
					if ($ceksudah == 0){
						$data = Organisms::where('id', $id)->update([
							'name'		=> $request->name,
							'category'	=> $category,
							'kelompok'	=> $request->kelompok
						]);
					} else {
						$pesan 		= $request->name.' ('.$request->category.') Sudah ada, Mohon ubah Data sebelum simpan kembali';
					}
				}
				if ($data){
					return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Saved']);
					return back();
				} else {
					return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Failed', 'message' => 'Unkown Error']);
					return back();
				}
			} else if ($tabel == 'BioRepository'){
				$kategorisimpan = $request->kategorisimpan;
				$shelfnomor 	= $request->shelfnomor;
				$raknomor 		= $request->raknomor;
				$slotnomor 		= $request->slotnomor;
				$boxnomor 		= $request->boxnomor;
				$tubenomor 		= $request->tubenomor;
				$nomor 			= $kategorisimpan.''.$shelfnomor.''.$raknomor.''.$slotnomor.''.$boxnomor.'-'.$tubenomor;
				$data 			= KomponenJawaban::where('id', $id)->update([
					'isidata'			=> $request->nmbakteri,
					'nobiorepository'	=> $nomor,
					'strain'			=> $request->strain,
					'atcc'				=> $request->atcc,
					'sample'			=> $request->nmbakteri,
					'tglpenyimpanan'	=> $request->tglpenyimpanan,
					'created_by'		=> $request->created_by
				]);
				if ($data){
					return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Saved']);
					return back();
				} else {
					return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Failed', 'message' => 'Unkown Error']);
					return back();
				}
			} else {
				if ($id == 'new'){
					$data 		= new SiraB;
					$inputData 	= $request->except(['id', 'tabel', '_token']);
					$data->fill($inputData);
					$data->save();
				} else {
					$data 		= SiraB::find($id);
					$inputData 	= $request->except(['id', 'tabel', '_token']);
					$data->update($inputData);
				}
				if ($data){
					return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Saved']);
					return back();
				} else {
					return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Failed', 'message' => 'Unkown Error']);
					return back();
				}
			}
		} catch (\Exception $e) {
			return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Failed', 'message' => $e->getMessage()]);
			return back();
		}
    }
}
