<?php
namespace Joomla\Component\Panggilan\Site\Helper;

defined('_JEXEC') or die;

class PdfHelper
{
    /**
     * Normalize URL for embedding
     *
     * @param   string  $url  Original URL
     * @return  string  Normalized URL
     */
    public static function normalizePdfUrl($url)
    {
        $url = trim($url);

        // Google Drive
        if (strpos($url, 'drive.google.com') !== false) {
            // Pattern 1: /file/d/{id}/view
            if (preg_match('#/file/d/([^/]+)/view#', $url, $matches)) {
                return 'https://drive.google.com/file/d/' . $matches[1] . '/preview';
            }
            // Pattern 2: open?id={id}
            if (preg_match('#id=([^&]+)#', $url, $matches)) {
                return 'https://drive.google.com/file/d/' . $matches[1] . '/preview';
            }
        }

        // Dropbox
        if (strpos($url, 'dropbox.com') !== false) {
            // Replace dl=0 or raw=0 with raw=1
            // Use native PDF viewer support
            if (strpos($url, '?') !== false) {
                // Remove existing params related to display
                $base = explode('?', $url)[0];
                return $base . '?raw=1';
            } else {
                return $url . '?raw=1';
            }
        }

        return $url;
    }

    /**
     * Detect if URL is likely embeddable in iframe
     *
     * @param   string  $url  Normalized URL
     * @return  bool
     */
    public static function detectEmbeddable($url)
    {
        // Google Drive Preview is embeddable
        if (strpos($url, 'drive.google.com') !== false && strpos($url, '/preview') !== false) {
            return true;
        }

        // Dropbox raw=1 is embeddable (browser PDF viewer)
        if (strpos($url, 'dropbox.com') !== false && strpos($url, 'raw=1') !== false) {
            return true;
        }

        // Direct PDF files (simple heuristic)
        if (strtolower(substr($url, -4)) === '.pdf') {
            return true;
        }

        // Default assumption: allow try, but might fail due to X-Frame-Options
        // If unknown domain, we can return true to "try" or false to be safe.
        // Given user requirement "fallback if fails", we can default to TRUE 
        // and let the onerror JS handler catch it. 
        // However, for strict explicit list:
        return true;
    }
}
