<?php

namespace App\Http\Controllers\Management;

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

class UserSekolahController extends Controller
{
    protected $title = 'User Sekolah';
    protected $template = 'modules.management.user_sekolah';
    protected $route = 'modules.management.user_sekolah';

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Management & Akses Role'],
            ['name' => 'Data User','active' => true],
        ];
        $data['title'] = $this->title;
        $data['route'] = $this->route;
        return view($this->template.'.index',$data);
    }

    public function grid(Request $request)
    {

        $data = User::where('ms_group_id',2)->where('id','!=',auth()->user()->id)->orderBy('id','DESC')->get();
        $_data = [];


        foreach ($data as $key => $row) {


            $action = '';

            if((permission('is_create', $this->route.'.*','module',false)) || (permission('is_update', $this->route.'.*','module',false))){
                $action .= '<a href="'.url('management/user_sekolah/update/'.encode_id($row->id)).'" data-toggle="tooltip" title="Edit Data" class="btn btn-xs btn-block btn-primary"><i class="fal fa-pencil text-white"></i></a>';
                if(session('group_id') == 1){
                    $action .= '<a href="#" data-href="'.url('management/user/forcelogin/'.encode_id($row->id)).'" data-toggle="tooltip" title="Force Login" class="forcelogin btn btn-xs btn-block btn-success"><i class="fal fa-user text-white"></i></a>';
                    $action .= '<a href="#" data-href="'.url('management/user_sekolah/delete/'.encode_id($row->id)).'" data-toggle="tooltip" title="Edit Data" class="remove_data btn btn-xs btn-block btn-danger"><i class="fal fa-trash text-white"></i></a>';
                }
            }
            
           $_data[] = [
            'no'                => $key+1,
            'id'                => encode_id($row->id),
            'name'              => @$row->name,
            'username'          => @$row->username,
            'email'             => @$row->email,
            'created_at'        => dateTime(@$row->created_at),
            'action'            => @$action,
        ];

        }

        // return response()->json($_data);  // Return the data as a JSON response
        return response()->json($_data);

    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {

            $keyId = decode_id($request->secure_id);

            Validator::make($request->all(), [
                    // 'email'           => 'required|unique:users|email',
                    'name'            => 'required|max:50',
                    'npsn'            => 'required|unique:users,username,'.$keyId,
                    'tingkat_sekolah' => 'required',
                    'status_sekolah'  => 'required',
                    'alamat_sekolah'  => 'required',
                    'kontak_person'   => 'required',
                    'telp'            => 'required',
                    'password'        => 'nullable|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();

            
            $user = User::find($keyId);
            $user->username = $request->npsn;
            if(@$request->password){
                $user->password = Hash::make($request->password);
            }
            $user->name     = $request->name;
            $user->save();

            $profile = Profile::where('user_id',$keyId)->first();
            $profile->npsn                  = $request->npsn;
            $profile->ms_tingkat_sekolah_id = $request->tingkat_sekolah;
            $profile->status_sekolah        = $request->status_sekolah;
            $profile->alamat_sekolah        = $request->alamat_sekolah;
            $profile->kontak_person         = $request->kontak_person;
            $profile->telp                  = $request->telp;
            $profile->save();

            return redirect()->back()->with([
                'message' => 'Berhasil update data',
                'type'    => 'success',
            ]);
            
        } catch (Exception $e) {
            return redirect()->back()->with([
                     'message' => $e->getMessage(),
                     'type'    => "error"
                ]);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update($id)
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Management & Akses Role'],
            ['name' => 'Data User Sekolah','active' => true],
        ];
        $keyId = decode_id($id);
        $data['title'] = $this->title;
        $data['route'] = $this->route;
        $data['keyId'] = $id;
        $data['item'] = User::with('profile')->where('id',$keyId)->first();
        return view($this->template.'.form',$data);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

    public function delete($id)
    {
        $keyId = decode_id($id);

        $user = User::where('id',$keyId)->delete();

        return response()->json(['success' => true,'message' => 'Berhasil update data','type' => 'success']);
    }
}
