<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Models\Users;
use App\Http\Models\IbuHamil;
use App\Http\Models\PeriodeKehamilan;
use App\Http\Models\Pemeriksaan;
use App\Http\Models\Admin;
use App\Http\Models\Bidan;
use Sentinel, Validator, File;

class KehamilanController extends Controller
{
    public function index(Request $request)
    {
        $data['level'] = Sentinel::getUser();
        $data['mn_active'] = "dataIbu";
        $data['title'] = "Data Ibu Hamil";
        $data['smallTitle'] = "Menampilkan data Ibu Hamil";
        return view('kehamilan.main', $data);
    }

    public function searchIbuHamil(Request $request)
    {
        $bumil = IbuHamil::where('nik', $request->nik)->first();
        if ($bumil) {
            $periode = PeriodeKehamilan::where('bumil_id',$bumil->id_bumil)->get();
            return ['status' => 'success','bumil' => $bumil, 'periode' => $periode];
        }else{
            return ['status' => 'notfound'];
        }
    }

    public function formAddKehamilan(Request $request)
    {
        $cekPeriode = PeriodeKehamilan::where('status_kehamilan','Hamil')->where('bumil_id',$request->id)->get();
        if (count($cekPeriode) == 0) {
            $data['bumil'] = IbuHamil::find($request->id);
            $content = view('kehamilan.periode.formAdd',$data)->render();
            return ['status' => 'success', 'content' => $content];
        }else{
            return ['status' => 'error', 'messages' => 'Masih Dalam Periode Kehamilan'];
        }
    }

    public function addKehamilan(Request $request)
    {
        $rules = array(
            'id_bumil'=>'required',
            'usia_ibu'=>'required',
            'usia_kehamilan'=>'required',
            'kehamilan'=>'required',
        );
        $messages = array(
            'required' => 'Kolom harus di isi',
        );
        $validator = Validator::make($request->all(), $rules,$messages);
        if(!$validator->fails()){
            date_default_timezone_set('Asia/Jakarta');
            $bumil = IbuHamil::find($request->id_bumil);
            if (!empty($bumil)) {
                $cekKehamilan = PeriodeKehamilan::where('bumil_id', $request->id_bumil)->where('kehamilan',$request->kehamilan)->get();
                if (count($cekKehamilan) == 0) {
                    $periode = new PeriodeKehamilan;
                    $periode->bumil_id = $request->id_bumil;
                    $periode->alamat_domisili = $bumil->alamat_ktp;
                    $periode->kabupaten_domisili_id = $bumil->kabupaten_ktp_id;
                    $periode->kecamatan_domisili_id = $bumil->kecamatan_ktp_id;
                    $periode->desa_domisili_id = $bumil->desa_ktp_id;
                    $periode->usia_ibu = $request->usia_ibu;
                    $periode->usia_kehamilan = $request->usia_kehamilan;
                    $periode->kehamilan = $request->kehamilan;
                    $periode->jarak_bulan = $request->jarak_bulan;
                    $periode->jarak_tahun = $request->jarak_tahun;
                    $periode->gol_darah = $request->gol_darah;
                    $periode->status_kehamilan = 'Hamil';
                    $periode->tlg_simpan = date('Y-m-d');
                    $periode->users_id = Sentinel::getUser()->id;
                    $periode->save();

                    if ($periode) {
                        for ($i=0; $i<18; $i++) { 
                            $kunjungan = new Pemeriksaan;
                            $kunjungan->periode_id = $periode->id_periode;
                            $kunjungan->bumil_id = $periode->bumil_id;
                            $kunjungan->kunjungan = $i+1;
                            $kunjungan->save();
                        }
                        $return = ['status'=>'success','code'=>'200','message'=>'Kehamilan Berhasil Ditambah !!'];
                    }else{
                        $return = ['status'=>'failed','code'=>'500','message'=>'Kehamilan Gagal Ditambah !!'];
                    }
                }else{
                    $return = ['status' => 'failed', 'code' => '500', 'message'=>'Angka Kehamilan Sudah Digunakan !!','data'=>''];
                }
            }else{
                $return = ['status' => 'failed', 'code' => '500', 'message'=>'Data Ibu Tidak Ditemukan','data'=>''];
            }
            return response()->json($return);
        } else {
            $status = 'required';
            $code = 500;
            $pesan = $validator->messages();  
            $return = ['status'=>$status, 'code'=>$code, 'pesan'=>$pesan];
            return response()->json($pesan);
        }
    }

    public function detailKehamilan(Request $request)
    {
        $data['periode'] = PeriodeKehamilan::find($request->id);
        $content = view('kehamilan.periode.detail',$data)->render();
        return ['status' => 'success', 'content' => $content];
    }

    public function formEditKehamilan(Request $request)
    {
       $data['periode'] = PeriodeKehamilan::find($request->id);
       $content = view('kehamilan.periode.formEdit',$data)->render();
       return ['status' => 'success', 'content' => $content];
    }

