<?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\Admin;
use App\Http\Models\Provinsi;
use App\Http\Models\Kabupaten;
use App\Http\Models\Kecamatan;
use App\Http\Libraries\CompresImage;
use File, Sentinel, Redirect, Validator;

class AdminController extends Controller
{
    public function index(Request $request)
    {
        if (Sentinel::getUser()->level_user==1) {
            $data['level'] = Sentinel::getUser();
            $data['mn_active'] = "users";
            $data['title'] = "Admin";
            $data['smallTitle'] = "Menampilkan seluruh User Admin";
            return view('users.admin.main', $data);
        }else{
            return Redirect::route('home')->with('title', 'Maaf !')->with('message', 'Anda Tidak Mempunyai Akses Ke Halaman Ini !!')->with('type', 'warning');
        }
    }

    public function datagrid(Request $request)
    {
        $data = Admin::getJson($request);
        return response()->json($data);
    }

    public function formAdd(Request $request)
    {
        $data['provinsis'] = Provinsi::all();
        $content = view('users.admin.formAdd', $data)->render();
        return ['status' => 'success', 'content' => $content];
    }

    public function add(Request $request)
    {
        $cekMail = Users::where('email',$request->email)->first();
        if (count($cekMail) == 0) {
            $cekNik = Users::where('nik',$request->nik)->first();
            if (count($cekNik) == 0) {
                $token = str_random(15).substr(md5(date('Y-m-d H:i:s', strtotime('now'))), -15);
                $user = Sentinel::registerAndActivate([
                    'email' => $request->email,
                    'password' => $request->nik,
                ]);
                $user->nik = $request->nik;
                $user->token = $token;
                $user->nama = $request->nama;
                $user->level_user = '1';
                $user->active = '1';
                if (!empty($request->foto)) {
                    date_default_timezone_set('Asia/Jakarta');
                    $ukuranFile = filesize($request->foto);
                    if ($ukuranFile <= 500000) {
                        $ext_foto = $request->foto->getClientOriginalExtension();
                        $filename = "Admin_".date('Ymd-His')."_".$request->nik.".".$ext_foto;
                        $temp_foto = 'dist/img/users/';
                        $proses = $request->foto->move($temp_foto, $filename);
                        $user->foto = $filename;
                    }else{
                        $file=$_FILES['foto']['name'];
                        if(!empty($file)){
                            $direktori="dist/img/users/"; //tempat upload foto
                            $name='foto'; //name pada input type file
                            $namaBaru="Admin_".date('Ymd-His')."_".$request->nik; //name pada input type file
                            $quality=50; //konversi kualitas gambar dalam satuan %
                            $upload = CompresImage::UploadCompress($namaBaru,$name,$direktori,$quality);
                        }
                        $ext_foto = $request->foto->getClientOriginalExtension();
                        $user->foto = $namaBaru.".".$ext_foto;
                    }
                }
                $user->save();

                $center = new Admin;
                $center->nama_admin = $request->nama;
                $center->tgl_lahir = date('Y-m-d', strtotime($request->tgl_lahir));
                $center->alamat = $request->alamat;
                $center->provinsi_id = $request->provinsi_id;
                $center->kabupaten_id = $request->kabupaten_id;
                $center->kecamatan_id = $request->kecamatan_id;
                $center->jenis_kelamin = $request->jenis_kelamin;
                $center->no_tlp = $request->no_tlp;
                $center->users_id = $user->id;
                $center->save();

                if ($center) {
                    return Redirect::route('admin')->with('title', 'Berhasil !')->with('message', 'Admin Berhasil Dibuat !!')->with('type', 'success');
                } else {
                    return Redirect::route('admin')->with('title', 'Maaf !!!')->with('message', 'Admin Gagal Dibuat !!')->with('type', 'error');
                }
            }else{
                return Redirect::route('admin')->with('title', 'Maaf !!!')->with('message', 'Username Sudah Digunakan !!')->with('type', 'warning');
            }
        }else{
            return Redirect::route('admin')->with('title', 'Maaf !!!')->with('message', 'Email Sudah Digunakan !!')->with('type', 'warning');
        }
    }

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

    public function nonActive(Request $request)
    {
        $center = Admin::find($request->id);
        $user_id = $center->users_id;
        $user = Users::find($user_id);
        $user->active = '0';
        $user->save();

        if($user){
            return ['status' => 'success'];
        }
        return ['status'=>'error'];
    }

