

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '/var/www/sklink.sinhro.si/komponentko/config.php';

$shortURL = rtrim($_SERVER['REQUEST_URI'], '/');
$shortURL = substr($shortURL, strrpos($shortURL, '/') + 1);

$length = strlen($shortURL);

if ($length < 5) {
    header("Location: https://komponentko.si");
    exit;
}

$cleanShortURL = str_replace('-', '', $shortURL);
$id = decodeShortURL($cleanShortURL);

if (!$id) {
    echo "The requested URL not found.";
    exit;
}

// DB connect
$conn = mysqli_init();
$conn->ssl_set($ssl_cert_path, null, null, null, null);
$conn->real_connect(
    $host_ch,
    $username_ch,
    $password_ch,
    $database_ch,
    (int)$port_database_ch,
    null,
    MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT
);

// Fetch mapping
$sql = "SELECT id, original_url, msisdn, flow_id, shorteningurl, message_id 
        FROM url_mapping 
        WHERE id = ?
        LIMIT 1";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header("Location: https://komponentko.si");

    exit;
}

$row = $result->fetch_assoc();
$stmt->close();

// Log visit
$ip = $_SERVER['REMOTE_ADDR'] ?? null;
$ua = $_SERVER['HTTP_USER_AGENT'] ?? null;

$log_sql = "INSERT INTO page_visits 
            (mapping_id, short_url, original_url, msisdn, flow_id, shorteningurl, user_agent, ip_address, message_id)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

$stmt2 = $conn->prepare($log_sql);
$stmt2->bind_param(
    "issssssss",
    $row['id'],
    $cleanShortURL,
    $row['original_url'],
    $row['msisdn'],
    $row['flow_id'],
    $row['shorteningurl'],
    $ua,
    $ip,
    $row['message_id']
);
$stmt2->execute();
$stmt2->close();

$conn->close();

header("Location: " . $row['original_url']);
exit;

function decodeShortURL($shortCode) {
    $characters = 'aG7Xv0YqKL1FeuN3TjdRZPAMsC8w2xE9obn5JmkVWgOHilBQDcSyztfU46rh';
    $base = strlen($characters);
    $minLength = 5;
    $offset = pow($base, $minLength - 1);
    $value = 0;
    $len = strlen($shortCode);
    for ($i = 0; $i < $len; $i++) {
        $pos = strpos($characters, $shortCode[$i]);
        if ($pos === false) {
            return null;
        }
        $value = $value * $base + $pos;
    }
    $id = $value - $offset;
    return ($id > 0) ? $id : null;
}
?>