<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Master\MasterGroupUser;
use App\Models\Master\Provinsi;
use App\Models\Master\Sekolah;
use App\Models\ProfileSekolah as Profile;

class CustomRegisterController extends Controller
{
    public function index()
    {
        if(Auth::check()){
            return redirect('dashboard');
        }
        $data['title'] = 'Register';
        $data['provinsi'] = Provinsi::where('kode_wilayah','010000')->get();
        return view('auth.register',$data);
    }

    public function post_register(Request $request)
    {

        // dd($request->all());
        DB::beginTransaction();
        try {
            Validator::make($request->all(), [
                'email'           => 'required|unique:users|email',
                // 'name'            => 'required|max:50',
                // 'provinsi'        => 'required',
                // 'kabupaten'       => 'required',
                // 'kecamatan'       => 'required',
                // 'sekolah'         => 'required',
                // 'tingkat_sekolah' => 'required',
                // 'status_sekolah'  => 'required',
                'npsn'            => 'required',
                'alamat_sekolah'  => 'required',
                'kontak_person'   => 'required',
                'telp'            => 'required',
                'check'           => 'required',
                'password'        => 'required|min:8|max:15|regex:/[a-z]/|regex:/[A-Z]/|regex:/[0-9]/|regex:/[@$!%*#?&]/', //min 8 char, maks 15 char, min 1 symbol, min 1 uppercase, min 1 lowercase, 1 number
            ],[
                'password.min' => 'password Minimal 8 Karakter',
                'password.max' => 'password Maksimal 15 Karakter',
                'password.regex' => 'Format Kata Sandi harus mengandung minimal Huruf Besar, Huruf Kecil, Angka, Spesial Karakter',
            ])->validate();



            $cek = Profile::where('npsn',$request->npsn)->count();
            if($cek > 0){
                // return response()->json(['status' => false,'message' => 'Untuk NPSN :'.$request->npsn.' Sudah terdaftar! Silahkan Login','type' => 'error']);
                return redirect('register')->with([
                     'message' => 'Untuk NPSN :'.$request->npsn.' Sudah terdaftar! Silahkan Login',
                     'type'    => "error"
                ])->withInput();
            }

            $sekolah = Sekolah::where('npsn',$request->npsn)->first();
            if(!@$sekolah){
                
                $user = new User;
                $user->email    = $request->email;
                $user->username = $request->npsn;
                $user->password = Hash::make($request->password);
                $user->name     = $request->name;
                $user->ms_group_id = 2;
                $user->save();

                Auth::attempt(['username' => $request->npsn, 'password' => $request->password]); 

                $session = [
                    'username'                  => $request->username,
                    'name'                      => $user->name,
                    'email'                     => $user->email,
                    'sekolah_id'                => @$user->profile->sekolah->MsSekolahId,
                    'npsn'                      => @$request->npsn,
                    'tingkat_sekolah'           => @$user->profile->tingkat->name,
                    'status_sekolah'            => @$user->profile->status_sekolah,
                    'alamat_sekolah'            => @$request->alamat_sekolah,
                    'kontak_person'             => @$request->kontak_person,
                    'telp'                      => @$request->telp,
                    'currYear'                  => date('Y'),
                    'group_id'                  => @$user->ms_group_id,
                    'kabupaten_id'              => @$user->ms_kabupaten_id,
                    'group_alias'               => @$user->group->alias,
                    'group_name'                => @$user->group->name,
                ];
                session($session);
                DB::commit();
                return redirect('profile-sekolah/lengkapi/'.encode_id($request->npsn));
            }

            $user = new User;
            $user->email    = $request->email;
            $user->username = $sekolah->npsn;
            $user->password = Hash::make($request->password);
            $user->name     = $sekolah->nama_sekolah;
            $user->ms_group_id = 2;
            $user->save();

            $profile = new Profile;
            $profile->user_id               = $user->id;
            $profile->ms_provinsi_id        = $sekolah->ms_provinsi_id;
            $profile->ms_kabupaten_id       = $sekolah->ms_kabupaten_id;
            $profile->ms_kecamatan_id       = $sekolah->ms_kecamatan_id;
            $profile->ms_sekolah_id         = $sekolah->MsSekolahId;
            $profile->npsn                  = $sekolah->npsn;
            $profile->ms_tingkat_sekolah_id = $sekolah->ms_tingkat_sekolah_id;
            $profile->status_sekolah        = $sekolah->status;
            $profile->alamat_sekolah        = $request->alamat_sekolah;
            $profile->kontak_person         = $request->kontak_person;
            $profile->telp                  = $request->telp;
            $profile->save();

            $group = new MasterGroupUser;
            $group->user_id     = $user->id;
            $group->ms_group_id = 2; //sekolah
            $group->save();

            
                Auth::attempt(['username' => $request->npsn, 'password' => $request->password]); 

                $session = [
                    'username'                  => $user->username,
                    'name'                      => $user->name,
                    'email'                     => $user->email,
                    'sekolah_id'                => @$user->profile->sekolah->MsSekolahId,
                    'npsn'                      => @$user->profile->npsn,
                    'tingkat_sekolah'           => @$user->profile->tingkat->name,
                    'status_sekolah'            => @$user->profile->status_sekolah,
                    'alamat_sekolah'            => @$user->profile->alamat_sekolah,
                    'kontak_person'             => @$user->profile->kontak_person,
                    'telp'                      => @$user->profile->telp,
                    'currYear'                  => date('Y'),
                    'group_id'                  => @$user->ms_group_id,
                    'kabupaten_id'              => @$user->ms_kabupaten_id,
                    'group_alias'               => @$user->group->alias,
                    'group_name'                => @$user->group->name,
                ];
                session($session);

                DB::commit();

                // return response()->json(['status' => true,'message' => 'Daftar Sekolah Berhasil','type' => 'success']);

                return redirect('dashboard')->with([
                        'message' => trans('Selamat datang kembali'),
                        'type'    => "success"
                ])->withInput();
                
                

            // return redirect('/login')->with([
            //     'message' => 'Berhasil membuat akun baru, silahkan login',
            //     'type' => 'success',
            // ]);


        } catch (Exception $e) {
            DB::rollBack();
            // return response()->json(['status' => false,'message' => $e->getMessage(),'type' => 'error']);
            return redirect('register')->with([
                     'message' => $e->getMessage(),
                     'type'    => "error"
                ])->withInput();
        }
    }
}
