<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Dosen;
use App\Models\Mahasiswa;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Yajra\DataTables\Facades\DataTables;

class UserController extends Controller
{
    private $activeMenu = 'Home/User & Akses';

    public function index(Request $request)
    {
        return view('pages.portal.master.user-access.index', [
            'breadcrumb' => [
                'Home' => '/',
                'Master' => '/',
                'User & Akses' => '/'
            ],
            'activeMenu' => $this->activeMenu,

        ]);
    }

    public function profile(Request $request)
    {
        return view('pages.portal.user.profile', [
            'breadcrumb' => [
                'Home' => '/',
                'Profile' => '/'
            ],
            'activeMenu' => 'Home/Profile',

        ]);
    }

    public function photochange(Request $request)
    {
        $dataValidated = $request->validate([
            'photo' => 'image|file|max:512'
        ]);

        $path = 'img/akun';
        if ($request->file('photo')) {
            if ($request->image_old) {
                Storage::delete('public/' . $request->image_old);
            }
            $dataValidated['photo'] = $request->file('photo')->store($path, 'public');
        }
        User::where('id', auth()->user()->id)
            ->update($dataValidated);

        return redirect('/user/profile')->with('success', 'Data berhasil disimpan');
    }

    public function changepassword(Request $request)
    {

        $rules = [
            'password_lama' => [
                'required',
                'min:6',
                function ($attribute, $value, $fail) {

                    $user = User::find(auth()->id());
                    if (!Hash::check($value, $user->password)) {
                        $fail('Password lama tidak sama.');
                    }
                }
            ],
            'password_baru' => 'required|min:6',
            'confirm_password' => 'required|min:6'
        ];

        $dataValidated = $request->validate($rules);
        $dataUpdate['password'] = Hash::make($dataValidated['confirm_password']);
        User::where('id', auth()->user()->id)
            ->update($dataUpdate);

        return redirect('/user/profile')->with('success', 'Password berhasil diperbaharui');
    }

    public function list(Request $request)
    {

        // if ($req->ajax()) {
        $data = User::leftJoin('prodis as p', 'p.id', 'users.position')
            ->select('users.*', 'p.kode');

        return DataTables::of($data)
            ->addIndexColumn()
            ->addColumn('action', function (User $user) {
                $actionBtn = '<a href="javascript:void(0)" class="delete btn btn-warning btn-xs" title="Reset" data-toggle="modal" data-target="#res' . $user->id . '"><i class="fas fa-redo-alt fa-sm"></i></a> ';

                if ($user->role != 'dosen' && $user->role != 'mahasiswa') {
                    $actionBtn .= ' <a href="' . url("/user/edit/" . $user->id . "") . '" class="edit btn btn-primary btn-xs"><i class="fas fa-edit fa-sm" title="Edit"></i></a> <a href="javascript:void(0)" class="delete btn btn-danger btn-xs" title="Hapus" data-toggle="modal" data-target="#del' . $user->id . '"><i class="fas fa-trash fa-sm"></i></a>
                    <div class="modal fade" id="del' . $user->id . '">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-body text-left pb-0">
                                <h4>Hapus data</h4>
                                    <p>Data yang dihapus tidak bisa dipulihkan kembali</p>
                                </div>
                                <div class="modal-footer pt-0 border-0 justify-content-end">
                                    <form action="' . url("/user/delete/" . $user->id . "") . '" method="post">
                                        <input type="hidden" name="_method" value="DELETE">
                                        <input type="hidden" name="_token" value="' . csrf_token() . '">
                                        <a href="javascript:void(0)" class="btn mr-2" data-dismiss="modal">Kembali</a>
                                        <button class="btn btn-danger">Hapus</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>';
                }
                $actionBtn .= '<div class="modal fade" id="res' . $user->id . '">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-body text-left pb-0">
                                    <h4>Reset password user</h4>
                                    <p>Password yang direset akan kembali ke semula sesuai dengan kebijakan <i>default role</i></p>
                                </div>
                                <div class="modal-footer  pt-0 border-0 justify-content-end">
                                    <form action="' . url("user/reset/" . $user->id . "") . '" method="post">
                                        <input type="hidden" name="_method" value="POST">
                                        <input type="hidden" name="_token" value="' . csrf_token() . '">
                                        <a href="javascript:void(0)" class="btn mr-2" data-dismiss="modal">Kembali</a>
                                        <button class="btn btn-warning">Reset</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    ';
                return $actionBtn;
            })
            ->addColumn('active', function (User $user) {
                $html = '<i class="fas fa-check fa-sm text-success"></i>';
                if ($user->access == 0)
                    $html = '<i class="fas fa-times fa-sm text-danger"></i>';

                return $html;
            })
            ->addColumn('verifikator', function (User $user) {
                $html = '';
                if ($user->role != 'mahasiswa') {

                    $html = '<input type="checkbox" name="be-verifikator" class="be-verifikator" data-id="' . $user->id . '" ' . ($user->verifikator == 1 ? 'checked' : '') . '>';

                    if ($user->role == 'admin' || $user->role == 'admin adak') {

                        $html = '<i class="fas fa-check fa-sm text-success"></i>';
                    }
                }

                return $html;
            })
            ->rawColumns(['action', 'active', 'verifikator'])
            ->make(true);
        // }

    }

