<?php

namespace App\Http\Controllers\Api;

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\PerkembanganAnak;
use App\Http\Models\PemeriksaanHpk;
use App\Http\Models\ImunisasiHpk;
use App\Http\Libraries\GrowthZScore;

use Sentinel, Validator, File;

class API1000hpkController extends Controller
{
    public function carikelahiran(Request $request)
    {
        $ibu = IbuHamil::where('nik',$request->nik)->first();
        if (!empty($ibu)) {
            $periodes = PeriodeKehamilan::select('periode_kehamilan.*','nama_kabupaten','nama_kecamatan','nama_desa')
                        ->where('bumil_id',$ibu->id_bumil)
                        ->join('kabupaten','kabupaten.id_kabupaten','=','periode_kehamilan.kabupaten_domisili_id')
                        ->join('kecamatan','kecamatan.id_kecamatan','=','periode_kehamilan.kecamatan_domisili_id')
                        ->join('desa','desa.id_desa','=','periode_kehamilan.desa_domisili_id')
                        ->where('status_kehamilan','Melahirkan')
                        ->get();
            $z = 0;
            if (count($periodes) > 0) {
                foreach ($periodes as $periode) {
                    $dataKelahiran = PerkembanganAnak::where('periode_id',$periode->id_periode)->get();
                    $kelahiran[$z] = [
                        'id_periode' => $periode->id_periode,
                        'bumil_id' => $periode->bumil_id,
                        'kehamilan' => $periode->kehamilan,
                        'status_kehamilan' => $periode->status_kehamilan,
                        'jumlah_anak' => count($dataKelahiran),
                    ];
                    $z++;
                }
            }else{
                $kelahiran = [];
            }
            $data['ibu'] = $ibu;
            $data['kelahiran'] = $kelahiran;
            $return = ['status'=>'success','code'=>'200','message'=>'','data'=>$data];
        }else{
            $return = ['status'=>'error','code'=>'404','message'=>'Ibu Hamil Tidak Ditemukan','data'=>''];
        }
        return response()->json($return);
    }
    
    public function addkelahiran(Request $request)
    {
        if ($request->kelahiran != null) {
            $cekKelahiran = PeriodeKehamilan::where('bumil_id',$request->id_bumil)->where('kehamilan',$request->kelahiran)->get();
            if (count($cekKelahiran) == 0) {
                $bumil = IbuHamil::find($request->id_bumil);
                $periode = new PeriodeKehamilan;
                $periode->bumil_id = $bumil->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->kehamilan = $request->kelahiran;
                $periode->status_kehamilan = 'Melahirkan';
                $periode->save();

                if ($periode) {
                    $return = ['status'=>'success','code'=>'200','message'=>'Kelahiran Berhasil Ditambah !!'];
                }else{
                    $return = ['status'=>'error','code'=>'500','message'=>'Kelahiran Gagal Ditambah !!'];
                }
            }else{
                $return = ['status'=>'error','code'=>'500','message'=>'Kelahiran Sudah Digunakan !!'];
            }
        }else{
            $return = ['status'=>'error','code'=>'404','message'=>'Angka Kelahiran Harus Di isi !!'];
        }
        return response()->json($return);
    }

    public function listAnak(Request $request)
    {
        $periode = PeriodeKehamilan::where('id_periode',$request->id_periode)->where('status_kehamilan','Melahirkan')->first();
        if (!empty($periode)) {
            $anaks = PerkembanganAnak::where('periode_id',$periode->id_periode)->orderBy('id_perkembangan_anak','ASC')->get();
            $data['anak'] = $anaks;
            $return = ['status'=>'success','code'=>'200','message'=>'','data'=>$data];
        }else{
            $return = ['status'=>'error','code'=>'404','message'=>'Data Kehamilan Tidak Ditemukan !!'];
        }
        return response()->json($return);
    }

