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

class Token_connection extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->admin_model('token_connection_model');
    }

    public function conectar($clienteId) {
        $api_path = 'https://testnucgt.digifact.com/api/login/get_token';
        $nit = '105767640';
        $usuario = 'TESTUSER';
        $contraseña = 'ctPV7%x_';

        $data = array(
            'nit' => $nit,
            'usuario' => $usuario,
            'contraseña' => $contraseña
        );

        $ch = curl_init($api_path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code == 200) {
            $response_data = json_decode($response, true);
            if (isset($response_data['token'])) {
                $token = $response_data['token'];
                $expira = date('Y-m-d H:i:s', strtotime('+1 hour'));
                $this->Token_connection_model->guardar_token($clienteId, $token, $expira);
                echo json_encode(array('status' => 'success', 'token' => $token, 'expira' => $expira));
            } else {
                echo json_encode(array('status' => 'error', 'message' => 'No se pudo obtener el token.'));
            }
        } else {
            echo json_encode(array('status' => 'error', 'message' => 'No conectado.'));
        }
    }
}