<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Maatwebsite\Excel\Facades\Excel;
use App\Role;
use App\User;
use App\Company;
use App\Status;
use App\Division;
use App\Partner;
use App\Position;
use App\File;
use App\History;
use App\Contract;
use Illuminate\Support\Facades\Validator;
use DataTables;
use Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use App\Imports\ImportUser;
use PDF;



class MemberController extends Controller
{
    public function __construct()
    {
        // $this->middleware('auth');
        $this->middleware('admin');
        $this->pageTitle = 'Member';
        $this->masterActive = 'active';
        $this->memberActive = 'active';
    }
    public function index()
    {
        $data = (array)$this;

        $role = Role::all();
        $company = Company::all();
        $status = Status::all();
        $division = Division::all();
        $data['division']  = $division;
        $data['partner'] = Partner::all();
        $position = Position::with('division')->get();
        $con = array();
        foreach ($position as $p) {
             $reb['id'] = $p->id;
             $reb['name'] = $p->name.' / '.$p->division->name;
             $con[]=$reb;
          
        }

        // $us = User::with('role', 'company', 'partner')->get();
        // return json_encode($us);

        $data['form'] = [
            [ 'name' => 'name', 'label' => 'Nama', 'type' => 'text'],
            [ 'name' => 'nik', 'label' => 'NIK', 'type' => 'text'],
            [ 'name' => 'tempat_lahir', 'label' => 'Tempat Lahir', 'type' => 'text'],
            [ 'name' => 'tanggal_lahir', 'label' => 'Tanggal Lahir', 'type' => 'date'],
            [ 'name' => 'alamat', 'label' => 'Alamat', 'type' => 'text'],
            [ 'name' => 'no_handpone', 'label' => 'No. Handphone', 'type' => 'text'],
            [ 'name' => 'nama_ibu_kandung', 'label' => 'Nama Ibu kandung', 'type' => 'text'],
            // [ 'name' => 'alamat', 'label' => 'Alamat', 'type' => 'text'],
            [ 'name' => 'awal_masuk', 'label' => 'Awal Masuk', 'type' => 'date'],




            // [ 'name' => 'password', 'label' => 'Password', 'type' => 'password'],
            ['name' => 'status_id', 'label' => 'Status', 'type'=>'select', 'option' =>$status],
            // ['name' => 'division_id', 'label' => 'Divisi', 'type'=>'select', 'option' =>$division],
            ['name' => 'division_id', 'label' => 'Divisi', 'type'=>'chain', 'option' =>$division],
            ['name' => 'position_id', 'label' => 'Posisi', 'type'=>'chained', 'option' =>[]],

            // ['name' => 'company_id', 'label' => 'Perusahaan', 'type'=>'select', 'option' =>$company]  
            // ['name' => 'ket', 'label' => 'Keterangan', 'type'=>'select', 'value' => ['sa', 'tu', 'dua']]  
        ];
        $data['form_action'] = "member.store";
        // $data['form_update'] = "member/update";
        // return json_encode($data);
        return View::make('dashboard.member.index', $data);
    }
    public function indexData(Request $request){
        $us = Role::where('name', 'Member')->get();

        // $data = User::with('role','company','partner')->where('role_id', $us[0]->id)->where('company_id', Auth::user()->company->id);
        $data = User::with('role','company','partner')->where('company_id', Auth::user()->company->id);
        if (!empty ($request->get('partner_id')) ){
            $data = $data->where('partner_id', $request->get('partner_id'));
        };
        if (!empty ($request->get('division_id')) ){
            $data = $data->where('division_id', $request->get('division_id'));
        };
        if (!empty ($request->get('status')) ){
            if($request->get('status') == '1'){
                $data = $data->where('is_active', '1');
            }else{
                $data = $data->where('is_active', null);
            }
        };
         return Datatables::of($data)
               ->editColumn('action', function($data){ return view('dashboard.member.index-action', compact('data'));})
               ->editColumn('is_active', function ($data) {    
                if($data->is_active == '1') {
                    return '<i class="material-icons">done</i>';
                }else{
                    return '<i class="material-icons text-danger">highlight_off</i>';
                }
                       
                        })
               ->rawColumns(['action','is_active'])
               ->make(true); 

   }
   public function indexEdit(Request $request){
    // $us = Role::where('name', 'Member')->get();

    $data = File::where('user_id', $request->get('id'));
    // $data = File::all();
     return Datatables::of($data)
           ->editColumn('action', function($data){ return view('dashboard.member.index-action', compact('data'));})
           ->rawColumns(['action'])
           ->make(true); 

}

