<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\User;
use App\Role;
use App\Dashboard;


class KakitanganController extends Controller
{
    public function __construct(){
        $this->middleware('auth');
    }

    public function daftarKakitangan(){
        $api_url = config('api.url');
        $auth_user = Auth::user();
        $cawangan_info = Http::get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();
        $role = Role::get();
        return view('operasi.daftar_kakitangan',compact('cawangan_info','api_url','role'));
    }

    public function registerStaff(Request $request){
        
        $validated = $request->validate([
            'nama' => 'required',
            'email' => 'required|email',
            'nokp' => 'required',
            'telefon' => 'required',
            'role' => 'required'
        ]);

        if($request->role == 'operasi'){
            $new_dashboard = Dashboard::create([
                'name' => $request->nama,
                'email' => $request->email,
                'password' => Hash::make($request->nokp),
                'no_kp' => $request->nokp,
                'no_telefon' => $request->telefon,
                'roles' => $request->role
            ]);
        }

        $new_staff = User::create([
            'name' => $request->nama,
            'email' => $request->email,
            'password' => Hash::make($request->nokp),
            'no_kp' => $request->nokp,
            'no_telefon' => $request->telefon,
            'roles' => $request->role,
            'cawangan' => $request->cawangan
        ]);

        return redirect()->route('daftar.kakitangan');
    }

    public function kakitanganHarian(Request $request){
        $auth_user = Auth::user();
        $user_cawangan = User::where('cawangan','=',$auth_user['cawangan'])->get();

        foreach($user_cawangan as $index=>$user){
            if($user['roles'] == 'teller'){
                if($user['id'] == $request->penilai){
                    $role_harian = 'penilai';
                }else{
                    $role_harian = 'teller';
                }
            }elseif($user['roles'] == 'ppc'){
                if($user['id'] == $request->khazanah){
                    $role_harian = 'khazanah';
                }else{
                    $role_harian = 'ppc';
                }
            }elseif($user['roles'] == 'pc'){
                if($user['id'] == $request->khazanah){
                    $role_harian = 'khazanah';
                }else{
                    $role_harian = 'pc';
                }
            }

            User::where('id','=',$user['id'])->update(array(
                'role_harian' => $role_harian
            ));
        }

        return redirect()->route('home');
    }
}