    public function form(Request $request)
    {
        return view('pages.portal.master.user-access.form', [
            'breadcrumb' => [
                'Home' => '/',
                'Master' => '/',
                'User & Akses' => '/user',
                'Form Tambah' => '/'
            ],
            'activeMenu' => $this->activeMenu,
            'prodis' => $this->getProdiCombo()

        ]);
    }

    public function store(Request $request, User $user)
    {
        $rules = [
            'name' => 'required|min:3',
            'role' => 'required',
            'password' => 'required|min:6',
            'username' => 'required|min:3|unique:users'
        ];

        if ($request->role == 'admin prodi' || $request->role == 'kaprodi') {
            $rules['position'] = 'required|numeric';
        }

        $dataValidated = $request->validate($rules);
        $dataValidated['password'] = bcrypt($dataValidated['password']);
        $dataValidated['access'] = 1;

        if ($request->role == 'admin' || $request->role == 'admin adak') {
            $dataValidated['verifikator'] = 1;
        }
        User::create($dataValidated);

        return redirect('/user')->with('success', 'Data berhasil disimpan');
    }

    public function reset(Request $request)
    {
        $user = User::find($request->id);
        if ($user->role == 'admin' || $user->role == 'admin adak' || $user->role == 'admin prodi' || $user->role == 'kaprodi') {
            $data['password'] = bcrypt('123456');
        } elseif ($user->role == 'mahasiswa') {
            $mahasiswa = Mahasiswa::where('nim', $user->username)->first();
            $data['password'] = bcrypt(Str::replace('-', '', $mahasiswa->tgllahir));
        } elseif ($user->role == 'dosen') {
            $dosen = Dosen::where('kode', $user->username)->first();
            $data['password'] = bcrypt($dosen->nidn);
        }

        User::where('id', $request->id)
            ->update($data);

        return redirect('/user')->with('success', 'Password berhasil direset');
    }

    public function edit($id)
    {
        return view('pages.portal.master.user-access.form', [
            'breadcrumb' => [
                'Home' => '/',
                'Master' => '/',
                'User & Akses' => '/user',
                'Form Edit' => '/'
            ],
            'activeMenu' => $this->activeMenu,
            'user' => User::find($id),
            'id' => $id,
            'prodis' => $this->getProdiCombo()

        ]);
    }

    public function update(Request $request)
    {
        $userOrigin = User::find($request->id);
        $rules = [
            'name' => 'required|min:3',
            'role' => 'required'
        ];

        if ($request->role == 'admin prodi' || $request->role == 'kaprodi') {
            $rules['position'] = 'required|numeric';
        }

        if ($request->username != $userOrigin->username) {
            $rules['username'] = 'required|min:3|unique:users';
        }

        $dataValidated = $request->validate($rules);
        if ($request->password != '') {
            $dataValidated['password'] = bcrypt($request->password);
        }

        if ($request->role == 'admin' || $request->role == 'admin adak') {
            $dataValidated['verifikator'] = 1;
        }

        User::where('id', $request->id)
            ->update($dataValidated);


        return redirect('/user')->with('success', 'Data berhasil disimpan');
    }

    public function destroy($id)
    {
        User::destroy($id);
        return redirect('/user')->with('success', 'Data berhasil dihapus');
    }

    public function verifikator(Request $request)
    {
        $data = [
            'status' => 'Data tidak terkirim ke server'
        ];

        if ($request->ajax()) {

            $usr = User::find($request->id);

            if ($request->jenis == 'Simpan') {
                $usr->update([
                    'verifikator' => 1
                ]);
            } else {
                $usr->update([
                    'verifikator' => 0
                ]);
            }

            $data = [
                'status' => 'Data berhasil disimpan'
            ];
        }

        return response()->json($data);
    }
}
