<?php
set_time_limit(600);
error_reporting(E_ALL);
ini_set('display_errors', 1);

function downloadFile($url, $path) {
    echo "Downloading from: $url to $path...<br>";
    $fp = fopen($path, 'w+');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 600);
    curl_setopt($ch, CURLOPT_FILE, $fp); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $res = curl_exec($ch); 
    if(!$res) { echo "Curl Error: " . curl_error($ch) . "<br>"; }
    curl_close($ch);
    fclose($fp);
}

function unzipFile($zipPath, $destDir, $libName) {
    $zip = new ZipArchive;
    if ($zip->open($zipPath) === TRUE) {
        $zip->extractTo($destDir);
        $zip->close();
        echo "Extracted $libName...<br>";

        // Try to find the extracted folder
        $dirs = glob($destDir . '/*', GLOB_ONLYDIR);
        foreach ($dirs as $dir) {
            $base = basename($dir);
            // Ignore existing target if already correct (e.g. 'tcpdf')
            if ($base === $libName) continue; 
            
            // Check content
            if ($libName === 'tcpdf' && (stripos($base, 'tcpdf') !== false || file_exists($dir.'/tcpdf.php'))) {
                rename($dir, $destDir . '/tcpdf');
                echo "Renamed $base to tcpdf<br>";
                return true;
            }
            if ($libName === 'phpqrcode' && (stripos($base, 'phpqrcode') !== false || file_exists($dir.'/qrlib.php'))) {
                rename($dir, $destDir . '/phpqrcode');
                echo "Renamed $base to phpqrcode<br>";
                return true;
            }
        }
        return true;
    } else {
        echo "Failed to unzip $zipPath<br>";
        return false;
    }
}

$libsDir = __DIR__ . '/libs';
if (!file_exists($libsDir)) mkdir($libsDir, 0777, true);

echo "<html><body style='font-family:sans-serif; padding: 20px;'>";
echo "<h2>Installing Libraries (Robust Mode)...</h2>";

// 1. Install TCPDF
if (!file_exists($libsDir . '/tcpdf/tcpdf.php')) {
    $tcpdfZip = $libsDir . '/tcpdf.zip';
    // Using main repo zip
    downloadFile('https://github.com/tecnickcom/TCPDF/archive/refs/heads/main.zip', $tcpdfZip);
    unzipFile($tcpdfZip, $libsDir, 'tcpdf');
    @unlink($tcpdfZip);
} else {
    echo "<p style='color:green'>TCPDF already installed.</p>";
}

// 2. Install PHP QR Code
if (!file_exists($libsDir . '/phpqrcode/qrlib.php')) {
    $qrZip = $libsDir . '/phpqrcode.zip';
    // Using a reliable mirror
    downloadFile('https://github.com/t0k4rt/phpqrcode/archive/refs/heads/master.zip', $qrZip);
    unzipFile($qrZip, $libsDir, 'phpqrcode');
    @unlink($qrZip);
} else {
    echo "<p style='color:green'>PHP QR Code already installed.</p>";
}

// Validation
$tcpdf_ok = file_exists($libsDir . '/tcpdf/tcpdf.php');
$qr_ok = file_exists($libsDir . '/phpqrcode/qrlib.php');

if ($tcpdf_ok && $qr_ok) {
    echo "<h3 style='color:green'>Installation Successful!</h3>";
    echo "<p>Both libraries are ready.</p>";
    echo "<a href='admin/dashboard.php' style='background:#28a745; color:white; padding:10px 20px; text-decoration:none; border-radius:5px;'>Go to Dashboard</a> ";
    echo "<a href='admin/manage_certificates.php' style='background:#007bff; color:white; padding:10px 20px; text-decoration:none; border-radius:5px; margin-left:10px;'>Go to Certificates</a>";
} else {
    echo "<h3 style='color:red'>Installation Partially Failed</h3>";
    if (!$tcpdf_ok) echo "<p>TCPDF missing. Check 'libs/tcpdf/tcpdf.php'.</p>";
    if (!$qr_ok) echo "<p>PHP QR Code missing. Check 'libs/phpqrcode/qrlib.php'.</p>";
    echo "<p>Check folder permissions or internet connection.</p>";
}
echo "</body></html>";
?>
