<?php

namespace App\Http\Controllers\Admin\AdminSession;

use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\Fail;
use App\Models\Session;
use App\Models\Success;

class AdminSessionController
{
    public function index(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'AccountAdmin' => 'required|string|max:50',
            'PasswordAdmin' => 'required|string|max:50',

        ]);
        if ($validator->fails()) {
            return json_encode(new Fail(
                success: false,
                error: $validator->errors()
            ));
        }

        $admin = Admin::where('AccountAdmin', $request->input('AccountAdmin'))
            ->where('PasswordAdmin', sha1($request->input('PasswordAdmin')))
            ->get();

        if (count($admin) <= 0) {
            return json_encode(new Fail(
                success: false,
                error: "Admin account does not exist"
            ));
        }
        $current_date = now();
        $date_24_hours = now()->addHours(24);
        $session = new Session();
        $session->IdAdmin = $admin[0]->IdAdmin;
        $session->DateStartSession = $current_date;
        $session->DateEndSession = $date_24_hours;
        $session->StatusSession = 1;
        $session->TokenSession = bin2hex(random_bytes(32));
        $session->save();

        return json_encode(
            new Success(
                true,
                "Admin found",
                (object)[
                    "TokenSession" => $session->TokenSession,
                    "IdAdmin"=>$session->IdAdmin
                ]
            )
        );
    }
}
