<?php
namespace App\Controllers\Api;

use Core\Controller;
use App\Models\ApiToken;

class AuthController extends Controller
{
    private $APP_USERNAME = 'middleware_user';
    private $APP_PASSWORD = 'SuperSecret123';

    public function getToken()
    {
        $input = json_decode(file_get_contents("php://input"), true);
        $username = $input['username'] ?? '';
        $password = $input['password'] ?? '';

        if ($username !== $this->APP_USERNAME || $password !== $this->APP_PASSWORD) {
            http_response_code(401);
            echo json_encode(['error' => true, 'message' => 'Unauthorized']);
            exit;
        }

        // generate token
        $token = bin2hex(random_bytes(32));
        $expired_at = date('Y-m-d H:i:s', strtotime('+1 hour'));

        $tokenModel = new ApiToken();
        $tokenModel->insert($token, $expired_at);

        echo json_encode(['error' => false, 'token' => $token, 'expired_at' => $expired_at]);
        exit;
    }
}