    public function editKehamilan(Request $request)
    {
        $rules = array(
            'id_periode'=>'required',
            'usia_ibu'=>'required',
            'usia_kehamilan'=>'required',
        );
        $messages = array(
                'required' => 'Kolom harus di isi',
        );
        $validator = Validator::make($request->all(), $rules,$messages);
        if(!$validator->fails()){
            $periode = PeriodeKehamilan::find($request->id_periode);
            $usiaHamilOld = $periode->usia_kehamilan;
            $periode->usia_ibu = $request->usia_ibu;
            $periode->usia_kehamilan = $request->usia_kehamilan;
            $periode->jarak_bulan = $request->jarak_bulan;
            $periode->jarak_tahun = $request->jarak_tahun;
            $periode->gol_darah = $request->gol_darah;
            $periode->save();

            if($periode){
            $kunjungans = Pemeriksaan::where('periode_id',$periode->id_periode)->where('tanggalSimpan','!=','0000-00-00 00:00:00')->get();
            if (count($kunjungans) > 0) {
                if ($usiaHamilOld != $request->usia_kehamilan) {
                    foreach ($kunjungans as $kunjungan) {
                        $updateKunjungan = Pemeriksaan::find($kunjungan->id_pemeriksaan);
                        $tglAwal = strtotime($periode->tlg_simpan);
                        $tglKunjung = date('Y-m-d', strtotime($updateKunjungan->tgl_kunjungan));
                        $tglAkhir = strtotime($tglKunjung);
                        $jeda = abs($tglAkhir - $tglAwal);
                        $jarakMinggu = floor($jeda/(60*60*24*7));
                        $usiaSekarang = $periode->usia_kehamilan + $jarakMinggu;

                        $updateKunjungan->usia_kehamilan = $usiaSekarang;
                        $updateKunjungan->save();
                    }
                    $return = ['status' => 'success', 'code' => '200', 'message'=>'Periode Kehamilan Berhasil Diperbaharui','data'=>''];
                }else{
                    $return = ['status' => 'success', 'code' => '200', 'message'=>'Periode Kehamilan Berhasil Diperbaharui','data'=>''];
                }
            }else{
                $return = ['status' => 'success', 'code' => '200', 'message'=>'Periode Kehamilan Berhasil Diperbaharui','data'=>''];
            }
            }else{
                $return = ['status' => 'error', 'code' => '500', 'message'=>'Periode Kehamilan Gagal Diperbaharui','data'=>''];
            }
        } else {
            $status = 'error';
            $code = 400;
            $message = $validator->messages();
            $return = ['status'=>$status, 'code'=>$code, 'message'=>$message];
        }
        return response()->json($return);
    }

    public function mainKunjungan(Request $request)
    {
        $data['periode'] = PeriodeKehamilan::find($request->id);
        $data['bumil'] = IbuHamil::find($data['periode']->bumil_id);
        $data['kunjungans'] = Pemeriksaan::where('periode_id', $data['periode']->id_periode)->get();
        $content = view('kehamilan.kunjungan.main',$data)->render();
        return ['status' => 'success', 'content' => $content];
    }

    public function searchKunjungan(Request $request)
    {
        date_default_timezone_set('Asia/Jakarta');
        $users = Sentinel::getUser();
        $kunjungan = Pemeriksaan::where('periode_id', $request->id)->get();
        $periode = PeriodeKehamilan::find($request->id);
        if ($kunjungan) {
            for($i=0; $i<$kunjungan->count();$i++) {
                if ($kunjungan[$i]->users_id == $users->id) {
                    if ($kunjungan[$i]->tanggalSimpan != '0000-00-00 00:00:00') {
                        $tglNow = date("Y-m-d H:i:s");
                        $tglSmp = strtotime($kunjungan[$i]->tanggalSimpan);
                        $tglBts = date('Y-m-d H:i:s', strtotime('+3 day', $tglSmp));
                        ($tglNow <= $tglBts ) ? $kunjungan[$i]['hak_edit'] = '1' : $kunjungan[$i]['hak_edit'] = '0';
                    }else{
                        $kunjungan[$i]['hak_edit'] = '1';
                    }
                }else{
                    if ($kunjungan[$i]->tanggalSimpan != '0000-00-00 00:00:00') {
                        $kunjungan[$i]['hak_edit'] = '0';
                    }else{
                        $kunjungan[$i]['hak_edit'] = '1';
                    }
                }
                if ($kunjungan[$i]->tanggalSimpan != '0000-00-00 00:00:00') {
                    $kunjungan[$i]['sudahIsi'] = '1';
                }else{
                    $kunjungan[$i]['sudahIsi'] = '0';
                }
            }
            return ['status' => 'success', 'kunjungan' => $kunjungan, 'id_user' => $users->id, 'periode'=>$periode];
        }else{
            return ['status' => 'notfound'];
        }
    }

