<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\Helpers\GlobalHelper;
use App\Models\User;
use App\Models\OtoritasModul;
use View;
use DB;

class UserController extends Controller
{
    public function get_user($search,$limit=10){
      $query=User::select('user.*','hak_akses.hak_akses')
        ->join('hak_akses','hak_akses.id','=','user.fid_hak_akses');
      if(!empty($search)){
        $query=$query->where(function ($i) use ($search) {
            $i->where('user.nama_lengkap', 'like', "%{$search}%")
              ->orWhere('user.username', 'like', "%{$search}%")
              ->orWhere('hak_akses.hak_akses', 'like', "%{$search}%");
         });
      }
      $result=$query->whereNull('user.deleted_at')->orderBy('user.fid_hak_akses')->orderBy('user.nama_lengkap')->paginate(10);
      if(!empty($search)){
        $result->withPath('user?search='.$search);
      }
      return $result;
    }

    public function user(Request $request){
      $search=(!empty($request->search) ? $request->search : null );
      $data['user']=$this->get_user($search);
      $data['hak_akses']=DB::table('hak_akses')->get();
      return view('manajemen_user.user')
        ->with('search',$search)
        ->with('data',$data)
        ->with('menu','Manajemen User')
        ->with('submenu','Data User');
    }

    public function proses_user(Request $request){
      if($request->action == 'add'){
        $cek_user = User::where('username',$request->username)->first();
        if(empty($cek_user)){
          $field=new User;
          $field->created_at = date('Y-m-d H:i:s');
          $field->created_by = Session::get('useractive')->nama_lengkap;
          $field->created_by_id = Session::get('useractive')->id;
          $msg ='Data User berhasil ditambahkan';
        }
        else{
          return redirect()->back()
            ->with('message','Username sudah tersedia, silahkan menggunakan username yang lain')
            ->with('message_type','warning');
        }
      }
      else{
        $cek_username = User::where('username',$request->username)->where('id','!=',$request->id)->first();
        if(empty($cek_username)){
          $cek_nik = User::where('nik',$request->nik)->where('id','!=',$request->id)->first();
          if(empty($cek_nik) || $request->action == 'delete' ){
            $field=User::find($request->id);
            $field->modified_at = date('Y-m-d H:i:s');
            $field->modified_by = Session::get('useractive')->nama_lengkap;
            $field->modified_by_id = Session::get('useractive')->id;
            $msg='Data User berhasil disimpan';
          }
          else{
            return redirect()->back()
              ->with('message','NIK sudah tersedia, silahkan menggunakan NIK yang lain')
              ->with('message_type','warning');
          }
        }
        else{
          return redirect()->back()
            ->with('message','Username sudah tersedia, silahkan menggunakan username yang lain')
            ->with('message_type','warning');
        }
      }
      if($request->action == 'delete'){
        $field->deleted_at = date('Y-m-d H:i:s');
        $field->deleted_by = Session::get('useractive')->nama_lengkap;
        $field->deleted_by_id = Session::get('useractive')->id;
        $msg = 'Data user berhasil dihapus';
      }
      else{
        $field->nama_lengkap=$request->nama_lengkap;
        $field->nik=$request->nik;
        $field->username=$request->username;
        if(!empty($request->password)){
          $field->password=encrypt($request->password);
        }
        else{
          $field->password=($request->action == 'add' ? encrypt($request->username) : $field->password );
        }
        $field->fid_hak_akses=$request->hak_akses;
        $field->no_handphone=$request->no_handphone;
        $field->email=$request->email;
        $field->alamat=$request->alamat;
        if($request->hasFile('foto')){
          if (file_exists(storage_path('app/'.$field->foto))) {
            if(!empty($field->foto)){
              unlink(storage_path('app/'.$field->foto));
            }
          }
          $uploadedFile = $request->file('foto');
          $path = $uploadedFile->store('user');
          $field->foto=$path;
        }
      }
      $field->save();
      return redirect()->back()
        ->with('message',$msg)
        ->with('message_type','success');
    }

    // --------------------- OTORITAS MODUL ------------------------//

    public function get_modul($hak_akses,$parent){
      $data=DB::table('modul')->select('id','nama_modul','order')->where('parent_id',$parent)->orderBy('order')->get();
      foreach ($data as $key => $value) {
        $submodul = $this->get_modul($hak_akses,$value->id);
        $data[$key]->otoritas=GlobalHelper::otoritas_modul($hak_akses,$value->id);
        $data[$key]->submodul = $submodul;
      }
      return $data;
    }

    public function otoritas_modul(Request $request){
      $hak_akses=(!empty($request->hak_akses) ? $request->hak_akses : 1 );
      $data['hak_akses']=DB::table('hak_akses')->get();
      $data['modul']=$this->get_modul($hak_akses,0);
      return view('manajemen_user.otoritas_modul')
        ->with('data',$data)
        ->with('hak_akses',$hak_akses)
        ->with('menu','Manajemen User')
        ->with('submenu','Otoritas Modul');
    }

    public function proses_otoritas_modul(Request $request){
      foreach ($request->id as $id) {
        $otoritas=OtoritasModul::where('fid_modul','=',$id)
          ->where('fid_hak_akses','=',$request->hak_akses)
          ->delete();
        $field=new OtoritasModul;
        $field->fid_hak_akses=$request->hak_akses;
        $field->fid_modul=$id;
        $field->is_view=((!empty($request->view[$id])) ? 'Y' : 'N');
        $field->is_insert=((!empty($request->insert[$id])) ? 'Y' : 'N');
        $field->is_update=((!empty($request->update[$id])) ? 'Y' : 'N');
        $field->is_delete=((!empty($request->delete[$id])) ? 'Y' : 'N');
        $field->save();
      }
      return redirect()->back()
        ->with('message','Otoritas Modul berhasil disimpan')
        ->with('message_type','success');
    }
}
