<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/visitor_tracker.php';

// Get the short code from URL or GET parameter
$shortCode = '';

// Check if code is passed from index.php
if (isset($_GET['code'])) {
    $shortCode = $_GET['code'];
} else {
    // Extract from URL path
    $request_uri = $_SERVER['REQUEST_URI'];
    $path_info = parse_url($request_uri, PHP_URL_PATH);
    
    // Get the script directory to properly handle subdirectories
    $script_dir = dirname($_SERVER['SCRIPT_NAME']);
    $script_dir = rtrim($script_dir, '/');
    
    // Remove the script directory from the path
    if ($script_dir !== '' && strpos($path_info, $script_dir) === 0) {
        $relative_path = substr($path_info, strlen($script_dir));
    } else {
        $relative_path = $path_info;
    }
    
    $segments = explode('/', trim($relative_path, '/'));
    $shortCode = $segments[0] ?? '';
}

// Clean the short code
$shortCode = preg_replace('/[^a-zA-Z0-9]/', '', $shortCode);

// Load URLs from JSON
$urls = loadUrls();

// Find the URL by short code
$targetUrl = null;
foreach ($urls as $url) {
    if ($url['short_code'] === $shortCode) {
        $targetUrl = $url['original_url'];
        break;
    }
}

if ($targetUrl) {
    // Track the visit
    $visitorData = trackVisitor($shortCode);
    
    // Save visit data
    saveVisit($visitorData);
    
    // Redirect to the original URL
    header('Location: ' . $targetUrl, true, 301);
    exit;
} else {
    // Short code not found, redirect to login page
    header('HTTP/1.0 404 Not Found');
    header('Location: login.php');
    exit;
}
?>
