<?php
require_once 'config.php';

/**
 * Load URLs from JSON file
 */
function loadUrls() {
    $content = file_get_contents(URLS_FILE);
    return json_decode($content, true) ?: [];
}

/**
 * Save URLs to JSON file
 */
function saveUrls($urls) {
    return file_put_contents(URLS_FILE, json_encode($urls, JSON_PRETTY_PRINT));
}

/**
 * Load visits from JSON file
 */
function loadVisits() {
    $content = file_get_contents(VISITS_FILE);
    return json_decode($content, true) ?: [];
}

/**
 * Save visits to JSON file
 */
function saveVisitsData($visits) {
    return file_put_contents(VISITS_FILE, json_encode($visits, JSON_PRETTY_PRINT));
}

/**
 * Generate random short code
 */
function generateShortCode($length = 6) {
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $shortCode = '';
    for ($i = 0; $i < $length; $i++) {
        $shortCode .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $shortCode;
}

/**
 * Check if short code exists
 */
function shortCodeExists($shortCode) {
    $urls = loadUrls();
    foreach ($urls as $url) {
        if ($url['short_code'] === $shortCode) {
            return true;
        }
    }
    return false;
}

/**
 * Shorten URL
 */
function shortenUrl($originalUrl, $customCode = '') {
    $urls = loadUrls();
    
    // Generate or validate short code
    if (!empty($customCode)) {
        if (shortCodeExists($customCode)) {
            return ['error' => 'Custom code already exists'];
        }
        $shortCode = $customCode;
    } else {
        do {
            $shortCode = generateShortCode();
        } while (shortCodeExists($shortCode));
    }
    
    // Create URL entry
    $urlEntry = [
        'id' => uniqid(),
        'original_url' => $originalUrl,
        'short_code' => $shortCode,
        'short_url' => BASE_URL . '/' . $shortCode,
        'created_at' => date('Y-m-d H:i:s'),
        'visits' => 0
    ];
    
    // Add to URLs array
    $urls[] = $urlEntry;
    
    // Save to file
    if (saveUrls($urls)) {
        return [
            'success' => true,
            'short_url' => $urlEntry['short_url'],
            'short_code' => $shortCode
        ];
    } else {
        return ['error' => 'Failed to save URL'];
    }
}

/**
 * Delete URL
 */
function deleteUrl($shortCode) {
    $urls = loadUrls();
    $found = false;
    
    foreach ($urls as $key => $url) {
        if ($url['short_code'] === $shortCode) {
            unset($urls[$key]);
            $found = true;
            break;
        }
    }
    
    if ($found) {
        $urls = array_values($urls); // Reindex array
        if (saveUrls($urls)) {
            return ['success' => true];
        } else {
            return ['error' => 'Failed to delete URL'];
        }
    } else {
        return ['error' => 'URL not found'];
    }
}

/**
 * Save visit data
 */
function saveVisit($visitData) {
    $visits = loadVisits();
    $visits[] = $visitData;
    
    // Keep only last 10000 visits to prevent file from getting too large
    if (count($visits) > 10000) {
        $visits = array_slice($visits, -10000);
    }
    
    saveVisitsData($visits);
    
    // Update URL visit count
    $urls = loadUrls();
    foreach ($urls as &$url) {
        if ($url['short_code'] === $visitData['short_code']) {
            $url['visits']++;
            break;
        }
    }
    saveUrls($urls);
}

/**
 * Get visits with filter
 */
function getVisits($filter = 'all', $limit = 50) {
    $visits = loadVisits();
    
    // Filter visits
    if ($filter === 'human') {
        $visits = array_filter($visits, function($visit) {
            return $visit['is_human'] === true;
        });
    } elseif ($filter === 'bot') {
        $visits = array_filter($visits, function($visit) {
            return $visit['is_human'] === false;
        });
    }
    
    // Sort by timestamp (newest first)
    usort($visits, function($a, $b) {
        return strtotime($b['timestamp']) - strtotime($a['timestamp']);
    });
    
    // Limit results
    return array_slice($visits, 0, $limit);
}

/**
 * Get recent visits
 */
function getRecentVisits($limit = 10, $since = null) {
    $visits = loadVisits();
    
    // Filter by timestamp if since is provided
    if ($since) {
        $visits = array_filter($visits, function($visit) use ($since) {
            return strtotime($visit['timestamp']) > strtotime($since);
        });
    }
    
    // Sort by timestamp (newest first)
    usort($visits, function($a, $b) {
        return strtotime($b['timestamp']) - strtotime($a['timestamp']);
    });
    
    return array_slice($visits, 0, $limit);
}

/**
 * Get statistics
 */
function getStatistics() {
    $urls = loadUrls();
    $visits = loadVisits();
    
    $totalUrls = count($urls);
    $totalVisits = count($visits);
    
    $humanVisits = 0;
    $botVisits = 0;
    
    foreach ($visits as $visit) {
        if ($visit['is_human']) {
            $humanVisits++;
        } else {
            $botVisits++;
        }
    }
    
    return [
        'total_urls' => $totalUrls,
        'total_visits' => $totalVisits,
        'human_visits' => $humanVisits,
        'bot_visits' => $botVisits
    ];
}

/**
 * Get analytics data
 */
function getAnalytics() {
    $visits = loadVisits();
    
    $countries = [];
    $devices = [];
    $os = [];
    $networks = [];
    $isps = [];
    
    foreach ($visits as $visit) {
        // Countries
        $country = $visit['country'] ?? 'Unknown';
        $countries[$country] = ($countries[$country] ?? 0) + 1;
        
        // Devices
        $device = $visit['device_type'] ?? 'Unknown';
        $devices[$device] = ($devices[$device] ?? 0) + 1;
        
        // Operating Systems
        $osName = $visit['os'] ?? 'Unknown';
        $os[$osName] = ($os[$osName] ?? 0) + 1;
        
        // Networks
        $network = $visit['connection_type'] ?? 'Unknown';
        $networks[$network] = ($networks[$network] ?? 0) + 1;
        
        // ISPs
        $isp = $visit['isp'] ?? 'Unknown';
        $isps[$isp] = ($isps[$isp] ?? 0) + 1;
    }
    
    // Sort by count (descending)
    arsort($countries);
    arsort($devices);
    arsort($os);
    arsort($networks);
    arsort($isps);
    
    return [
        'countries' => $countries,
        'devices' => $devices,
        'os' => $os,
        'networks' => $networks,
        'isps' => $isps
    ];
}

/**
 * Time ago helper function
 */
function timeAgo($timestamp) {
    $time = time() - strtotime($timestamp);
    
    if ($time < 60) {
        return 'Just now';
    } elseif ($time < 3600) {
        $minutes = floor($time / 60);
        return $minutes . ' minute' . ($minutes > 1 ? 's' : '') . ' ago';
    } elseif ($time < 86400) {
        $hours = floor($time / 3600);
        return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
    } else {
        $days = floor($time / 86400);
        return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
    }
}
?>
