<?php
include("db_config.php");  // Include your database configuration file

// Get the short code from the URL parameter (e.g., short_code=abcd123)
if (isset($_GET['short_code'])) {
    $short_code = $_GET['short_code'];
    
    // Prepare the SQL query to find the corresponding long URL and click count for the given short code
    $sql = "SELECT image1_long_url, image2_long_url, image1_link, image2_link, image1_clicks, image2_clicks FROM appstores WHERE image1_link = ? OR image2_link = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $short_code, $short_code);  // Binding the short code for both image1_link and image2_link
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // Fetch the row data
        $row = $result->fetch_assoc();
        
        // Initialize the long URL and click count variable
        $long_url = '';
        $clicks_column = '';
        
        // Check if the short code matches image1_link or image2_link and get the corresponding long URL and click column
        if ($short_code == $row['image1_link']) {
            $long_url = $row['image1_long_url'];
            $clicks_column = 'image1_clicks';
        } elseif ($short_code == $row['image2_link']) {
            $long_url = $row['image2_long_url'];
            $clicks_column = 'image2_clicks';
        }

        // Increment the click count for the respective short code
        $update_sql = "UPDATE appstores SET $clicks_column = $clicks_column + 1 WHERE image1_link = ? OR image2_link = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("ss", $short_code, $short_code);
        $update_stmt->execute();
        
        // Redirect to the long URL
        header("Location: $long_url");
        exit();
    } else {
        // If no matching short code found, show an error message
        echo "Invalid short code.";
    }
} else {
    // If no short code is passed, show an error message
    echo "Short code not provided.";
}

// Close the database connection
$conn->close();
?>
