<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Fel_library {

    public function __construct() {
        $this->ci =& get_instance();
    }

    // Función para generar token
    public function generarToken($usuario, $clave, $api_pad) {
        // Preparar datos
        $data = [
            'usuario' => $usuario,
            'clave'   => $clave
        ];

        // Llamada cURL al API TEST
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_pad . '/auth/token'); // endpoint de prueba
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);

        $response = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $result = json_decode($response, true);

        if($httpcode == 200 && isset($result['token'])) {
            return [
                'success' => true,
                'token' => $result['token'],
                'expiracion' => date('Y-m-d H:i:s', strtotime('+1 hour')) // ejemplo expiración 1 hora
            ];
        } else {
            return [
                'success' => false,
                'message' => $result['message'] ?? 'Error desconocido'
            ];
        }
    }
}
