<?php
/**
 * Functions for tracking link clicks
 */

// Include database connection if not already included
if (!isset($conn)) {
    require_once __DIR__ . '/db.php';
    
    // If still no connection, try to create one
    if (!isset($conn)) {
        // Load central DB config
        $config = require __DIR__ . '/../config/database.php';
        
        $conn = new mysqli(
            $config['host'],
            $config['username'],
            $config['password'],
            $config['dbname']
        );
        // Set charset
        if (!mysqli_connect_errno()) {
            $conn->set_charset('utf8mb4');
        }
        
        if ($conn->connect_error) {
            error_log("Database connection failed: " . $conn->connect_error);
            die("Database connection failed. Please try again later.");
        }
    }
}

/**
 * Track a link click
 * @param string $url The URL that was clicked
 * @param string $title The title of the link (optional)
 * @return bool True on success, false on failure
 */
function trackLinkClick($url, $title = '') {
    global $conn;
    
    // Validate URL
    if (empty($url) || !filter_var($url, FILTER_VALIDATE_URL)) {
        error_log("Invalid URL provided for tracking: " . substr($url, 0, 100));
        return false;
    }
    
    // Sanitize inputs
    $url = filter_var($url, FILTER_SANITIZE_URL);
    $title = strip_tags($title);
    
    try {
        // Prepare the SQL statement
        $stmt = $conn->prepare("
            INSERT INTO link_stats (url, title, click_count, last_clicked) 
            VALUES (?, ?, 1, NOW())
            ON DUPLICATE KEY UPDATE 
            click_count = click_count + 1,
            last_clicked = NOW()
        ");
        
        if ($stmt === false) {
            throw new Exception("Failed to prepare statement: " . $conn->error);
        }
        
        $stmt->bind_param("ss", $url, $title);
        $result = $stmt->execute();
        $stmt->close();
        
        return $result;
    } catch (Exception $e) {
        error_log("Error tracking link click: " . $e->getMessage());
        return false;
    }
}

/**
 * Get most visited links
 * @param int $limit Number of links to return (default: 10)
 * @return array Array of link data or empty array on failure
 */
function getMostVisitedLinks($limit = 10) {
    global $conn;
    
    $limit = max(1, (int)$limit); // Ensure limit is at least 1
    $links = [];
    
    try {
        $sql = "
            SELECT url, title, click_count, last_clicked 
            FROM link_stats 
            ORDER BY click_count DESC, last_clicked DESC 
            LIMIT ?
        ";
        
        $stmt = $conn->prepare($sql);
        if ($stmt === false) {
            throw new Exception("Failed to prepare statement: " . $conn->error);
        }
        
        $stmt->bind_param("i", $limit);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $links[] = [
                'url' => $row['url'],
                'title' => $row['title'],
                'click_count' => (int)$row['click_count'],
                'last_clicked' => $row['last_clicked']
            ];
        }
        
        $stmt->close();
    } catch (Exception $e) {
        error_log("Error getting most visited links: " . $e->getMessage());
    }
    
    return $links;
}