    public function addAnak(Request $request)
    {
        $users = Users::where('token', $request->token)->first();
        $periode = PeriodeKehamilan::where('id_periode',$request->id_periode)->where('status_kehamilan','Melahirkan')->first();
        if (!empty($periode)) {
            $listAnak = PerkembanganAnak::where('periode_id', $periode->id_periode)->get();
            if (count($listAnak) == 0) {
                $namaAnak = explode(',', $request->nama);
                $jumlahAnak = count($namaAnak);
                for ($i=0; $i < $jumlahAnak; $i++) { 
                    $perkembangan = new PerkembanganAnak;
                    $perkembangan->bumil_id = $periode->bumil_id;
                    $perkembangan->nama_bayi = $namaAnak[$i];
                    $perkembangan->users_id = $users->id;
                    $perkembangan->periode_id = $periode->id_periode;
                    $perkembangan->save();

                    for ($b=1; $b <= 24; $b++) { 
                        $pemerHpk = new PemeriksaanHpk;
                        $pemerHpk->perkembangan_anak_id = $perkembangan->id_perkembangan_anak;
                        $pemerHpk->bulan = $b;
                        $pemerHpk->save();
                    }

                    $imun = ['BCG','DPT1','DPT2','DPT3','HepB 0','HepB 1','HepB 2','HepB 3','Polio 1','Polio 2','Polio 3','Polio 4','Campak','MR'];
                    for ($m=0; $m < count($imun); $m++) { 
                        $imunisasi = new ImunisasiHpk;
                        $imunisasi->perkembangan_anak_id = $perkembangan->id_perkembangan_anak;
                        $imunisasi->nama_imunisasi = $imun[$m];
                        $imunisasi->save();
                    }
                }
                $data['namaAnak'] = PerkembanganAnak::where('periode_id',$periode->id_periode)->orderBy('id_perkembangan_anak','ASC')->get();
                $return = ['status'=>'success','code'=>'200','message'=>'Anak Berhasil ditambahkan !!','data'=>$data];
            }else{
                $return = ['status'=>'error','code'=>'500','message'=>'Data Anak Sudah ada, dan tidak dapat di tambah kembali !!'];
            }
        }else{
            $return = ['status'=>'error','code'=>'404','message'=>'Data Kehamilan Tidak Ditemukan !!'];
        }
        return response()->json($return);
    }

    public function infoDataAnak(Request $request)
    {
        date_default_timezone_set('Asia/Jakarta');
        $user = Users::where('token', $request->token)->first();
        $datAnak = PerkembanganAnak::where('id_perkembangan_anak',$request->id_perkembangan_anak)->with('bumil')->first();
        if (!empty($datAnak)) {
            if ($datAnak->users_id == $user->id) {
                if ($datAnak->tanggalSimpan != '0000-00-00 00:00:00') {
                    $tglNow = date("Y-m-d H:i:s");
                    $tglSmp = strtotime($datAnak->tanggalSimpan);
                    $tglBts = date('Y-m-d H:i:s', strtotime('+3 day', $tglSmp));
                    ($tglNow <= $tglBts ) ? $hakEdit = 1 : $hakEdit = 0;
                }else{
                    $hakEdit = 1;
                }
            }else{
                $hakEdit = 0;
            }

            $data['dataAnak'] = $datAnak;
            $data['hak_edit'] = $hakEdit;
            $return = ['status'=>'success','code'=>'200','message'=>'','data'=>$data];
        }else{
            $return = ['status'=>'error','code'=>'404','message'=>'Data Anak Tidak Ditemukan !!'];
        }
        return response()->json($return);
    }

    public function updateDataAnak(Request $request)
    {
        $rules = array(
            'id_perkembangan_anak'=>'required',
            'tgl_lahir'=>'required',
            'jenis_kelamin'=>'required',
            'berat_bayi_lahir'=>'required',
            'panjang_bayi_lahir'=>'required',
            'menyusui_dini'=>'required',
            'susu_formula'=>'required',
            'melahirkan_di'=>'required',
            'penolong'=>'required',
            // 'makanan_selain_asi'=>'required',
            // 'mp_asi'=>'required',
            // 'vitamin_a'=>'required',
            // 'vitamin_a2'=>'required',
            // 'vitamin_a3'=>'required',
            // 'vitamin_a4'=>'required',
        );
        $messages = array(
                'required' => 'Kolom harus di isi',
        );
        $validator = Validator::make($request->all(), $rules,$messages);
        if(!$validator->fails()){
            date_default_timezone_set('Asia/Jakarta');
            $perkembangan = PerkembanganAnak::find($request->id_perkembangan_anak);
            $perkembangan->tgl_lahir = date('Y-m-d', strtotime($request->tgl_lahir));
            $perkembangan->jenis_kelamin = $request->jenis_kelamin;
            $perkembangan->berat_bayi_lahir = $request->berat_bayi_lahir;
            $perkembangan->panjang_bayi_lahir = $request->panjang_bayi_lahir;
            $perkembangan->menyusui_dini = $request->menyusui_dini;
            $perkembangan->susu_formula = $request->susu_formula;
            $perkembangan->melahirkan_di = $request->melahirkan_di;
            $perkembangan->penolong = $request->penolong;
            $perkembangan->makanan_selain_asi = $request->makanan_selain_asi;
            $perkembangan->mp_asi = $request->mp_asi;
            $perkembangan->vitamin_a = $request->vitamin_a;
            $perkembangan->vitamin_a2 = $request->vitamin_a2;
            $perkembangan->vitamin_a3 = $request->vitamin_a3;
            $perkembangan->vitamin_a4 = $request->vitamin_a4;
            if($perkembangan->tanggalSimpan == "0000-00-00 00:00:00"){
                $perkembangan->tanggalSimpan = date('Y-m-d H:i:s');
            }
            $perkembangan->save();

            if ($perkembangan) {
                $return = ['status' => 'success', 'code' => '200', 'message'=>'Data Anak Berhasil Diperbaharui','data'=>$perkembangan];
            }else{
                $return = ['status' => 'error', 'code' => '500', 'message'=>'Data Anak Gagal Diperbaharui','data'=>''];
            }
        } else {
            $status = 'error';
            $code = 400;
            $message = $validator->messages();
            $return = ['status'=>$status, 'code'=>$code, 'message'=>$message];
        }
        return response()->json($return);
    }

