<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

// Library
use DB;
use Str;
use Illuminate\Support\Facades\Hash;

use App\Models\User\UserModel;
use App\Models\Master\PeriodeModel;
use App\Models\User\UserUsulanModel;
use App\Models\Log\LogUploadSuratKepsekModel;

class AuthController extends Controller
{   
    private $views      = 'auth';
    private $url        = '';
    private $title      = 'Halaman Authentifikasi';

public function __construct()
    {
        createLogActivity();
        $this->mUser            = new UserModel();
        $this->mPerpusPeriode   = new PeriodeModel();
        $this->mUserUsulan      = new UserUsulanModel();
        $this->mLogSuratKepsek  = new LogUploadSuratKepsekModel();
        $this->mPeriode               = New PeriodeModel();
    
    }

    //LOGIN
    public function login()
    {
        // session()->flush();

        // if(session()->get('users_id') != null){
        //     return redirect('admin/dashboard');
        // }

        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
        ];
        return view($this->views . "/index", $data);
    }

    //proses
    public function loginProses(Request $request)
    {
        // Validate
        $request->validate([
            'username'                  => 'required',
            // 'login.*'                => 'required', // untuk semua array
            'login.password'            => 'required',
            'g-recaptcha-response'      => 'required|captcha',
        ],[
            'username.required'         => 'Mohon masukkan Username',
            'login.password.required'   => 'Mohon masukkan Password',
            'g-recaptcha-response.required'          => 'Mohon masukkan Captcha',
            'g-recaptcha-response.captcha'           => 'Captcha yang anda masukkan salah',
        ]);
        // echo json_encode($request->all()); die;

        // Get Data
        $users = $this->mUser->where('username', $request->username)->first();
        
        // Check User
        if ($users == null) {
            return redirect()->back()->with('gagal', 'Pengguna Tidak Ditemukan');
        }
        
        // Check User Status
        if ($users->status == 0) {
            return redirect()->back()->with('gagal', 'Pengguna Tidak Aktif');
        }
        // Check User Password
        if (Hash::check($request->login['password'], $users->password) == false) {
            return redirect()->back()->with('gagal', 'Kata Sandi Salah');
        }
        // Table user and Update Last Login
        $dataUser = [
            'last_login' => date('Y-m-d H:i:s'),
        ];
        $this->mUser->where('id', $users->id)->update($dataUser);
        // echo json_encode($users); die;
        // Create Session

        $session = [
            'users_id'      => $users->id,
            'username'      => $users->username,
            'nama'          => $users->nama,
            'role'          => $users->role,
            'isLogin'       => true,
            'idPSekolah'    => $users->idPSekolah,
            'idSKonselor'   => $users->idSKonselor,
            'idPPeriode'    => $users->idPPeriode,
        ];
        session($session);

        return redirect('admin/dashboard')->with('sukses', 'Berhasil Login');
    }

    public function reloadCaptcha()
    {
        return response()->json(['captcha'=> captcha_img()]);
    }

    //REGISTER
    public function register()
    {
        $periode            = $this->mPeriode->get();
        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
            'periode'       => $periode,
        ];
        return view($this->views . "/create", $data);
    }

    public function registerProses(Request $request){
        $request->validate([
            'idMProvinsi'           => 'required',
            'idMDaerah'             => 'required',
            'idPPeriode'            => 'required',
            'npsn'                  => 'required|unique:users,username|numeric',
            'nama'                  => 'required',
            'admin'                 => 'required',
            'nomor'                 => 'required|numeric|unique:users,telp',
            'surat'                 => 'required|mimes:pdf|max:10000',
        ],[
            'idMProvinsi.required'  => 'Mohon Pilih Provinsi',
            'idMDaerah.required'    => 'Mohon masukkan Daerah',
            'idPPeriode.required'   => 'Mohon masukkan Periode',
            'npsn.required'         => 'Mohon masukkan NPSN',
            'npsn.unique'           => 'NPSN sudah terdaftar, mohon kontak admin',
            'npsn.numeric'          => 'Isian harus angka',
            'nama.required'         => 'Mohon masukkan Nama Sekolah',
            'admin.required'        => 'Mohon masukkan nama admin sekolah',
            'nomor.required'        => 'Mohon masukkan nomor admin sekolah',
            'nomor.numeric'         => 'Isian harus angka',
            'nomor.unique'          => 'Nomor sudah terdaftar, mohon kontak admin',
            'surat.required'        => 'Mohon masukkan NPSN',
            'surat.mimes'           => 'Mohon masukkan Format PDF',
            'surat.max'             => 'Max upload 1 MB',
        ]);

        if (isset($request->surat)) {
            if ($request->hasFile('surat')) {
                $file       = $request->file('surat');
                $fileName   = Str::uuid()."-".time().".".$file->extension();
                $file->move( "upload/surat_usulan/", $fileName);
            }
        }

        // Table user
        $dataUserUsulan = [
            'idMProvinsi'   => $request->idMProvinsi,
            'idMDaerah'     => $request->idMDaerah,
            'idPPeriode'    => $request->idPPeriode,
            'npsn'          => $request->npsn,
            'nama'          => $request->nama,
            'admin'         => $request->admin,
            'nomor'         => $request->nomor,
            'surat'         => $fileName,
        ];
        $userUsulan = $this->mUserUsulan->create($dataUserUsulan);

        $logUpload = [
            'idUserUsulan'  => $userUsulan->id,
            'ip'            => request()->ip(),
            'img'           => $fileName,
        ];
        $this->mLogSuratKepsek->create($logUpload);
        
        return redirect('/login')->with('sukses', 'Berhasil Daftar, Silahkan Menunggu Admin untuk Mengkonfirmasi');
    }

    public function updatePassword()
    {
        if(!session()->get('users_id')){
            return redirect('/login');
        }

        $data = [
            'title'         => $this->title,
            'url'           => $this->url,
        ];
        return view($this->views . "/edit", $data);
    }

    public function updateProses(Request $request)
    {

        $users = $this->mUser->where('id', session()->get('users_id'))->first();
        
        // Check User Password
        if (Hash::check($request->login['password'], $users->password) == false) {
            return redirect("$this->url/update-password")->with('gagal', 'Password Salah');
        }

        if ($request->login['password'] == $users->password) {
            return redirect("$this->url/update-password")->with('gagal', 'Password Baru sama dengan Password Lama');
        }

        if ($request->login['password_new'] != $request->login['password_verif']) {
            return redirect("$this->url/update-password")->with('gagal', 'Verifikasi password harus sama dengan password baru');
        } else {
            $dataUser = [
                'password'      => Hash::make($request->login['password_new']),
                'sandi'         => $request->login['password_new'],
            ];
            $this->mUser->where('id', session()->get('users_id'))->update($dataUser);

            session()->flush();
            return redirect("$this->url")->with('sukses', 'Password berhasil di rubah');
        }
    }

    public function logout()
    {
        session()->flush();
        return redirect('login');
    }
}