    public function active(Request $request)
    {
        $center = Admin::find($request->id);
        $user_id = $center->users_id;
        $user = Users::find($user_id);
        $user->active = '1';
        $user->save();

        if($user){
            return ['status' => 'success'];
        }
        return ['status'=>'error'];
    }

    public function resetPassword(Request $request)
    {
        $center = Admin::find($request->id);
        $user_id = $center->users_id;

        $user = Sentinel::findById($user_id);
        $nik = $user->nik;
        $credentials = [
            'password' => $nik,
        ];
        $user = Sentinel::update($user, $credentials);
        if ($user) {
            return ['status' => 'success', 'message' => 'Password Successfully Reset !!'];
        } else {
            return ['status'=>'error', 'message'=>'Password Failed to Reset !!'];
        }
    }

    public function formEdit(Request $request)
    {
        $data['admin'] = Admin::find($request->id);
        if (!empty($request->asal)) {
            $data['asal'] = $request->asal;
        }
        $data['provinsis'] = Provinsi::all();
        $data['kabupatens'] = Kabupaten::where('provinsi_id',$data['admin']->provinsi_id)->get();
        $data['kecamatans'] = Kecamatan::where('kabupaten_id',$data['admin']->kabupaten_id)->get();
        $content = view('users.admin.formEdit',$data)->render();
        return ['status' => 'success', 'content' => $content];
    }

    public function edit(Request $request)
    {
        $center = Admin::find($request->id_admin);
        $center->nama_admin = $request->nama;
        $center->tgl_lahir = date('Y-m-d', strtotime($request->tgl_lahir));
        $center->alamat = $request->alamat;
        $center->provinsi_id = $request->provinsi_id;
        $center->kabupaten_id = $request->kabupaten_id;
        $center->kecamatan_id = $request->kecamatan_id;
        $center->jenis_kelamin = $request->jenis_kelamin;
        $center->no_tlp = $request->no_tlp;
        $center->save();

        $user = Users::find($center->users_id);
        $user->nama = $request->nama;
        if (!empty($request->foto)) {
            if ($user->foto != null) {
                File::delete('dist/img/users/'.$user->foto);
            }
            date_default_timezone_set('Asia/Jakarta');
            $ukuranFile = filesize($request->foto);
            if ($ukuranFile <= 500000) {
                $ext_foto = $request->foto->getClientOriginalExtension();
                $filename = "Admin_".date('Ymd-His')."_".$request->nik.".".$ext_foto;
                $temp_foto = 'dist/img/users/';
                $proses = $request->foto->move($temp_foto, $filename);
                $user->foto = $filename;
            }else{
                $file=$_FILES['foto']['name'];
                if(!empty($file)){
                    $direktori="dist/img/users/"; //tempat upload foto
                    $name='foto'; //name pada input type file
                    $namaBaru="Admin_".date('Ymd-His')."_".$request->nik; //name pada input type file
                    $quality=50; //konversi kualitas gambar dalam satuan %
                    $upload = CompresImage::UploadCompress($namaBaru,$name,$direktori,$quality);
                }
                $ext_foto = $request->foto->getClientOriginalExtension();
                $user->foto = $namaBaru.".".$ext_foto;
            }
        }
        $user->save();

        if ($center) {
            if (!empty($request->asal)) {
                return Redirect::route('profile')->with('title', 'Berhasil !')->with('message', 'Profile Berhasil Diperbaharui !!')->with('type', 'success');
            }else{
                return Redirect::route('admin')->with('title', 'Berhasil !')->with('message', 'Admin Berhasil Diperbaharui !!')->with('type', 'success');
            }
        } else {
            if (!empty($request->asal)) {
                return Redirect::route('profile')->with('title', 'Maaf !!!')->with('message', 'Profile Gagal Diperbaharui !!')->with('type', 'error');
            }else{
                return Redirect::route('admin')->with('title', 'Maaf !!!')->with('message', 'Admin Gagal Diperbaharui !!')->with('type', 'error');
            }
        }
    }

    public function delete(Request $request)
    {
        $center = Admin::find($request->id);
        if(!empty($center)){
            $id_user = $center->users_id;
            $user = Sentinel::findById($id_user);
            $nama_file = $user->foto;
            $center->delete();
            $user->delete();
            if ($nama_file != null) {
                File::delete('dist/img/users/'.$nama_file);
            }
            return ['status' => 'success', 'message' => 'Data berhasil dihapus'];
        }else{
            return ['status'=>'error', 'message'=>'Invalid user.'];
        }
    }
}