    public function infoimunisasi(Request $request){
        date_default_timezone_set('Asia/Jakarta');
        $user = Users::where('token', $request->token)->first();
        $datAnak = ImunisasiHpk::where('perkembangan_anak_id',$request->id_perkembangan_anak)->get();
        for($i=0; $i<$datAnak->count();$i++) {
            if ($datAnak[$i]->tgl_simpan_imunisasi != '0000-00-00 00:00:00') {
                $tglNow = date("Y-m-d H:i:s");
                $tglSmp = strtotime($datAnak[$i]->tgl_simpan_imunisasi);
                $tglBts = date('Y-m-d H:i:s', strtotime('+3 day', $tglSmp));
                ( $datAnak[$i]->users_id == $user->id && $tglNow <= $tglBts ) ? $hakEdit = 1 : $hakEdit = 0;
            }else{
                $hakEdit = 1;
            }

            $datAnak[$i]['hak_edit'] = $hakEdit;
            $return = ['status'=>'success','code'=>'200','message'=>'','data'=>$datAnak];
        }
        return response()->json($return);
    }

    public function updateImunisasi(Request $request){
        date_default_timezone_set('Asia/Jakarta');
        $user = Users::where('token', $request->token)->first();
        $infoDtAnak = PerkembanganAnak::find($request->id_perkembangan_anak);
        if($infoDtAnak->tgl_lahir != '0000-00-00'){
            $datAnak = ImunisasiHpk::where('perkembangan_anak_id',$request->id_perkembangan_anak)->get(); //sunnah
            $dataImunisasi = json_decode($request->dataImunisasi, true);
    
            for ($i=0; $i <count($dataImunisasi) ; $i++) { 
                if(($dataImunisasi[$i]['tanggal'] != '') && ($dataImunisasi[$i]['hakedit'] == 2)){
                    $updateimun = ImunisasiHpk::find($dataImunisasi[$i]['id_imunisasi_hpk']);
                    $updateimun->tgl_imunisasi = $dataImunisasi[$i]['tanggal'];
                    if($updateimun->tgl_simpan_imunisasi == '0000-00-00 00:00:00'){
                        $updateimun->tgl_simpan_imunisasi = date('Y-m-d H:i:s');
                        $updateimun->users_id = $user->id;
                    }
                    $updateimun->save();
                }
            }
            $return = ['status'=>'success','code'=>200,'message'=>'Data Imunisasi Berhasil di Perbarui'];
        }else{
            $return = ['status' => 'error', 'code' => '400', 'message'=>'Data Anak Harus Diisi Terlebih daluhu !!','data'=>''];
        }
        return response()->json($return);
    }

