<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use App\Partner;
use App\User;
use App\Schedule;

use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use Log;





class AbsenController extends Controller
{
    public function index($id)
    {
        // $data = (array)$this;
        // $data['form'] = [
        //     [ 'name' => 'name', 'label' => 'Nama', 'type' => 'text'],
        //     [ 'name' => 'description', 'label' => 'Deskripsi', 'type' => 'text'],
        //     // ['name' => 'ket', 'label' => 'Keterangan', 'type'=>'select', 'value' => ['sa', 'tu', 'dua']]  
        // ];
        // session()->put('error', 'Lokasi salah');
        // $request->session()->put('error', 'value');
        // session(['error' => 'value']);
        $partner = Partner::where('slug', $id)->get();
        if($partner->count() < 1){
            // session()->put('error','Gagal hapus.');
                return redirect('/blank');
            };
        $data['form_action'] = "partner.store";
        $data['form_update'] = "partner.update";
        $data['slug'] = $id;
        // return redirect('/blank');
        // return json_encode($data);
        return View::make('dashboard.absen.index', $data);
    }
    public function blank()
    {
       
        return View::make('dashboard.absen.blank');
    }
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nip' => 'required|integer',
        ]);
        if ($validator->fails()) {
            session()->put('error','Absen gagal.');
            return back();
        }
        // return $request->all();
        $partner = Partner::where('slug', $request->slug)->get();
        // return json_encode($partner[0]);
        // session()->put('success','Berhasil Input.');   
        // return redirect('/company');
        // return json_encode($user->count()<1);
        $lat1 = $partner[0]->latitude;
        $lat2 = $request->latitude;
        $lon1 = $partner[0]->longitude;
        $lon2 = $request->longitude;

        $theta=$lon1-$lon2;
        $dist=sin(deg2rad($lat1))*sin(deg2rad($lat2))+cos(deg2rad($lat1))*cos(deg2rad($lat2))*cos(deg2rad($theta));
        $dist=acos($dist);
        $dist=rad2deg($dist);
        $miles=$dist*60*1.1515;
        
        $hasil = $miles*1.609344;
        // return json_encode($hasil);
        $jarak = env('JARAK_MAKSIMAL');
        if($hasil < $jarak){
            // return $this->status('susscess', 'Absen berhasil');
            $user = User::where('partner_id', $partner[0]->id)->where('nip', $request->nip)->where('is_active', 1)->get();
        //     $user_init = User::with('role')->where('nip', $request->nip)->get();
        // // return json_encode($user_init);

        //     if($user_init[0]->role->name == "Koordinator Lapangan"){
        //         $user = User::where('nip', $request->nip)->get();
        //     }else{
        //         $user = User::where('partner_id', $partner[0]->id)->where('nip', $request->nip)->get();
        //     }
            
            if($user->count() < 1){
                session()->put('error', 'User tidak ditemukan');
                return redirect('/absen/'.$request->slug); 
            }
            // return json_encode($request->all());
            // return json_encode($user[0]->id);
            $mytime = Carbon::now()->format('Y-m-d H:i:s');
            $mytime2 = Carbon::now();
            $after = env('TIME_BEFORE');
            // $before = intval($bfr);
            $mytimeAfter = $mytime2->addMinutes($after)->format('Y-m-d H:i:s');
            // return json_encode($mytime->toDateTimeString());
            $absen=Schedule::where('user_id', $user[0]->id)->where('partner_id', $partner[0]->id)
                            ->where('start_plot', '<=', $mytimeAfter)
                            // ->orWhere('end_plot', '>=', $mytime )
                            ->where('end_plot', '>=', Carbon::now()->format('Y-m-d') )
                            ->where('end_absen', null)

                            // ->where('end_plot', null )
                            // ->where(function ($query) {
                            //     // $query->where('end_plot', '>=', Carbon::now()->format('Y-m-d H:i:s') )
                            //     $query->where('end_plot', '>=', Carbon::now()->format('Y-m-d') )
                            //           ->orWhere('end_plot', null);
                            // })
                            ->get();
                            // return json_encode($absen);

                            if($absen->count() < 1){
                                // return json_encode('ma');
                                session()->put('error', 'Jadwal tidak ditemukan');
                                return redirect('/absen/'.$request->slug); 
                            };

                            $terlambat = Carbon::parse($absen[0]->start_plot);
                            $late = env('TIME_LATE');
                            $to_late = $terlambat->addMinutes($late)->format('Y-m-d H:i:s');
                            // return json_encode($late);
                            // return json_encode($terlambat->addMinutes($late)->format('Y-m-d H:i:s'));                 
                            if($absen[0]->start_absen == null){
                                $sek = Carbon::now();
                                if($mytime > $to_late){
                                    // $selisih = $sek->diff($to_late)->format('%H:%I:%S');
                                    $selisih = $sek->diff($to_late)->format('%H Jam, %I Menit');
                                    // return json_encode('terlambat '.$selisih);
                                    $pesan = 'Berhasil Absen, terlambat '.$selisih;
                                }else{
                                    $pesan = 'Berhasil Absen';
                                };
                                $absen[0]->start_absen = $mytime;
                            }else{
                                $absen[0]->end_absen = $mytime;
                                $pesan = 'Berhasil Absen Pulang';
                                session()->put('validation', true);
                                session()->put('id_absen', $absen[0]->id);

                            };
                                $absen[0]->save();
                            
                            // return json_encode($absen[0]);           
                session()->put('success', $pesan);
                session()->put('image', $user[0]->image);
                session()->put('name', $user[0]->name);
                return redirect('/absen/'.$request->slug); 
        }else{
            // return $this->status('error', 'Lokasi salah');
            session()->put('error', 'Lokasi salah');
            return redirect('/absen/'.$request->slug); 
        }
        // return json_decode($miles*1.609344);
        
    }
    public function status($tatus, $pesan)
    {
       $balas = [
        "status" => $tatus,
        "pesan" => $pesan
       ];
        return $balas;
    }

    public function batal(Request $request)
    {
        // return json_encode($request->all());
        // Log::info($request->all());
        $data = Schedule::find($request->data);
        $data->end_absen = null;
        $data->save();
        session()->put('success', 'Absen dibatalkan');

        return json_encode("success");

    }

}