<?php
// Get the requested URL path
$request_uri = $_SERVER['REQUEST_URI'];

// Prevent index.php from serving HTML for static assets (in case .htaccess routes everything here)
$ext = strtolower(pathinfo(parse_url($request_uri, PHP_URL_PATH), PATHINFO_EXTENSION));
if (in_array($ext, ['js', 'css', 'png', 'jpg', 'jpeg', 'gif', 'svg', 'json', 'ttf', 'woff', 'woff2', 'ico', 'map'])) {
    // If a static file is routed here, it means it doesn't exist on the server
    http_response_code(404);
    exit("404 Not Found");
}

// Handle smart link for /download or /invite
if (preg_match('/^\/(download|invite)/i', $request_uri)) {
    $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    
    if (stripos($userAgent, 'iphone') !== false || stripos($userAgent, 'ipad') !== false || stripos($userAgent, 'ipod') !== false) {
        // Redirect to Apple App Store
        header("Location: https://apps.apple.com/app/id6768265863");
        exit;
    } else if (stripos($userAgent, 'android') !== false) {
        // Redirect to Google Play Store
        header("Location: https://play.google.com/store/apps/details?id=com.scanner.kittyconnectai");
        exit;
    } else {
        // If desktop or unknown, redirect to the main homepage
        header("Location: /");
        exit;
    }
}

// Read the default Flutter Web index.html
// Make sure this index.php is placed in the same directory as index.html
$indexPath = __DIR__ . '/index.html';
if (!file_exists($indexPath)) {
    die("Error: index.html not found. Please ensure the Flutter web build 'index.html' is uploaded to the same folder as 'index.php'.");
}
$html = file_get_contents($indexPath);

// Check if the URL is a post, lost-found, or market deep link
if (preg_match('/^\/(post|lost-found|market)\/(.*)$/', $request_uri, $matches)) {
    $type = $matches[1];
    $pathParts = explode('/', $matches[2]);
    $itemId = end($pathParts);
    $itemId = explode('?', $itemId)[0]; // Remove query string if any
    
    // Default fallback tags
    $title = "KittyConnect AI";
    $desc = "Join the KittyConnect AI community! Share moments, find lost cats, and explore the marketplace.";
    $image = "https://kittyconnectai.akstool.com/icons/Icon-512.png";
    
    // Supabase credentials
    $supabaseUrl = 'https://qnxdlqlhekxyesimyjvs.supabase.co/rest/v1/';
    $anonKey = 'sb_publishable_TBvCEvzXzsCzbXL6ZOpSIA_p6Rf3i5H';
    
    // Determine the table based on URL type
    $table = 'posts';
    if ($type === 'lost-found') $table = 'lost_found_posts';
    if ($type === 'market') $table = 'market_listings';
    
    if ($itemId && strlen($itemId) > 10) { // basic check for valid UUID/ID
        $queryUrl = $supabaseUrl . $table . '?id=eq.' . $itemId . '&select=*';
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $queryUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // Supabase requires these headers
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "apikey: " . $anonKey,
            "Authorization: Bearer " . $anonKey
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        if ($response) {
            $data = json_decode($response, true);
            if (is_array($data) && count($data) > 0) {
                $post = $data[0];
                
                // Extract description/title based on the table
                $content = '';
                if (isset($post['content'])) $content = $post['content'];
                if (isset($post['title'])) $content = $post['title'];
                if (isset($post['description'])) $content = $post['description'];
                
                if (!empty($content)) {
                    $desc = htmlspecialchars(strip_tags($content));
                    $title = strlen($desc) > 60 ? substr($desc, 0, 60) . '...' : $desc;
                }
                
                // Extract image
                $raw_image = '';
                if (!empty($post['image_url'])) {
                    $raw_image = $post['image_url'];
                } elseif (!empty($post['images']) && is_array($post['images']) && count($post['images']) > 0) {
                    $raw_image = $post['images'][0]; // Market listings use array of images
                }
                
                if (!empty($raw_image)) {
                    // Fix spaces in URL which can break Facebook's scraper
                    $raw_image = str_replace(' ', '%20', $raw_image);
                    $image = htmlspecialchars($raw_image);
                }
            }
        }
    }
    
    $ext = strtolower(pathinfo(parse_url($image, PHP_URL_PATH), PATHINFO_EXTENSION));
    $mimeType = 'image/jpeg';
    if ($ext === 'png') $mimeType = 'image/png';
    if ($ext === 'webp') $mimeType = 'image/webp';
    if ($ext === 'gif') $mimeType = 'image/gif';
    
    $custom_meta = '
    <meta name="title" content="' . $title . '">
    <meta name="description" content="' . $desc . '">
    
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://kittyconnectai.akstool.com' . $request_uri . '">
    <meta property="og:title" content="' . $title . '">
    <meta property="og:description" content="' . $desc . '">
    <meta property="og:image" content="' . $image . '">
    <meta property="og:image:secure_url" content="' . $image . '">
    <meta property="og:image:type" content="' . $mimeType . '">
    <meta property="og:image:alt" content="' . $title . '">
    
    <meta property="twitter:card" content="summary_large_image">
    <meta property="twitter:url" content="https://kittyconnectai.akstool.com' . $request_uri . '">
    <meta property="twitter:title" content="' . $title . '">
    <meta property="twitter:description" content="' . $desc . '">
    <meta property="twitter:image" content="' . $image . '">
    <title>' . $title . '</title>
    ';
    
    // Inject the custom meta tags into the HTML by replacing any existing <title> tag, 
    // and injecting right before </head>
    $html = preg_replace('/<title>.*?<\/title>/is', '', $html); 
    $html = preg_replace('/<meta\s+(property|name)=["\'](og:|twitter:|description|title).*?["\'].*?>/is', '', $html);
    $html = str_replace('</head>', $custom_meta . "\n</head>", $html);
}

// Serve the final HTML (which perfectly boots up Flutter Web for humans, 
// and perfectly feeds Open Graph tags to Facebook/WhatsApp scrapers)
echo $html;
?>