    public function dataPerkembangan(Request $request)
    {
        date_default_timezone_set('Asia/Jakarta');
        $user = Users::where('token', $request->token)->first();
        $datAnak = PemeriksaanHpk::where('perkembangan_anak_id',$request->id_perkembangan_anak)->orderBy('bulan','ASC')->get();
        for($i=0; $i<$datAnak->count();$i++) {
            if ($datAnak[$i]->tgl_simpan_hpk != '0000-00-00 00:00:00') {
                $tglNow = date("Y-m-d H:i:s");
                $tglSmp = strtotime($datAnak[$i]->tgl_simpan_hpk);
                $tglBts = date('Y-m-d H:i:s', strtotime('+3 day', $tglSmp));
                ( $datAnak[$i]->users_id == $user->id && $tglNow <= $tglBts ) ? $hakEdit = 1 : $hakEdit = 0;
            }else{
                $hakEdit = 1;
            }
            
            $info_bb_u = GrowthZScore::valueBb_u($datAnak[$i]->bb_u);
            $info_pb_u = GrowthZScore::valuePb_u($datAnak[$i]->pb_u);
            $info_bb_pb = GrowthZScore::valueBb_Pb($datAnak[$i]->bb_pb);

            $datAnak[$i]['info_bb_u'] = $info_bb_u;
            $datAnak[$i]['info_pb_u'] = $info_pb_u;
            $datAnak[$i]['info_bb_pb'] = $info_bb_pb;
            $datAnak[$i]['hak_edit'] = $hakEdit;
        }
        $return = ['status'=>'success','code'=>'200','message'=>'','data'=>$datAnak];
        return response()->json($return);
    }

    public function updatePerkembangan(Request $request)
    {
        $rules = array(
            'id_pemeriksaan_hpk'=>'required',
            'tgl_pemeriksaan_hpk'=>'required',
            'berat_badan'=>'required',
            'tinggi_badan'=>'required',
            'bulan'=>'required',
        );
        if ($request->bulan <= 6) {
            $rules['asi_eksklusif'] = 'required'; 
            if ($request->asi_eksklusif == 2) {
                $rules['mp_asi'] = 'required'; 
            }
        }
        $messages = array(
                'required' => 'Kolom harus di isi',
        );
        $validator = Validator::make($request->all(), $rules,$messages);
        if(!$validator->fails()){
            date_default_timezone_set('Asia/Jakarta');
            $user = Users::where('token', $request->token)->first();
            $perkem = PemeriksaanHpk::find($request->id_pemeriksaan_hpk);
            if($perkem->perkembangan->jenis_kelamin != null){
                $perkem->tgl_pemeriksaan_hpk = date('Y-m-d', strtotime($request->tgl_pemeriksaan_hpk));
                $perkem->berat_badan = $request->berat_badan;
                $perkem->tinggi_badan = $request->tinggi_badan;
                if ($request->bulan <= 6) {
                    $perkem->asi_eksklusif = $request->asi_eksklusif;
                    if ($request->asi_eksklusif == 2) {
                        $perkem->mp_asi = $request->mp_asi;
                    }
                }
                $bb_u = GrowthZScore::cekBb_U($perkem->perkembangan->jenis_kelamin,$perkem->bulan,$request->berat_badan);
                $pb_u = GrowthZScore::cekPb_U($perkem->perkembangan->jenis_kelamin,$perkem->bulan,$request->tinggi_badan);
                $bb_pb = GrowthZScore::cekBb_Pb($perkem->perkembangan->jenis_kelamin,$request->berat_badan,$request->tinggi_badan);
                $perkem->bb_u = $bb_u;
                $perkem->pb_u = $pb_u;
                $perkem->bb_pb = $bb_pb;
                if ($perkem->tgl_simpan_hpk == '0000-00-00 00:00:00') {
                    $perkem->tgl_simpan_hpk = date('Y-m-d H:i:s');
                    $perkem->users_id = $user->id;
                }
                $perkem->save();
                
                $info_bb_u = GrowthZScore::valueBb_u($perkem->bb_u);
                $info_pb_u = GrowthZScore::valuePb_u($perkem->pb_u);
                $info_bb_pb = GrowthZScore::valueBb_Pb($perkem->bb_pb);
    
                if ($perkem) {
                    $return = ['status' => 'success', 'code' => '200', 'message'=>'Data Perkembangan Anak Diperbaharui','data'=>$perkem, 'info_bb_u'=>$info_bb_u,'info_pb_u'=>$info_pb_u,'info_bb_pb'=>$info_bb_pb];
                }else{
                    $return = ['status' => 'error', 'code' => '500', 'message'=>'Data Perkembangan Anak Gagal Diperbaharui','data'=>''];
                }
            }else{
                $return = ['status' => 'error', 'code' => '400', 'message'=>'Data Anak Harus Diisi Terlebih daluhu !!','data'=>''];
            }
        } else {
            $status = 'error';
            $code = 400;
            $message = $validator->messages();
            $return = ['status'=>$status, 'code'=>$code, 'message'=>$message];
        }
        return response()->json($return);
    }
}
