<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\UserProfile;

class UserProfileController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'name'          => 'required|string|max:255',
            'email'         => 'required|email|max:255',
            'gender'        => 'required|in:laki-laki,perempuan',
            'day'           => 'required|integer|min:1|max:31',
            'month'         => 'required|integer|min:1|max:12',
            'year'          => 'required|integer|min:1900|max:' . date('Y'),
            'voice_keyword' => 'required|string|max:255',
        ]);

        $birthDate = $request->year . '-' . str_pad($request->month, 2, '0', STR_PAD_LEFT) . '-' . str_pad($request->day, 2, '0', STR_PAD_LEFT);

        UserProfile::create([
            'name'            => $request->name,
            'email'           => $request->email,
            'gender'          => $request->gender,
            'birth_date'      => $birthDate,
            'voice_keyword'   => $request->voice_keyword,
            'face_registered' => DB::raw('false'),
        ]);

        return redirect()->route('dashboard')->with('success', 'Data berhasil disimpan');
    }

    public function index()
    {
        $users = UserProfile::latest()->get();

        return view('dashboard', compact('users'));
    }

    public function histori()
    {
        $logs = \App\Models\AccessLog::with('user')->latest()->get();

        $totalLogs = \App\Models\AccessLog::count();
        $successLogs = \App\Models\AccessLog::whereRaw('LOWER(status) IN (?, ?)', ['success', 'sukses'])->count();
        $failedLogs = \App\Models\AccessLog::whereRaw('LOWER(status) IN (?, ?)', ['failed', 'gagal'])->count();

        return view('histori', compact(
            'logs',
            'totalLogs',
            'successLogs',
            'failedLogs'
        ));
    }
}