    public function detailKunjungan(Request $request)
    {
        $data['kunjungan'] = Pemeriksaan::find($request->id);
        $user = Users::find($data['kunjungan']->users_id);
        $data['tngMedis'] = $user;
        if ($user->level_user == 1) {
            $admin = Admin::where('users_id',$user->id)->first();
            $data['TlpTngMedis'] = $admin->no_tlp;
            $data['AlamatTngMedis'] = $admin->alamat;
        }elseif($user->level_user == 2 || $user->level_user == 3){
            $bidan = Bidan::where('users_id',$user->id)->first();
            $data['TlpTngMedis'] = $bidan->no_tlp;
            $data['AlamatTngMedis'] = $bidan->alamat;
        }
        $content = view('kehamilan.kunjungan.detail',$data)->render();
        return ['status' => 'success', 'content' => $content];
    }

    public function formAddKunjungan(Request $request)
    {
        date_default_timezone_set('Asia/Jakarta');
        $data['kunjungan'] = Pemeriksaan::find($request->id);
        $data['tglNow'] = date('d-m-Y');
        $data['statusForm'] = 'Tambah';
        $content = view('kehamilan.kunjungan.formKunjungan',$data)->render();
        return ['status' => 'success', 'content' => $content];
    }

    public function formEditKunjungan(Request $request)
    {
        date_default_timezone_set('Asia/Jakarta');
        $data['kunjungan'] = Pemeriksaan::find($request->id);
        $data['statusForm'] = 'Edit';
        $content = view('kehamilan.kunjungan.formKunjungan',$data)->render();
        return ['status' => 'success', 'content' => $content];
    }

    public function updateKunjungan(Request $request)
    {
        $rules = array(
            'statusForm'=>'required',
            'id_pemeriksaan'=>'required',
            'tgl_kunjungan'=>'required',
            'status'=>'required',
        );
        if ($request->protein_hewani == 5) {
            $rules['protein_hewani_lain'] = 'required'; 
        }
        $messages = array(
            'required' => 'Kolom harus di isi',
        );
        $validator = Validator::make($request->all(), $rules,$messages);
        if(!$validator->fails()){
            date_default_timezone_set('Asia/Jakarta');
            $kunjungan = Pemeriksaan::find($request->id_pemeriksaan);
            $kunjungan->tgl_kunjungan = date('Y-m-d', strtotime($request->tgl_kunjungan));
                $tglAwal = strtotime($kunjungan->periode->tlg_simpan);
                $tglKunjung = date('Y-m-d', strtotime($request->tgl_kunjungan));
                $tglAkhir = strtotime($tglKunjung);
                $jeda = abs($tglAkhir - $tglAwal);
                $jarakMinggu = floor($jeda/(60*60*24*7));
                $usiaSekarang = $kunjungan->periode->usia_kehamilan + $jarakMinggu;
            $kunjungan->usia_kehamilan = $usiaSekarang;
            if ($request->berat_badan != null) {
                $kunjungan->berat_badan = $request->berat_badan;
            }
            if ($request->tinggi_badan != null) {
                $kunjungan->tinggi_badan = $request->tinggi_badan;
            }
            if ($request->lila != null) {
                $kunjungan->lila = $request->lila;
            }
            if ($request->hb != null) {
                $kunjungan->hb = $request->hb;
            }
            if ($request->sistole != null) {
                $kunjungan->sistole = $request->sistole;
            }
            if ($request->diastole != null) {
                $kunjungan->diastole = $request->diastole;
            }
            $kunjungan->faktor_resiko = $request->faktor_resiko;
            $kunjungan->letak_janin = $request->letak_janin;
            if ($request->denyut_jantung_janin != null) {
                $kunjungan->denyut_jantung_janin = $request->denyut_jantung_janin;
            }
            if ($request->tinggi_fundus != null) {
                $kunjungan->tinggi_fundus = $request->tinggi_fundus;
            }
            $kunjungan->kaki_bengkak = $request->kaki_bengkak;
            $kunjungan->imunisasi_tt = $request->imunisasi_tt;
            $kunjungan->suplemen_fe = $request->suplemen_fe;
            $kunjungan->protein_hewani = $request->protein_hewani;
            if ($kunjungan->protein_hewani == 5) {
                $kunjungan->protein_hewani_lain = $request->protein_hewani_lain;
            }else{
                $kunjungan->protein_hewani_lain = null;
            }
            $kunjungan->status = $request->status;
                $user = Sentinel::getUser();
            $kunjungan->users_id = $user->id;
            if ($request->statusForm == 'Tambah') {
                $kunjungan->tanggalSimpan = date('Y-m-d H:i:s');
            }
            $kunjungan->save();

            if ($kunjungan) {
                $updateKehamilan = PeriodeKehamilan::find($kunjungan->periode_id);
                $updateKehamilan->status_kehamilan = $request->status;
                $updateKehamilan->save();

                $return = ['status'=>'success','code'=>'200','message'=>'Kunjungan Berhasil Disimpan !!'];
            }else{
                $return = ['status'=>'error','code'=>'500','message'=>'Kunjungan Gagal Disimpan !!'];
            }
            return response()->json($return);
        } else {
            $status = 'required';
            $code = 500;
            $pesan = $validator->messages();  
            $return = ['status'=>$status, 'code'=>$code, 'pesan'=>$pesan];
            return response()->json($pesan);
        }
    }
}