    public function store(Request $request)
    {

        $us = Role::where('name', 'Member')->get();
        // return json_encode($us[0]->id);
        // return json_encode($invID);
        // return json_encode($request->all());

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'nik' => 'required'
        ]);

        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        
        do{
            $nip = mt_rand(100000,999999);
            // $dokumen = Str::random(40);
            $cekuniq =  User::where('nip', $nip);
        }while(empty($cekuniq)); 


        $researche = User::create([
            'name' => $request->name,
            'role_id' => $request->role_id,
            'company_id' => Auth::user()->company->id,
            'email' => $request->name,
            'password' => Hash::make('admin'),

        //     'name', 
        // 'email', 
        // 'password',
        // 'role_id',
        // 'company_id',
        // 'image',
        'nip'=> $nip,
        'is_active'=> 1,
        'position_id'=> $request->position_id ?? null,
        'division_id'=> $request->division_id ?? null,
        'status_id'=> $request->status_id ?? null,
        // 'partner_id'=> $request->
        // 'is_bpjskes'=> $request->
        // 'is_bpjstk'=> $request->
        'awal_masuk'=> $request->awal_masuk ?? null,
        'nama_ibu_kandung'=> $request->nama_ibu_kandung ?? null,
        'no_handpone'=> $request->no_handpone ?? null,
        'alamat'=> $request->alamat ?? null,
        'tanggal_lahir'=> $request->tanggal_lahir ?? null,
        'tempat_lahir'=> $request->tempat_lahir ?? null,
        'nik' => $request->nik ?? null,
        'role_id' => $us[0]->id


            ]);

        session()->put('success','Berhasil Input.');   
        return redirect('/member');
        
    }

    public function destroy($id)
    {
        $data = User::find($id);
        if($data->count() < 1){
        session()->put('error','Gagal hapus.');
            return redirect('/member');
        };
        $data->delete();
        session()->put('success','Berhasil Hapus.');
            return redirect('/member');
    }
    public function delete_file(Request $request)
    {
        $data = File::find($request->id);
        if($data->count() < 1){
        session()->put('error','Gagal hapus.');
            // return redirect('/user');
            return back();

        };
        $data->delete();
        session()->put('success','Berhasil Hapus.');
            // return redirect('/user');
        return redirect('/member/edit/'.$request->user_id); 

    }
    public function delete_pkwt(Request $request)
    {
        $data = Contract::find($request->id);
        if($data->count() < 1){
        session()->put('error','Gagal hapus.');
            // return redirect('/user');
            return back();

        };
        $data->delete();
        session()->put('success','Berhasil Hapus.');
            // return redirect('/user');
        return redirect('/member/edit/'.$request->user_id); 

    }
    public function delete_history(Request $request)
    {
        $data = History::find($request->id);
        if($data->count() < 1){
        session()->put('error','Gagal hapus.');
            // return redirect('/user');
            return back();

        };
        $data->delete();
        session()->put('success','Berhasil Hapus.');
            // return redirect('/user');
        return redirect('/member/edit/'.$request->user_id); 

    }
    public function look(Request $request)
    {
       
        $data = User::findOrFail($request->data);
        return json_encode($data);

    }
    public function look_position(Request $request)
    {
       
        $data = Position::where('division_id', $request->data)->get();
        return json_encode($data);

    }
    public function update(Request $request)
    {
        // return json_encode($request->all());

        $validator = Validator::make($request->all(), [
            'name' => 'required'
        ]);
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $data = User::find($request->id);
        $data->name = $request->name;
        $data->nip = $request->nip;
        $data->nama_ibu_kandung = $request->nama_ibu_kandung;
        $data->no_handpone = $request->no_handpone;
        $data->alamat = $request->alamat;
        $data->nik = $request->nik;
        $data->tempat_lahir = $request->tempat_lahir;
        $data->tanggal_lahir = $request->tanggal_lahir;
        $data->awal_masuk = $request->awal_masuk;
        $data->division_id = $request->division_id;
        $data->position_id = $request->position_id;
        // $data->status_id = $request->status_id;
        $data->is_active = $request->is_active;
        $data->is_bpjskes = $request->is_bpjskes;
        $data->is_bpjstk = $request->is_bpjstk;
        $data->is_payroll = $request->is_payroll;
        
        $data->save();
        session()->put('success','Berhasi edit!');
        // return redirect('/user');  
        return redirect('/member/edit/'.$request->id); 

    }
    public function update_pkwt(Request $request)
    {
        // return json_encode($request->all());

        $validator = Validator::make($request->all(), [
            'status_id' => 'required',
            'start_date' => 'required',
            'end_date' => 'required',
            'berkas' => 'required|mimes:pdf'
        ]);
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $data = User::find($request->id);
        
        $data->status_id = $request->status_id;
        if( $data->tanggal_pkwt == null){
            $data->tanggal_pkwt = $request->start_date;
        }
        $data->save();
        if ($request->hasFile('berkas')) {

            // return json_encode('dalam');
            do{
                $dokumen = Str::random(40);
                $cekuniq =  Contract::where('berkas', $dokumen);
            }while(empty($cekuniq)); 


            $request['berkas']->move(public_path('contracts'), $dokumen.'.'.$request->berkas->getClientOriginalExtension());


            // File::create([
            //     'name' => $request->name,
            //     'user_id' => $request->id,
            //     'berkas' => $dokumen.'.'.$request->berkas->getClientOriginalExtension(),
            //     ]);
               Contract::create([
                    'user_id' => $request->id,
                    'description' => 'Perpanjangan PKWT',
                    'start_date' => $request->start_date,
                    'end_date' => $request->end_date,
                    'berkas' => $dokumen.'.'.$request->berkas->getClientOriginalExtension()
                    ]);


                session()->put('success','Berhasil Input.');   
                // return redirect('/member');
                return redirect('/member/edit/'.$request->id); 

        };
        


        session()->put('success','Berhasi edit!');
        // return redirect('/user');  
        return redirect('/member/edit/'.$request->id); 

    }
    public function update_partner(Request $request)
    {
        // return json_encode($request->all());

        $validator = Validator::make($request->all(), [
            'partner_id' => 'required'
        ]);
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $partner = Partner::find($request->partner_id);
        $data = User::find($request->id);
        // return json_encode($data);
        if($data->partner_id != $request->partner_id){
            $researche = History::create([
                'user_id' => $request->id,
                'description' => 'Ditempatkan di '. $partner->name,
                'tanggal' => $request->tanggal
                ]);
        };

        $data->partner_id = $request->partner_id;
        $data->save();
        session()->put('success','Berhasi edit!');
        // return redirect('/user');  
        return redirect('/member/edit/'.$request->id); 

    }
    public function edit($id)
    {
        $data = (array)$this;

        $data['status'] = Status::all();
        $data['division'] = Division::all();
        $data['position'] = Position::all();
        $data['partner'] = Partner::where('company_id', Auth::user()->company->id)->get();
        $data['user'] = User::find($id);
        $data['id'] = $id;
        $data['file'] = File::where('user_id', $id)->get();
        $data['history'] = History::where('user_id', $id)->get();
        $data['contract'] = Contract::where('user_id', $id)->get();
        // return json_encode($data);
        return View::make('dashboard.member.edit', $data);

    }

    public function update_image(Request $request)
    {
        // return json_encode($request->all());





        if($request->hasFile('image')) {
//    return json_encode('masuk');
            // Upload path
            $destinationPath = 'image/';
     
            // Get file extension
            $extension = $request->file('image')->getClientOriginalExtension();
     
            // Valid extensions
            $validextensions = array("jpeg","jpg","png");
     
            // Check extension
            if(in_array(strtolower($extension), $validextensions)){
  
              do{
                  $dokumen = Str::random(60);
                  $cekuniq =  User::where('image', $dokumen);
              }while(empty($cekuniq)); 
     
              // Rename file 
              // $fileName = $request->file('file')->getClientOriginalName().time() .'.' . $extension;
              $fileName = $request->file('image')->getClientOriginalName();
              $fileReal = $dokumen . '.' . $extension;
              // Uploading file to given path
              $request->file('image')->move($destinationPath, $fileReal); 
              
  

              $data = User::find($request->id);
                $data->image = $fileReal;
                $data->save();
                session()->put('success','Berhasi edit!');
                return redirect('/member/edit/'.$request->id); 

            }
     
          }




            session()->put('error','Input gagal.');
            return back();
        
     
    }

    public function update_password(Request $request)
    {
        // return json_encode($request->all());

        $validator = Validator::make($request->all(), [
            'password' => 'required'
        ]);
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $data = User::find($request->id);
        $data->password = Hash::make($request->password);
      
        $data->save();
        session()->put('success','Berhasi edit!');
        // return redirect('/user');  
        return redirect('/member/edit/'.$request->id); 

    }
    public function store_file(Request $request)
    {

        // $us = Role::where('name', 'Member')->get();
        // return json_encode($us[0]->id);
        // return json_encode($invID);
        // return json_encode($request->all());

        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'berkas' => 'required|mimes:pdf'
        ]);

        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }

        if ($request->hasFile('berkas')) {

            // return json_encode('dalam');
            do{
                $dokumen = Str::random(40);
                $cekuniq =  File::where('berkas', $dokumen);
            }while(empty($cekuniq)); 


            $request['berkas']->move(public_path('berkas'), $dokumen.'.'.$request->berkas->getClientOriginalExtension());


            File::create([
                'name' => $request->name,
                'user_id' => $request->id,
                'berkas' => $dokumen.'.'.$request->berkas->getClientOriginalExtension(),
                ]);


                session()->put('success','Berhasil Input.');   
                // return redirect('/member');
                return redirect('/member/edit/'.$request->id); 

        };

        session()->put('error','Input gagal.');
        return back();
        
    }
    public function look_file(Request $request)
    {
       
        $data = File::findOrFail($request->data);
        return json_encode($data);

    }
    public function look_pkwt(Request $request)
    {
        $data = Contract::findOrFail($request->data);
        return json_encode($data);

    }
    public function download_fileex()
    {
    //    dd('o');
        $pathToFile = base_path().'/public/contoh_format.xls';
        // return json_encode($pathToFile);
        return response()->download($pathToFile);

    }

    public function import(Request $request){
        try{
            Excel::import(new ImportUser, request()->file('file'));
            session()->put('success','Berhasi upload!');
            return redirect()->back();
        }catch (\Exception $e) {
            session()->put('error','Gagal upload!');
            return redirect()->back();
        }
    }


    public function export_pdf(Request $request){


        // return json_encode($request->all());
    $data = User::with('role','company','partner','division','position')->where('company_id', Auth::user()->company->id);
        if (!empty ($request->get('partner_id_filter')) ){
            $data = $data->where('partner_id', $request->get('partner_id_filter'));
        };
        if (!empty ($request->get('division_id_filter')) ){
            $data = $data->where('division_id', $request->get('division_id_filter'));
        };
        if (!empty ($request->get('status_id_filter')) ){
            if($request->get('status_id_filter') == '1'){
                $data = $data->where('is_active', '1');
            }else{
                $data = $data->where('is_active', null);
            }
        };


        // return json_encode($data->get());
        $inset['user'] = $data->get();
        $inset['company'] = strtoupper(Auth::user()->company->name);


        $pdf = PDF::loadView('dashboard.member.cetak', $inset)->setPaper('a4', 'landscape');
        return $pdf->stream('ceklist_harian.pdf');
            // return $pdf->download('export.pdf');


    }

}