<?php

namespace App\Http\Controllers;

use App\LogSession;
use App\Cawangan;
use App\Logsession as AppLogsession;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

use Carbon\Carbon;
use App\Audit;

class LogController extends Controller
{

    

    

    public function logSession($kodcaw, Request $request)
    {
        $current = Carbon::now();
        $current = new Carbon();

        $logsession = Logsession::on('mysql7')->where('kodcaw', '=', $kodcaw)
        ->create([
            'nama' => $request->nama,
            'nokp' => $request->nokp,
            'kodcaw' => $request->kodcaw,
            'email' => $request->email,
            'taraf' => $request->taraf,

        ]);

        $audit = new Audit();
            $audit->users = $request->nama;
            $audit->actions = "Log Masuk";
            // $audit->norujukan = $norujukan;
            // $audit->old_data = $old_data;
            $audit->kodcaw =  $kodcaw;
            $audit->created_at = $current;
            $audit->updated_at = $current;
            $audit->save();


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

    public function checkNokpSession($kodcaw, $nokp, $tarikh)
    {

        $cawangan = Cawangan::on('mysql7')->where('kodcaw', '=', $kodcaw)->first();

        $checknokp = Logsession::on('mysql7')->where('kodcaw', '=', $kodcaw)
        ->where('nokp', '=', $nokp)
        ->where('created_at','LIKE',"%{$tarikh}%")
        ->get();

        if (sizeof($checknokp) != 0) {
            $newnokp = $nokp;
        } else {

            $newnokp = 'NULL';
        }
        return response()->json($newnokp);
    }

    public function logoutSession($kodcaw, Request $request)
    {
        $current = Carbon::now();
        $current = new Carbon();

        $logoutsession = Logsession::on('mysql7')->where('kodcaw', '=', $kodcaw)
        ->create([
            'nama' => $request->nama,
            'nokp' => $request->nokp,
            'kodcaw' => $request->kodcaw,
            'email' => $request->email,
            'taraf' => $request->taraf,

        ]);

        $audit = new Audit();
            $audit->users = $request->nama;
            $audit->actions = "Log Keluar";
            // $audit->norujukan = $norujukan;
            // $audit->old_data = $old_data;
            $audit->kodcaw =  $kodcaw;
            $audit->created_at = $current;
            $audit->updated_at = $current;
            $audit->save();


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

    
}
